From 62d24a0320d6dc8f162523a76eca87393028554c Mon Sep 17 00:00:00 2001 From: Tim Date: Thu, 14 Sep 2023 09:02:42 -0500 Subject: [PATCH 1/5] Scc pheonix update (#4780) * removed the previous iteration * adding the new entities go files * taking out x-correlation-id and x-request-id * adding the documentation * test: fix the test build fail due to argument mismatch * updating the test files * test: fixing a bunch of tests for acceptance * fix: fixed the rules entities * feat: adding instance_settings as a data_source * Deleting scc_instance_settings as a resource * Taking out the instance provider validation * Changing the description between control_id and control_name * working on acceptance testing, need to address profile change later * edited intros * updated intros * addressing @hkantare comments * fixing the subcategory * fixing the Update portion of the resource_ibm_scc_profile * adding examples * secrets and doc update --------- Co-authored-by: Timothy-Yao Co-authored-by: Hadassa Romeus --- .secrets.baseline | 70 +- examples/ibm-scc/admin/README.md | 83 - examples/ibm-scc/admin/main.tf | 26 - examples/ibm-scc/admin/outputs.tf | 11 - examples/ibm-scc/admin/variables.tf | 17 - examples/ibm-scc/admin/versions.tf | 3 - examples/ibm-scc/configuration/README.md | 100 -- examples/ibm-scc/configuration/main.tf | 91 - examples/ibm-scc/configuration/outputs.tf | 24 - examples/ibm-scc/configuration/provider.tf | 8 - examples/ibm-scc/configuration/variables.tf | 16 - examples/ibm-scc/configuration/versions.tf | 3 - examples/ibm-scc/control_library/main.tf | 37 + examples/ibm-scc/control_library/variables.tf | 18 + examples/ibm-scc/findings/README.md | 119 -- examples/ibm-scc/findings/main.tf | 253 --- examples/ibm-scc/findings/outputs.tf | 9 - examples/ibm-scc/findings/variables.tf | 25 - examples/ibm-scc/findings/versions.tf | 3 - examples/ibm-scc/integration/main.tf | 6 + examples/ibm-scc/integration/outputs.tf | 6 + examples/ibm-scc/integration/variables.tf | 17 + examples/ibm-scc/posture-management/README.md | 191 --- examples/ibm-scc/posture-management/main.tf | 3 - .../ibm-scc/posture-management/outputs.tf | 0 .../ibm-scc/posture-management/provider.tf | 1 - .../posture-management/terraform.tfvars | 1 - .../ibm-scc/posture-management/variables.tf | 155 -- .../ibm-scc/posture-management/versions.tf | 3 - examples/ibm-scc/profile/main.tf | 41 + examples/ibm-scc/profile/variables.tf | 29 + examples/ibm-scc/report/main.tf | 32 + examples/ibm-scc/report/variables.tf | 11 + examples/ibm-scc/rule/main.tf | 16 + examples/ibm-scc/rule/variables.tf | 5 + go.mod | 83 +- go.sum | 11 +- ibm/acctest/acctest.go | 28 +- ibm/conns/config.go | 420 ++--- ibm/provider/provider.go | 121 +- ibm/service/scc/README.md | 9 +- .../data_source_ibm_scc_account_location.go | 124 +- ...ource_ibm_scc_account_location_settings.go | 58 +- ...ta_source_ibm_scc_account_location_test.go | 36 - .../data_source_ibm_scc_account_locations.go | 153 +- ...e_ibm_scc_account_notification_settings.go | 55 +- ..._scc_account_notification_settings_test.go | 34 - .../data_source_ibm_scc_control_library.go | 505 ++++++ ...ata_source_ibm_scc_control_library_test.go | 177 ++ .../data_source_ibm_scc_instance_settings.go | 162 ++ ...a_source_ibm_scc_instance_settings_test.go | 37 + .../scc/data_source_ibm_scc_latest_reports.go | 576 +++++++ ...ata_source_ibm_scc_latest_reports_test.go} | 16 +- .../scc/data_source_ibm_scc_profile.go | 595 +++++++ .../data_source_ibm_scc_profile_attachment.go | 435 +++++ ..._source_ibm_scc_profile_attachment_test.go | 239 +++ .../scc/data_source_ibm_scc_profile_test.go | 189 +++ .../scc/data_source_ibm_scc_provider_type.go | 222 +++ ...source_ibm_scc_provider_type_collection.go | 211 +++ ..._ibm_scc_provider_type_collection_test.go} | 15 +- ...a_source_ibm_scc_provider_type_instance.go | 115 ++ ...rce_ibm_scc_provider_type_instance_test.go | 90 + .../data_source_ibm_scc_provider_type_test.go | 46 + ibm/service/scc/data_source_ibm_scc_report.go | 354 ++++ .../data_source_ibm_scc_report_controls.go | 527 ++++++ ...ata_source_ibm_scc_report_controls_test.go | 39 + .../data_source_ibm_scc_report_evaluations.go | 481 ++++++ ..._source_ibm_scc_report_evaluations_test.go | 40 + .../data_source_ibm_scc_report_resources.go | 297 ++++ ...ta_source_ibm_scc_report_resources_test.go | 40 + .../scc/data_source_ibm_scc_report_rule.go | 146 ++ .../data_source_ibm_scc_report_rule_test.go | 41 + .../scc/data_source_ibm_scc_report_summary.go | 548 ++++++ ...data_source_ibm_scc_report_summary_test.go | 39 + .../scc/data_source_ibm_scc_report_tags.go | 116 ++ .../data_source_ibm_scc_report_tags_test.go | 39 + .../scc/data_source_ibm_scc_report_test.go | 39 + ...a_source_ibm_scc_report_violation_drift.go | 197 +++ ...rce_ibm_scc_report_violation_drift_test.go | 39 + ibm/service/scc/data_source_ibm_scc_rule.go | 758 +++++++++ .../scc/data_source_ibm_scc_rule_test.go | 130 ++ .../scc/resource_ibm_scc_account_settings.go | 338 +--- .../resource_ibm_scc_account_settings_test.go | 124 -- ...urce_ibm_scc_account_settings_validator.go | 24 - .../scc/resource_ibm_scc_control_library.go | 944 +++++++++++ .../resource_ibm_scc_control_library_test.go | 252 +++ ibm/service/scc/resource_ibm_scc_profile.go | 838 ++++++++++ .../resource_ibm_scc_profile_attachment.go | 905 ++++++++++ ...esource_ibm_scc_profile_attachment_test.go | 293 ++++ .../scc/resource_ibm_scc_profile_test.go | 264 +++ ...resource_ibm_scc_provider_type_instance.go | 266 +++ ...rce_ibm_scc_provider_type_instance_test.go | 165 ++ ibm/service/scc/resource_ibm_scc_rule.go | 1477 ++++++++++------- .../scc/resource_ibm_scc_rule_attachment.go | 340 +--- .../resource_ibm_scc_rule_attachment_test.go | 172 -- ...ource_ibm_scc_rule_attachment_validator.go | 24 - ibm/service/scc/resource_ibm_scc_rule_test.go | 184 +- .../scc/resource_ibm_scc_rule_validator.go | 30 - ibm/service/scc/resource_ibm_scc_template.go | 398 +---- .../resource_ibm_scc_template_attachment.go | 330 +--- ...source_ibm_scc_template_attachment_test.go | 158 -- ...e_ibm_scc_template_attachment_validator.go | 24 - .../scc/resource_ibm_scc_template_test.go | 118 -- .../resource_ibm_scc_template_validator.go | 46 - .../docs/d/scc_account_location.html.markdown | 50 - ...cc_account_location_settings.html.markdown | 27 - .../d/scc_account_locations.html.markdown | 38 - ...ccount_notification_settings.html.markdown | 27 - .../docs/d/scc_control_library.html.markdown | 133 ++ .../d/scc_instance_settings.html.markdown | 36 + .../docs/d/scc_latest_reports.html.markdown | 97 ++ website/docs/d/scc_profile.html.markdown | 152 ++ .../d/scc_profile_attachment.html.markdown | 117 ++ .../docs/d/scc_provider_type.html.markdown | 61 + ...scc_provider_type_collection.html.markdown | 44 + .../scc_provider_type_instance.html.markdown | 48 + website/docs/d/scc_report.html.markdown | 75 + .../docs/d/scc_report_controls.html.markdown | 105 ++ .../d/scc_report_evaluations.html.markdown | 92 + .../docs/d/scc_report_resources.html.markdown | 72 + website/docs/d/scc_report_rule.html.markdown | 56 + .../docs/d/scc_report_summary.html.markdown | 98 ++ website/docs/d/scc_report_tags.html.markdown | 41 + .../scc_report_violation_drift.html.markdown | 53 + website/docs/d/scc_rule.html.markdown | 162 ++ website/docs/d/scc_si_note.html.markdown | 123 -- website/docs/d/scc_si_notes.html.markdown | 125 -- .../docs/d/scc_si_occurrence.html.markdown | 106 -- .../docs/d/scc_si_occurrences.html.markdown | 106 -- website/docs/d/scc_si_providers.html.markdown | 46 - .../docs/r/scc_account_settings.html.markdown | 56 - .../docs/r/scc_control_library.html.markdown | 167 ++ website/docs/r/scc_profile.html.markdown | 186 +++ .../r/scc_profile_attachment.html.markdown | 112 ++ .../scc_provider_type_instance.html.markdown | 55 + website/docs/r/scc_rule.html.markdown | 353 ++-- .../docs/r/scc_rule_attachment.html.markdown | 91 - website/docs/r/scc_si_note.html.markdown | 198 --- .../docs/r/scc_si_occurrence.html.markdown | 142 -- website/docs/r/scc_template.html.markdown | 85 - .../r/scc_template_attachment.html.markdown | 92 - 141 files changed, 15089 insertions(+), 6317 deletions(-) delete mode 100644 examples/ibm-scc/admin/README.md delete mode 100644 examples/ibm-scc/admin/main.tf delete mode 100644 examples/ibm-scc/admin/outputs.tf delete mode 100644 examples/ibm-scc/admin/variables.tf delete mode 100644 examples/ibm-scc/admin/versions.tf delete mode 100644 examples/ibm-scc/configuration/README.md delete mode 100644 examples/ibm-scc/configuration/main.tf delete mode 100644 examples/ibm-scc/configuration/outputs.tf delete mode 100644 examples/ibm-scc/configuration/provider.tf delete mode 100644 examples/ibm-scc/configuration/variables.tf delete mode 100644 examples/ibm-scc/configuration/versions.tf create mode 100644 examples/ibm-scc/control_library/main.tf create mode 100644 examples/ibm-scc/control_library/variables.tf delete mode 100644 examples/ibm-scc/findings/README.md delete mode 100644 examples/ibm-scc/findings/main.tf delete mode 100644 examples/ibm-scc/findings/outputs.tf delete mode 100644 examples/ibm-scc/findings/variables.tf delete mode 100644 examples/ibm-scc/findings/versions.tf create mode 100644 examples/ibm-scc/integration/main.tf create mode 100644 examples/ibm-scc/integration/outputs.tf create mode 100644 examples/ibm-scc/integration/variables.tf delete mode 100644 examples/ibm-scc/posture-management/README.md delete mode 100644 examples/ibm-scc/posture-management/main.tf delete mode 100644 examples/ibm-scc/posture-management/outputs.tf delete mode 100644 examples/ibm-scc/posture-management/provider.tf delete mode 100644 examples/ibm-scc/posture-management/terraform.tfvars delete mode 100644 examples/ibm-scc/posture-management/variables.tf delete mode 100644 examples/ibm-scc/posture-management/versions.tf create mode 100644 examples/ibm-scc/profile/main.tf create mode 100644 examples/ibm-scc/profile/variables.tf create mode 100644 examples/ibm-scc/report/main.tf create mode 100644 examples/ibm-scc/report/variables.tf create mode 100644 examples/ibm-scc/rule/main.tf create mode 100644 examples/ibm-scc/rule/variables.tf delete mode 100644 ibm/service/scc/data_source_ibm_scc_account_location_test.go delete mode 100644 ibm/service/scc/data_source_ibm_scc_account_notification_settings_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_control_library.go create mode 100644 ibm/service/scc/data_source_ibm_scc_control_library_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_instance_settings.go create mode 100644 ibm/service/scc/data_source_ibm_scc_instance_settings_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_latest_reports.go rename ibm/service/scc/{data_source_ibm_scc_account_locations_test.go => data_source_ibm_scc_latest_reports_test.go} (52%) create mode 100644 ibm/service/scc/data_source_ibm_scc_profile.go create mode 100644 ibm/service/scc/data_source_ibm_scc_profile_attachment.go create mode 100644 ibm/service/scc/data_source_ibm_scc_profile_attachment_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_profile_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_provider_type.go create mode 100644 ibm/service/scc/data_source_ibm_scc_provider_type_collection.go rename ibm/service/scc/{data_source_ibm_scc_account_location_settings_test.go => data_source_ibm_scc_provider_type_collection_test.go} (50%) create mode 100644 ibm/service/scc/data_source_ibm_scc_provider_type_instance.go create mode 100644 ibm/service/scc/data_source_ibm_scc_provider_type_instance_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_provider_type_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_controls.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_controls_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_evaluations.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_evaluations_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_resources.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_resources_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_rule.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_rule_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_summary.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_summary_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_tags.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_tags_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_violation_drift.go create mode 100644 ibm/service/scc/data_source_ibm_scc_report_violation_drift_test.go create mode 100644 ibm/service/scc/data_source_ibm_scc_rule.go create mode 100644 ibm/service/scc/data_source_ibm_scc_rule_test.go delete mode 100644 ibm/service/scc/resource_ibm_scc_account_settings_test.go delete mode 100644 ibm/service/scc/resource_ibm_scc_account_settings_validator.go create mode 100644 ibm/service/scc/resource_ibm_scc_control_library.go create mode 100644 ibm/service/scc/resource_ibm_scc_control_library_test.go create mode 100644 ibm/service/scc/resource_ibm_scc_profile.go create mode 100644 ibm/service/scc/resource_ibm_scc_profile_attachment.go create mode 100644 ibm/service/scc/resource_ibm_scc_profile_attachment_test.go create mode 100644 ibm/service/scc/resource_ibm_scc_profile_test.go create mode 100644 ibm/service/scc/resource_ibm_scc_provider_type_instance.go create mode 100644 ibm/service/scc/resource_ibm_scc_provider_type_instance_test.go delete mode 100644 ibm/service/scc/resource_ibm_scc_rule_attachment_test.go delete mode 100644 ibm/service/scc/resource_ibm_scc_rule_attachment_validator.go delete mode 100644 ibm/service/scc/resource_ibm_scc_rule_validator.go delete mode 100644 ibm/service/scc/resource_ibm_scc_template_attachment_test.go delete mode 100644 ibm/service/scc/resource_ibm_scc_template_attachment_validator.go delete mode 100644 ibm/service/scc/resource_ibm_scc_template_test.go delete mode 100644 ibm/service/scc/resource_ibm_scc_template_validator.go delete mode 100644 website/docs/d/scc_account_location.html.markdown delete mode 100644 website/docs/d/scc_account_location_settings.html.markdown delete mode 100644 website/docs/d/scc_account_locations.html.markdown delete mode 100644 website/docs/d/scc_account_notification_settings.html.markdown create mode 100644 website/docs/d/scc_control_library.html.markdown create mode 100644 website/docs/d/scc_instance_settings.html.markdown create mode 100644 website/docs/d/scc_latest_reports.html.markdown create mode 100644 website/docs/d/scc_profile.html.markdown create mode 100644 website/docs/d/scc_profile_attachment.html.markdown create mode 100644 website/docs/d/scc_provider_type.html.markdown create mode 100644 website/docs/d/scc_provider_type_collection.html.markdown create mode 100644 website/docs/d/scc_provider_type_instance.html.markdown create mode 100644 website/docs/d/scc_report.html.markdown create mode 100644 website/docs/d/scc_report_controls.html.markdown create mode 100644 website/docs/d/scc_report_evaluations.html.markdown create mode 100644 website/docs/d/scc_report_resources.html.markdown create mode 100644 website/docs/d/scc_report_rule.html.markdown create mode 100644 website/docs/d/scc_report_summary.html.markdown create mode 100644 website/docs/d/scc_report_tags.html.markdown create mode 100644 website/docs/d/scc_report_violation_drift.html.markdown create mode 100644 website/docs/d/scc_rule.html.markdown delete mode 100644 website/docs/d/scc_si_note.html.markdown delete mode 100644 website/docs/d/scc_si_notes.html.markdown delete mode 100644 website/docs/d/scc_si_occurrence.html.markdown delete mode 100644 website/docs/d/scc_si_occurrences.html.markdown delete mode 100644 website/docs/d/scc_si_providers.html.markdown delete mode 100644 website/docs/r/scc_account_settings.html.markdown create mode 100644 website/docs/r/scc_control_library.html.markdown create mode 100644 website/docs/r/scc_profile.html.markdown create mode 100644 website/docs/r/scc_profile_attachment.html.markdown create mode 100644 website/docs/r/scc_provider_type_instance.html.markdown delete mode 100644 website/docs/r/scc_rule_attachment.html.markdown delete mode 100644 website/docs/r/scc_si_note.html.markdown delete mode 100644 website/docs/r/scc_si_occurrence.html.markdown delete mode 100644 website/docs/r/scc_template.html.markdown delete mode 100644 website/docs/r/scc_template_attachment.html.markdown diff --git a/.secrets.baseline b/.secrets.baseline index 55f7c7981a..70af282b73 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "go.mod|go.sum|.*.map|^.secrets.baseline$", "lines": null }, - "generated_at": "2023-09-11T17:15:43Z", + "generated_at": "2023-09-14T05:19:33Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -627,6 +627,16 @@ "verified_result": null } ], + "examples/ibm-scc/profile/main.tf": [ + { + "hashed_secret": "ba02c5a1aad447298fcfbd962a953e7706b8b430", + "is_secret": false, + "is_verified": false, + "line_number": 25, + "type": "Hex High Entropy String", + "verified_result": null + } + ], "examples/ibm-schematics/README.md": [ { "hashed_secret": "5ffafdbd72224c86c3601bacfa0b6f04f308b9f6", @@ -722,7 +732,7 @@ "hashed_secret": "731438016c5ab94431f61820f35e3ae5f8ad6004", "is_secret": false, "is_verified": false, - "line_number": 355, + "line_number": 353, "type": "Secret Keyword", "verified_result": null }, @@ -730,7 +740,7 @@ "hashed_secret": "12da2e35d6b50c902c014f1ab9e3032650368df7", "is_secret": false, "is_verified": false, - "line_number": 361, + "line_number": 359, "type": "Secret Keyword", "verified_result": null }, @@ -738,7 +748,7 @@ "hashed_secret": "813274ccae5b6b509379ab56982d862f7b5969b6", "is_secret": false, "is_verified": false, - "line_number": 1067, + "line_number": 1065, "type": "Base64 High Entropy String", "verified_result": null } @@ -748,7 +758,7 @@ "hashed_secret": "9184b0c38101bf24d78b2bb0d044deb1d33696fc", "is_secret": false, "is_verified": false, - "line_number": 134, + "line_number": 130, "type": "Secret Keyword", "verified_result": null }, @@ -756,7 +766,7 @@ "hashed_secret": "c427f185ddcb2440be9b77c8e45f1cd487a2e790", "is_secret": false, "is_verified": false, - "line_number": 1468, + "line_number": 1427, "type": "Base64 High Entropy String", "verified_result": null }, @@ -764,7 +774,7 @@ "hashed_secret": "1f7e33de15e22de9d2eaf502df284ed25ca40018", "is_secret": false, "is_verified": false, - "line_number": 1536, + "line_number": 1494, "type": "Secret Keyword", "verified_result": null }, @@ -772,7 +782,7 @@ "hashed_secret": "1f614c2eb6b3da22d89bd1b9fd47d7cb7c8fc670", "is_secret": false, "is_verified": false, - "line_number": 3433, + "line_number": 3248, "type": "Secret Keyword", "verified_result": null }, @@ -780,7 +790,7 @@ "hashed_secret": "7abfce65b8504403afc25c9790f358d513dfbcc6", "is_secret": false, "is_verified": false, - "line_number": 3446, + "line_number": 3261, "type": "Secret Keyword", "verified_result": null }, @@ -788,7 +798,7 @@ "hashed_secret": "0c2d85bf9a9b1579b16f220a4ea8c3d62b2e24b1", "is_secret": false, "is_verified": false, - "line_number": 3487, + "line_number": 3302, "type": "Secret Keyword", "verified_result": null } @@ -826,7 +836,7 @@ "hashed_secret": "c8b6f5ef11b9223ac35a5663975a466ebe7ebba9", "is_secret": false, "is_verified": false, - "line_number": 1730, + "line_number": 1757, "type": "Secret Keyword", "verified_result": null }, @@ -834,7 +844,7 @@ "hashed_secret": "8abf4899c01104241510ba87685ad4de76b0c437", "is_secret": false, "is_verified": false, - "line_number": 1736, + "line_number": 1763, "type": "Secret Keyword", "verified_result": null } @@ -2865,6 +2875,36 @@ "verified_result": null } ], + "ibm/service/scc/data_source_ibm_scc_provider_type_instance_test.go": [ + { + "hashed_secret": "83747cea2b26d7652ed39218ddcdb1461c570535", + "is_secret": false, + "is_verified": false, + "line_number": 80, + "type": "Hex High Entropy String", + "verified_result": null + } + ], + "ibm/service/scc/data_source_ibm_scc_provider_type_test.go": [ + { + "hashed_secret": "83747cea2b26d7652ed39218ddcdb1461c570535", + "is_secret": false, + "is_verified": false, + "line_number": 43, + "type": "Hex High Entropy String", + "verified_result": null + } + ], + "ibm/service/scc/resource_ibm_scc_provider_type_instance_test.go": [ + { + "hashed_secret": "83747cea2b26d7652ed39218ddcdb1461c570535", + "is_secret": false, + "is_verified": false, + "line_number": 95, + "type": "Hex High Entropy String", + "verified_result": null + } + ], "ibm/service/schematics/data_source_ibm_schematics_action.go": [ { "hashed_secret": "49f3bb8f759241df51c899d3725d877bad58f66e", @@ -3556,7 +3596,7 @@ "hashed_secret": "4d55af37dbbb6a42088d917caa1ca25428ec42c9", "is_secret": false, "is_verified": false, - "line_number": 797, + "line_number": 788, "type": "Secret Keyword", "verified_result": null } @@ -3862,7 +3902,7 @@ "hashed_secret": "d47dcacc720a39e236679ac3e311a0d58bb6519e", "is_secret": false, "is_verified": false, - "line_number": 161, + "line_number": 153, "type": "Secret Keyword", "verified_result": null }, @@ -3870,7 +3910,7 @@ "hashed_secret": "e66e7d67fdf3c596c435fc7828b13205e4950a0f", "is_secret": false, "is_verified": false, - "line_number": 163, + "line_number": 155, "type": "Secret Keyword", "verified_result": null } diff --git a/examples/ibm-scc/admin/README.md b/examples/ibm-scc/admin/README.md deleted file mode 100644 index f2110f4c63..0000000000 --- a/examples/ibm-scc/admin/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# Example for AdminServiceApiV1 - -This example illustrates how to use the AdminServiceApiV1 - -These types of resources are supported: - - -## Usage - -To run this example you need to execute: - -```bash -$ terraform init -$ terraform plan -$ terraform apply -``` - -Run `terraform destroy` when you don't need these resources. - - -## AdminServiceApiV1 resources -```hcl -resource "ibm_scc_account_settings" "ibm_scc_account_settings_instance" { - location_id = var.ibm_scc_account_settings_location_id -} -``` - -## AdminServiceApiV1 Data sources - -scc_account_location_settings data source: - -```hcl -data "scc_account_location_settings" "scc_account_location_settings_instance" { -} -``` -scc_account_location data source: - -```hcl -data "scc_account_location" "scc_account_location_instance" { - location_id = var.scc_account_location_location_id -} -``` -scc_account_locations data source: - -```hcl -data "scc_account_locations" "scc_account_locations_instance" { -} -``` - -## Assumptions - -- The default location has already been set for you - -## Notes - -- Running `terraform apply` will output the location your account is operating in as well as the available locations for your Security and Compliance center - -## Requirements - -| Name | Version | -|------|---------| -| terraform | ~> 0.12 | - -## Providers - -| Name | Version | -|------|---------| -| ibm | 1.13.1 | - -## Inputs - -| Name | Description | Type | Required | -|------|-------------|------|---------| -| ibmcloud\_api\_key | IBM Cloud API key | `string` | true | -| location_id | The programatic ID of the location that you want to work in. | `string` | true | - -## Outputs - -| Name | Description | -|------|-------------| -| available_locations | The available Security and Compliance Center locations | -| location_details | The details of a given location | -| current_location_settings_details | The details of the current account settings | diff --git a/examples/ibm-scc/admin/main.tf b/examples/ibm-scc/admin/main.tf deleted file mode 100644 index 060649b0d3..0000000000 --- a/examples/ibm-scc/admin/main.tf +++ /dev/null @@ -1,26 +0,0 @@ -provider "ibm" { - ibmcloud_api_key = var.ibmcloud_api_key -} - -// Update the current account settings -resource "ibm_scc_account_settings" "ibm_scc_account_settings_instance" { - // Optional input of location - location { - location_id = "us" - } - // Optional input of event_notifications - event_notifications { - // instance_crn = "instance_crn" - } -} - -// Read the current account location settings -data "ibm_scc_account_settings" "scc_account_location_settings_instance" {} - -// Read the details of a given location -data "ibm_scc_account_location" "scc_account_location_instance" { - location_id = var.scc_account_location_location_id -} - -// Read all the available locations -data "ibm_scc_account_locations" "scc_account_locations_instance" {} diff --git a/examples/ibm-scc/admin/outputs.tf b/examples/ibm-scc/admin/outputs.tf deleted file mode 100644 index b6f652b0f4..0000000000 --- a/examples/ibm-scc/admin/outputs.tf +++ /dev/null @@ -1,11 +0,0 @@ -output "available_locations" { - value = data.ibm_scc_account_locations.scc_account_locations_instance.locations -} - -output "location_details" { - value = data.ibm_scc_account_location.scc_account_location_instance -} - -output "current_location_settings_details" { - value = data.ibm_scc_account_settings.scc_account_location_settings_instance -} diff --git a/examples/ibm-scc/admin/variables.tf b/examples/ibm-scc/admin/variables.tf deleted file mode 100644 index 7442d2e2d6..0000000000 --- a/examples/ibm-scc/admin/variables.tf +++ /dev/null @@ -1,17 +0,0 @@ -variable "ibmcloud_api_key" { - description = "IBM Cloud API key" - type = string -} - -// Data source arguments for scc_account_location -variable "scc_account_location_location_id" { - description = "The programatic ID of the location that you want to work in." - type = string - default = "us" -} - -// Resource arguments for ibm_scc_account_settings -variable "ibm_scc_account_settings_location_id" { - description = "The programatic ID of the location that you want to work in." - type = string -} diff --git a/examples/ibm-scc/admin/versions.tf b/examples/ibm-scc/admin/versions.tf deleted file mode 100644 index d9b6f790b9..0000000000 --- a/examples/ibm-scc/admin/versions.tf +++ /dev/null @@ -1,3 +0,0 @@ -terraform { - required_version = ">= 0.12" -} diff --git a/examples/ibm-scc/configuration/README.md b/examples/ibm-scc/configuration/README.md deleted file mode 100644 index 3218c5d6d3..0000000000 --- a/examples/ibm-scc/configuration/README.md +++ /dev/null @@ -1,100 +0,0 @@ -# Example for ConfigurationGovernanceV1 - -This example illustrates how to use the ConfigurationGovernanceV1 - -These types of resources are supported: - -* scc_template -* scc_template_attachment -* scc_rule -* scc_rule_attachment - -## Usage - -To run this example you need to execute: - -```bash -$ terraform init -$ terraform plan -$ terraform apply -``` - -Run `terraform destroy` when you don't need these resources. - - -## ConfigurationGovernanceV1 resources - -scc_template resource: - -```hcl -resource "scc_template" "scc_template_instance" { - template = var.scc_template_template -} -``` -scc_template_attachment resource: - -```hcl -resource "scc_template_attachment" "scc_template_attachment_instance" { - template_id = var.scc_template_attachment_template_id - attachment = var.scc_template_attachment_attachment -} -``` -scc_rule resource: - -```hcl -resource "scc_rule" "scc_rule_instance" { - rule = var.scc_rule_rule -} -``` -scc_rule_attachment resource: - -```hcl -resource "scc_rule_attachment" "scc_rule_attachment_instance" { - rule_id = var.scc_rule_attachment_rule_id - attachment = var.scc_rule_attachment_attachment -} -``` - -## ConfigurationGovernanceV1 Data sources - - -## Assumptions - -1. TODO - -## Notes - -1. TODO - -## Requirements - -| Name | Version | -|------|---------| -| terraform | ~> 0.12 | - -## Providers - -| Name | Version | -|------|---------| -| ibm | 1.13.1 | - -## Inputs - -| Name | Description | Type | Required | -|------|-------------|------|---------| -| ibmcloud\_api\_key | IBM Cloud API key | `string` | true | -| template | A list of templates to be created. | `list()` | true | -| template_id | The UUID that uniquely identifies the template. | `string` | true | -| attachment | | `list()` | true | -| rule | A list of rules to be created. | `list()` | true | -| rule_id | The UUID that uniquely identifies the rule. | `string` | true | -| attachment | | `list()` | true | - -## Outputs - -| Name | Description | -|------|-------------| -| scc_template | scc_template object | -| scc_template_attachment | scc_template_attachment object | -| scc_rule | scc_rule object | -| scc_rule_attachment | scc_rule_attachment object | diff --git a/examples/ibm-scc/configuration/main.tf b/examples/ibm-scc/configuration/main.tf deleted file mode 100644 index 2c191020e3..0000000000 --- a/examples/ibm-scc/configuration/main.tf +++ /dev/null @@ -1,91 +0,0 @@ -provider "ibm" { - ibmcloud_api_key = var.ibmcloud_api_key -} - -// Provision scc_template resource instance -resource "ibm_scc_template" "scc_template_instance" { - account_id = var.account_id - name = "Terraform template" - description = "description" - target { - service_name = "cloud-object-storage" - resource_kind = "bucket" - additional_target_attributes { - name = "location" - value = "us-south" - } - } - customized_defaults { - property = "activity_tracking.write_data_events" - value = "true" - } - customized_defaults { - property = "activity_tracking.read_data_events" - value = "true" - } -} - -// Provision scc_template_attachment resource instance -resource "ibm_scc_template_attachment" "scc_template_attachment_instance" { - template_id = ibm_scc_template.scc_template_instance.id - account_id = var.account_id - included_scope { - note = "account id" - scope_id = var.account_id - scope_type = "account" - } - excluded_scopes { - note = "Automated Testing resource group" - scope_id = var.resource_group_id - scope_type = "account.resource_group" - } - depends_on = [ - ibm_scc_template.scc_template_instance // ensures that the template is created first - ] -} -// Provision scc_rule resource instance -resource "ibm_scc_rule" "scc_rule_instance" { - account_id = var.account_id - name = "Terraform rule" - description = "description" - target { - service_name = "cloud-object-storage" - resource_kind = "bucket" - additional_target_attributes { - name = "location" - operator = "string_equals" - value = "us-south" - } - } - labels = ["example"] - required_config { - description = "test config" - and { - property = "storage_class" - operator = "string_equals" - value = "smart" - } - } - enforcement_actions { - action = "disallow" - } -} - -// Provision scc_rule_attachment resource instance -resource "ibm_scc_rule_attachment" "scc_rule_attachment_instance" { - rule_id = ibm_scc_rule.scc_rule_instance.id - account_id = var.account_id - included_scope { - note = "account id" - scope_id = var.account_id - scope_type = "account" - } - excluded_scopes { - note = "Automated Testing resource group" - scope_id = var.resource_group_id - scope_type = "account.resource_group" - } - depends_on = [ - ibm_scc_rule.scc_rule_instance // ensures that the rule is created first - ] -} \ No newline at end of file diff --git a/examples/ibm-scc/configuration/outputs.tf b/examples/ibm-scc/configuration/outputs.tf deleted file mode 100644 index 571ddaa6f4..0000000000 --- a/examples/ibm-scc/configuration/outputs.tf +++ /dev/null @@ -1,24 +0,0 @@ -// This allows scc_template data to be referenced by other resources and the terraform CLI -// Modify this if only certain data should be exposed -output "ibm_scc_template" { - value = ibm_scc_template.scc_template_instance - description = "scc_template resource instance" -} -// This allows scc_template_attachment data to be referenced by other resources and the terraform CLI -// Modify this if only certain data should be exposed -output "ibm_scc_template_attachment" { - value = ibm_scc_template_attachment.scc_template_attachment_instance - description = "scc_template_attachment resource instance" -} -// This allows scc_rule data to be referenced by other resources and the terraform CLI -// Modify this if only certain data should be exposed -output "ibm_scc_rule" { - value = ibm_scc_rule.scc_rule_instance - description = "scc_rule resource instance" -} -// This allows scc_rule_attachment data to be referenced by other resources and the terraform CLI -// Modify this if only certain data should be exposed -output "ibm_scc_rule_attachment" { - value = ibm_scc_rule_attachment.scc_rule_attachment_instance - description = "scc_rule_attachment resource instance" -} diff --git a/examples/ibm-scc/configuration/provider.tf b/examples/ibm-scc/configuration/provider.tf deleted file mode 100644 index 41fe3e3740..0000000000 --- a/examples/ibm-scc/configuration/provider.tf +++ /dev/null @@ -1,8 +0,0 @@ -terraform { - required_providers { - ibm = { - source = "github.ibm.com/cloudengineering/ibm" - version = "0.0.1" - } - } -} \ No newline at end of file diff --git a/examples/ibm-scc/configuration/variables.tf b/examples/ibm-scc/configuration/variables.tf deleted file mode 100644 index 6440a3aea8..0000000000 --- a/examples/ibm-scc/configuration/variables.tf +++ /dev/null @@ -1,16 +0,0 @@ -variable "ibmcloud_api_key" { - description = "IBM Cloud API key" - type = string -} - -// Resource arguments - -variable "account_id" { - description = "The ID of the account to target found in: https://cloud.ibm.com/account/settings" - type = string -} - -variable "resource_group_id" { - description = "The ID of the account's resource group to target found in: https://cloud.ibm.com/account/resource-groups" - type = string -} diff --git a/examples/ibm-scc/configuration/versions.tf b/examples/ibm-scc/configuration/versions.tf deleted file mode 100644 index ee0f9705a2..0000000000 --- a/examples/ibm-scc/configuration/versions.tf +++ /dev/null @@ -1,3 +0,0 @@ -terraform { - required_version = ">= 0.12" -} \ No newline at end of file diff --git a/examples/ibm-scc/control_library/main.tf b/examples/ibm-scc/control_library/main.tf new file mode 100644 index 0000000000..cfcf5419e6 --- /dev/null +++ b/examples/ibm-scc/control_library/main.tf @@ -0,0 +1,37 @@ +resource "ibm_scc_control_library" "scc_demo_control_library" { + control_library_name = var.scc_control_library_name + control_library_description = var.scc_control_library_description + control_library_type = "custom" + control_library_version = var.scc_control_version + version_group_label = "d755830f-1d83-4fab-b5d5-1dfb2b0dad1f" + latest = true + controls { + control_id = "032a81ca-6ef7-4ac2-81ac-20ee4a780e3b" + control_name = var.scc + control_description = "Boundary Protection" + control_category = "System and Communications Protection" + control_requirement = true + status = "enabled" + control_docs {} + control_specifications { + control_specification_id = "5c7d6f88-a92f-4734-9b49-bd22b0900184" + control_specification_description = "IBM Cloud" + component_id = "iam-identity" + component_name = "IAM Identity Service" + environment = "ibm-cloud" + assessments { + assessment_type = "automated" + assessment_method = "ibm-cloud-rule" + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_description = "All assessments related to iam_identity" + parameters { + parameter_name = "session_invalidation_in_seconds" + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_type = "numeric" + } + } + responsibility = "user" + } + } +} + diff --git a/examples/ibm-scc/control_library/variables.tf b/examples/ibm-scc/control_library/variables.tf new file mode 100644 index 0000000000..50bf4ae3f4 --- /dev/null +++ b/examples/ibm-scc/control_library/variables.tf @@ -0,0 +1,18 @@ +variable "scc_control_library_name" { + description = "The name of the control library." + type = string + default = "scc_demo_control_library" +} + +variable "scc_control_library_description" { + description = "The description of the control library." + type = string + default = "This control library was made for demo purposes" +} + +variable "scc_control_library_version" { + description = "The version of the control library" + type = string + default = "0.0.1" +} + diff --git a/examples/ibm-scc/findings/README.md b/examples/ibm-scc/findings/README.md deleted file mode 100644 index 1019c721b5..0000000000 --- a/examples/ibm-scc/findings/README.md +++ /dev/null @@ -1,119 +0,0 @@ -# Example for FindingsV1 - -This example illustrates how to use the FindingsV1 - -These types of resources are supported: - -* scc_si_note - -## Usage - -To run this example you need to execute: - -```bash -$ terraform init -$ terraform plan -$ terraform apply -``` - -Run `terraform destroy` when you don't need these resources. - - -## FindingsV1 resources - -scc_si_note resource: - -```hcl -resource "ibm_scc_si_note" "ts-card-finding" { - provider_id = "scc" - short_description = "Security Threat" - long_description = "Security Threat found in your account" - kind = "CARD" - note_id = "ts-card-finding" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - card { - section = "Security" - title = "Threats" - subtitle = "Summary of Security Threats" - finding_note_names = ["providers/scc/notes/finding"] - elements { - kind = "TIME_SERIES" - text = "count" - default_time_range = "3d" - value_types { - text = "count" - finding_note_names = ["providers/scc/notes/finding"] - kind = "FINDING_COUNT" - } - } - } -} -``` - -## FindingsV1 Data sources - -scc_si_providers data source: - -```hcl -data "ibm_scc_si_providers" "providers" { - limit = 4 -} -``` -scc_si_notes data source: - -```hcl -data "ibm_scc_si_notes" "notes" { - page_size = 3 -} -``` -scc_si_note data source: - -```hcl -data "ibm_scc_si_note" "scc_si_note" { - note_id = "note_id" - provider_id = "provider_id" -} -``` - -## Requirements - -| Name | Version | -|------|---------| -| terraform | ~> 0.12 | - -## Providers - -| Name | Version | -|------|---------| -| ibm | 1.13.1 | - -## Inputs - -| Name | Description | Type | Required | -|------|-------------|------|---------| -| ibmcloud\_api\_key | IBM Cloud API key | `string` | true | -| provider_id | Part of the parent. This field contains the provider ID. For example: providers/{provider_id}. | `string` | true | -| short_description | A one sentence description of your note. | `string` | true | -| long_description | A more detailed description of your note. | `string` | true | -| kind | The type of note. Use this field to filter notes and occurences by kind. - FINDING: The note and occurrence represent a finding. - KPI: The note and occurrence represent a KPI value. - CARD: The note represents a card showing findings and related metric values. - CARD_CONFIGURED: The note represents a card configured for a user account. - SECTION: The note represents a section in a dashboard. | `string` | true | -| note_id | The ID of the note. | `string` | true | -| reported_by | The entity reporting a note. | `` | true | -| related_url | | `list()` | false | -| shared | True if this note can be shared by multiple accounts. | `bool` | false | -| finding | FindingType provides details about a finding note. | `` | false | -| kpi | KpiType provides details about a KPI note. | `` | false | -| card | Card provides details about a card kind of note. | `` | false | -| section | Card provides details about a card kind of note. | `` | false | -| id | The ID of the provider. | `string` | false | -| provider_id | Part of the parent. This field contains the provider ID. For example: providers/{provider_id}. | `string` | true | -| note_id | Second part of note `name`: providers/{provider_id}/notes/{note_id}. | `string` | true | - -## Outputs - -| Name | Description | -|------|-------------| -| scc_si_note | scc_si_note object | diff --git a/examples/ibm-scc/findings/main.tf b/examples/ibm-scc/findings/main.tf deleted file mode 100644 index 7519ffbf2e..0000000000 --- a/examples/ibm-scc/findings/main.tf +++ /dev/null @@ -1,253 +0,0 @@ -provider "ibm" { - ibmcloud_api_key = var.ibmcloud_api_key -} - -# Provision scc_si_providers data source instance - -data "ibm_scc_si_providers" "providers" { - limit = 4 -} - -# Provision scc_si_notes data source instance - -data "ibm_scc_si_notes" "notes" { - provider_id = var.provider_id - page_size = 3 -} - -# Provision scc_si_note data source instance - -data "ibm_scc_si_note" "note" { - provider_id = var.provider_id - note_id = var.note_id -} - -# Provision scc_si_occurrences data source instance -data "ibm_scc_si_occurrences" "occurrences" { - provider_id = var.provider_id - page_size = 4 -} - -# Provision scc_si_occurrence data source instance - -data "ibm_scc_si_occurrence" "occurrence" { - provider_id = var.provider_id - occurrence_id = var.occurrence_id -} - -# Provision scc_si_note resource instance - Kind FINDING -resource "ibm_scc_si_note" "finding" { - provider_id = var.provider_id - short_description = "Security Threat" - long_description = "Security Threat found in your account" - kind = "FINDING" - note_id = "finding" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - finding { - severity = "LOW" - next_steps { - title = "Security Threat" - url = "https://cloud.ibm.com/security-compliance/findings" - } - } -} - -# Provision scc_si_note resource instance - Kind KPI -resource "ibm_scc_si_note" "kpi" { - provider_id = var.provider_id - short_description = "Security Threat" - long_description = "Security Threat found in your account" - kind = "KPI" - note_id = "kpi" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - kpi { - aggregation_type = "SUM" - } -} - -# Provision scc_si_note resource instance - Kind Card (NUMERIC - FINDING_COUNT) -resource "ibm_scc_si_note" "num-card-finding" { - provider_id = var.provider_id - short_description = "Security Threat" - long_description = "Security Threat found in your account" - kind = "CARD" - note_id = "num-card-finding" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - card { - section = "Terraform Insights" - title = "NUMERIC Finding Card" - subtitle = "Summary of Findings" - finding_note_names = ["${var.account_id}/providers/scc/notes/finding"] - elements { - kind = "NUMERIC" - text = "Issue Count" - value_type { - finding_note_names = ["${var.account_id}/providers/scc/notes/finding"] - kind = "FINDING_COUNT" - } - } - } -} - -# Provision scc_si_note resource instance - Kind Card (NUMERIC - KPI) -resource "ibm_scc_si_note" "num-card-kpi" { - provider_id = var.provider_id - short_description = "Security Threat" - long_description = "Security Threat found in your account" - kind = "CARD" - note_id = "num-card-kpi" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - card { - section = "Terraform Insights" - title = "NUMERIC KPI Card" - subtitle = "Summary of KPIs" - finding_note_names = ["${var.account_id}/providers/scc/notes/finding"] - elements { - kind = "NUMERIC" - text = "Issue Count" - value_type { - kpi_note_name = "${var.account_id}/providers/scc/notes/kpi" - kind = "KPI" - } - } - } -} - -# Provision scc_si_note resource instance - Kind Card (BREAKDOWN - FINDING_COUNT) -resource "ibm_scc_si_note" "bkd-card-finding" { - provider_id = var.provider_id - short_description = "Security Threat Breakdown Card" - long_description = "Security Threat found in your account" - kind = "CARD" - note_id = "bkd-card-finding" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - card { - section = "Terraform Insights" - title = "BREAKDOWN Finding Card" - subtitle = "Summary of Findings" - finding_note_names = ["${var.account_id}/providers/scc/notes/finding"] - elements { - kind = "BREAKDOWN" - text = "Issue Count" - value_types { - text = "Issue Count" - finding_note_names = ["${var.account_id}/providers/scc/notes/finding"] - kind = "FINDING_COUNT" - } - } - } -} - -# Provision scc_si_note resource instance - Kind Card (BREAKDOWN - KPI) -resource "ibm_scc_si_note" "bkd-card-kpi" { - provider_id = var.provider_id - short_description = "Security Threat" - long_description = "Security Threat found in your account" - kind = "CARD" - note_id = "bkd-card-kpi" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - card { - section = "Terraform Insights" - title = "BREAKDOWN KPI Card" - subtitle = "Summary of KPIs" - finding_note_names = ["${var.account_id}/providers/scc/notes/finding"] - elements { - kind = "BREAKDOWN" - text = "Issue Count" - value_types { - text = "Issue Count" - kpi_note_name = "${var.account_id}/providers/scc/notes/kpi" - kind = "KPI" - } - } - } -} - -# Provision scc_si_note resource instance - Kind Card (TIME_SERIES - FINDING_COUNT) -resource "ibm_scc_si_note" "ts-card-finding" { - provider_id = var.provider_id - short_description = "Security Threat" - long_description = "Security Threat found in your account" - kind = "CARD" - note_id = "ts-card-finding" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - card { - section = "Terraform Insights" - title = "TIME_SERIES Finding Card" - subtitle = "Summary of Findings" - finding_note_names = ["${var.account_id}/providers/scc/notes/finding"] - elements { - kind = "TIME_SERIES" - text = "Issue Count" - default_time_range = "3d" - value_types { - text = "Issue Count" - finding_note_names = ["${var.account_id}/providers/scc/notes/finding"] - kind = "FINDING_COUNT" - } - } - } -} - - -// Provision scc_si_occurrence resource instance - Kind FINDING - -resource "ibm_scc_si_occurrence" "finding-occurrence" { - provider_id = var.provider_id - note_name = "${var.account_id}/providers/${var.provider_id}/notes/${var.note_id}" - kind = "FINDING" - occurrence_id = "finding-occ" - resource_url = "https://cloud.ibm.com" - remediation = "Limit the cluster access" - finding { - severity = "HIGH" - certainty = "LOW" - next_steps { - title = "Security Threat" - url = "https://cloud.ibm.com/security-compliance/findings" - } - } -} - -// Provision scc_si_occurrence resource instance - Kind KPI - -resource "ibm_scc_si_occurrence" "kpi-occurrence" { - provider_id = var.provider_id - note_name = "${var.account_id}/providers/${var.provider_id}/notes/${var.note_id}" - kind = "KPI" - occurrence_id = "kpi-occ" - resource_url = "https://cloud.ibm.com" - remediation = "Limit the cluster access" - kpi { - value = 40 - total = 100 - } -} \ No newline at end of file diff --git a/examples/ibm-scc/findings/outputs.tf b/examples/ibm-scc/findings/outputs.tf deleted file mode 100644 index d42bfd6b5a..0000000000 --- a/examples/ibm-scc/findings/outputs.tf +++ /dev/null @@ -1,9 +0,0 @@ -output "ibm_scc_si_note" { - value = ibm_scc_si_note.bkd-card-kpi - description = "scc_si_note resource instance" -} - -output "ibm_scc_si_occurrence" { - value = ibm_scc_si_occurrence.kpi-occurrence - description = "scc_si_occurrence resource instance" -} \ No newline at end of file diff --git a/examples/ibm-scc/findings/variables.tf b/examples/ibm-scc/findings/variables.tf deleted file mode 100644 index ec4cce4494..0000000000 --- a/examples/ibm-scc/findings/variables.tf +++ /dev/null @@ -1,25 +0,0 @@ -variable "ibmcloud_api_key" { - description = "IBM Cloud API key" - type = string -} - -variable "account_id" { - description = "IBM Cloud Account ID" - type = string -} - -variable "provider_id" { - description = "Part of parent. This field contains the provider_id for example: providers/{provider_id}" - type = string -} - -variable "note_id" { - description = "Second part of note name: providers/{provider_id}/notes/{note_id}" - type = string -} - -variable "occurrence_id" { - description = "Second part of occurrence name: providers/{provider_id}/occurrences/{occurrence_id}" - type = string -} - diff --git a/examples/ibm-scc/findings/versions.tf b/examples/ibm-scc/findings/versions.tf deleted file mode 100644 index ee0f9705a2..0000000000 --- a/examples/ibm-scc/findings/versions.tf +++ /dev/null @@ -1,3 +0,0 @@ -terraform { - required_version = ">= 0.12" -} \ No newline at end of file diff --git a/examples/ibm-scc/integration/main.tf b/examples/ibm-scc/integration/main.tf new file mode 100644 index 0000000000..178cfd6c2b --- /dev/null +++ b/examples/ibm-scc/integration/main.tf @@ -0,0 +1,6 @@ +resource "ibm_scc_provider_type_instance" "scc_provider_type_instance_instance" { + provider_type_id = var.scc_provider_type_id + name = var.scc_provider_type_instance_instance + attributes = var.scc_provider_type_instance_attributes +} + diff --git a/examples/ibm-scc/integration/outputs.tf b/examples/ibm-scc/integration/outputs.tf new file mode 100644 index 0000000000..2ed4ff24c7 --- /dev/null +++ b/examples/ibm-scc/integration/outputs.tf @@ -0,0 +1,6 @@ +// This output allows scc_provider_type_instance data to be referenced by other resources and the terraform CLI +// Modify this output if only certain data should be exposed +output "ibm_scc_provider_type_instance" { + value = ibm_scc_provider_type_instance.scc_provider_type_instance_instance + description = "scc_provider_type_instance resource instance" +} diff --git a/examples/ibm-scc/integration/variables.tf b/examples/ibm-scc/integration/variables.tf new file mode 100644 index 0000000000..34627bb653 --- /dev/null +++ b/examples/ibm-scc/integration/variables.tf @@ -0,0 +1,17 @@ +variable "scc_provider_type_id" { + description = "The provider type ID." + type = string + default = "INSERT VALID INSTANCE ID" +} + +variable "scc_provider_type_instance_name" { + description = "The name of the provider type instance." + type = string + default = "workload-protection-instance-1" +} + +variable "scc_provider_type_instance_attributes" { + description = "The provider type instance attributes" + type = map + default = {} +} diff --git a/examples/ibm-scc/posture-management/README.md b/examples/ibm-scc/posture-management/README.md deleted file mode 100644 index db4bc3e63c..0000000000 --- a/examples/ibm-scc/posture-management/README.md +++ /dev/null @@ -1,191 +0,0 @@ -# Example for PostureManagementV2 - -This example illustrates how to use the PostureManagementV2 - -These types of resources are supported: - -* collectors -* scopes -* credentials - -## Usage - -To run this example you need to execute: - -```bash -$ terraform init -$ terraform plan -$ terraform apply -``` - -Run `terraform destroy` when you don't need these resources. - - -## PostureManagementV2 resources - -scc_posture_collector resource: - -```hcl -resource "ibm_scc_posture_collector" "collectors_instance" { - name = var.collectors_name - is_public = var.collectors_is_public - managed_by = var.collectors_managed_by - description = var.collectors_description - passphrase = var.collectors_passphrase - is_ubi_image = var.collectors_is_ubi_image -} -``` -scc_posture_scope resource: - -```hcl -resource "ibm_scc_posture_scope" "scopes_instance" { - name = var.scopes_name - description = var.scopes_description - collector_ids = var.scopes_collector_ids - credential_id = var.scopes_credential_id - credential_type = var.scopes_credential_type - interval = var.scopes_interval - is_discovery_scheduled = var.scopes_is_discovery_scheduled -} -``` -scc_posture_credential resource: - -```hcl -resource "ibm_scc_posture_credential" "credentials_instance" { - enabled = var.credentials_enabled - type = var.credentials_type - name = var.credentials_name - description = var.credentials_description - display_fields = var.credentials_display_fields - group = var.credentials_group - purpose = var.credentials_purpose -} -``` - -## PostureManagementV2 Data sources - -scc_posture_scopes data source: - -```hcl -data "ibm_scc_posture_scopes" "list_scopes_instance" { -} -``` -scc_posture_profile data source: - -```hcl -data "ibm_scc_posture_profile" "profileDetails_instance" { - id = var.profileDetails_id - profile_type = var.profileDetails_profile_type -} -``` -scc_posture_profiles data source: - -```hcl -data "ibm_scc_posture_profiles" "list_profiles_instance" { -} -``` -scc_posture_latest_scans data source: - -```hcl -data "ibm_scc_posture_latest_scans" "list_latest_scans_instance" { - scan_id = var.list_latest_scans_scan_id -} -``` -scc_posture_scan_summary data source: - -```hcl -data "ibm_scc_posture_scan_summary" "scans_summary_instance" { - scan_id = var.scans_summary_scan_id - profile_id = var.scans_summary_profile_id -} -``` -scc_posture_scan_summaries data source: - -```hcl -data "ibm_scc_posture_scan_summaries" "scan_summaries_instance" { - report_setting_id = var.scan_summaries_report_setting_id -} -``` -scc_posture_group_profile data source: - -```hcl -data "ibm_scc_posture_group_profile" "group_profile_details_instance" { - profile_id = var.group_profile_details_profile_id -} -``` -scc_posture_scope_correlation data source: - -```hcl -data "ibm_scc_posture_scope_correlation" "scope_correlation_instance" { - correlation_id = var.scope_correlation_correlation_id -} -``` - -## Assumptions - -1. TODO - -## Notes - -1. TODO - -## Requirements - -| Name | Version | -|------|---------| -| terraform | ~> 0.12 | - -## Providers - -| Name | Version | -|------|---------| -| ibm | 1.13.1 | - -## Inputs - -| Name | Description | Type | Required | -|------|-------------|------|---------| -| ibmcloud\_api\_key | IBM Cloud API key | `string` | true | -| name | A unique name for your collector. | `string` | true | -| is_public | Determines whether the collector endpoint is accessible on a public network. If set to `true`, the collector connects to resources in your account over a public network. If set to `false`, the collector connects to resources by using a private IP that is accessible only through the IBM Cloud private network. | `bool` | true | -| managed_by | Determines whether the collector is an IBM or customer-managed virtual machine. Use `ibm` to allow Security and Compliance Center to create, install, and manage the collector on your behalf. The collector is installed in an OpenShift cluster and approved automatically for use. Use `customer` if you would like to install the collector by using your own virtual machine. For more information, check out the [docs](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-collector). | `string` | true | -| description | A detailed description of the collector. | `string` | false | -| passphrase | To protect the credentials that you add to the service, a passphrase is used to generate a data encryption key. The key is used to securely store your credentials and prevent anyone from accessing them. | `string` | false | -| is_ubi_image | Determines whether the collector has a Ubi image. | `bool` | false | -| name | A unique name for your scope. | `string` | true | -| description | A detailed description of the scope. | `string` | true | -| collector_ids | The unique IDs of the collectors that are attached to the scope. | `list(string)` | true | -| credential_id | The unique identifier of the credential. | `string` | true | -| credential_type | The environment that the scope is targeted to. | `string` | true | -| interval | Stores the value of Frequency. This is used in case of on-prem Scope if the user wants to schedule a discovery task.The unit is seconds. Example if a user wants to trigger discovery every hour, this value will be set to 3600. | `number` | false | -| is_discovery_scheduled | Stores the value of Discovery Scheduled.This is used in case of on-prem Scope if the user wants to schedule a discovery task. | `bool` | false | -| enabled | Credentials status enabled/disbaled. | `bool` | true | -| type | Credentials type. | `string` | true | -| name | Credentials name. | `string` | true | -| description | Credentials description. | `string` | true | -| display_fields | Details the fields on the credential. This will change as per credential type selected. | `` | true | -| purpose | Purpose for which the credential is created. | `string` | true | -| id | The id for the given API. | `string` | true | -| profile_type | The profile type ID. This will be 4 for profiles and 6 for group profiles. | `string` | true | -| scan_id | The ID of the scan. | `string` | false | -| scan_id | Your Scan ID. | `string` | true | -| profile_id | The profile ID. This can be obtained from the Security and Compliance Center UI by clicking on the profile name. The URL contains the ID. | `string` | true | -| report_setting_id | The report setting ID. This can be obtained from the /validations/latest_scans API call. | `string` | true | -| profile_id | The profile ID. This can be obtained from the Security and Compliance Center UI by clicking on the profile name. The URL contains the ID. | `string` | true | -| correlation_id | A correlation_Id is created when a scope is created and discovery task is triggered or when a validation is triggered on a Scope. This is used to get the status of the task(discovery or validation). | `string` | true | - -## Outputs - -| Name | Description | -|------|-------------| -| collectors | collectors object | -| scopes | scopes object | -| credentials | credentials object | -| list_scopes | list_scopes object | -| profileDetails | profileDetails object | -| list_profiles | list_profiles object | -| list_latest_scans | list_latest_scans object | -| scans_summary | scans_summary object | -| scan_summaries | scan_summaries object | -| group_profile_details | group_profile_details object | -| scope_correlation | scope_correlation object | diff --git a/examples/ibm-scc/posture-management/main.tf b/examples/ibm-scc/posture-management/main.tf deleted file mode 100644 index ec9cd3db23..0000000000 --- a/examples/ibm-scc/posture-management/main.tf +++ /dev/null @@ -1,3 +0,0 @@ -provider "ibm" { - ibmcloud_api_key = var.ibmcloud_api_key -} \ No newline at end of file diff --git a/examples/ibm-scc/posture-management/outputs.tf b/examples/ibm-scc/posture-management/outputs.tf deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/ibm-scc/posture-management/provider.tf b/examples/ibm-scc/posture-management/provider.tf deleted file mode 100644 index 8b13789179..0000000000 --- a/examples/ibm-scc/posture-management/provider.tf +++ /dev/null @@ -1 +0,0 @@ - diff --git a/examples/ibm-scc/posture-management/terraform.tfvars b/examples/ibm-scc/posture-management/terraform.tfvars deleted file mode 100644 index 526c6b7c1f..0000000000 --- a/examples/ibm-scc/posture-management/terraform.tfvars +++ /dev/null @@ -1 +0,0 @@ -ibmcloud_api_key = "" \ No newline at end of file diff --git a/examples/ibm-scc/posture-management/variables.tf b/examples/ibm-scc/posture-management/variables.tf deleted file mode 100644 index fc4de589bb..0000000000 --- a/examples/ibm-scc/posture-management/variables.tf +++ /dev/null @@ -1,155 +0,0 @@ -variable "ibmcloud_api_key" { - description = "IBM Cloud API key" - type = string -} - -// Resource arguments for collectors -variable "collectors_name" { - description = "A unique name for your collector." - type = string - default = "IBM-collector-sample" -} -variable "collectors_is_public" { - description = "Determines whether the collector endpoint is accessible on a public network. If set to `true`, the collector connects to resources in your account over a public network. If set to `false`, the collector connects to resources by using a private IP that is accessible only through the IBM Cloud private network." - type = bool - default = true -} -variable "collectors_managed_by" { - description = "Determines whether the collector is an IBM or customer-managed virtual machine. Use `ibm` to allow Security and Compliance Center to create, install, and manage the collector on your behalf. The collector is installed in an OpenShift cluster and approved automatically for use. Use `customer` if you would like to install the collector by using your own virtual machine. For more information, check out the [docs](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-collector)." - type = string - default = "customer" -} -variable "collectors_description" { - description = "A detailed description of the collector." - type = string - default = "sample collector" -} -variable "collectors_passphrase" { - description = "To protect the credentials that you add to the service, a passphrase is used to generate a data encryption key. The key is used to securely store your credentials and prevent anyone from accessing them." - type = string - default = "secret" -} -variable "collectors_is_ubi_image" { - description = "Determines whether the collector has a Ubi image." - type = bool - default = true -} - -// Resource arguments for scopes -variable "scopes_name" { - description = "A unique name for your scope." - type = string - default = "IBMSchema-new-048-test1" -} -variable "scopes_description" { - description = "A detailed description of the scope." - type = string - default = "IBMSchema1" -} -variable "scopes_collector_ids" { - description = "The unique IDs of the collectors that are attached to the scope." - type = list(string) - default = ["3"] -} -variable "scopes_credential_id" { - description = "The unique identifier of the credential." - type = string - default = "4" -} -variable "scopes_credential_type" { - description = "The environment that the scope is targeted to." - type = string - default = "ibm" -} - -// Resource arguments for credentials -variable "credentials_enabled" { - description = "Credentials status enabled/disbaled." - type = bool - default = true -} -variable "credentials_type" { - description = "Credentials type." - type = string - default = "ibm_cloud" -} -variable "credentials_name" { - description = "Credentials name." - type = string - default = "test_create1" -} -variable "credentials_description" { - description = "Credentials description." - type = string - default = "This credential is used for testing" -} -variable "credentials_purpose" { - description = "Purpose for which the credential is created." - type = string - default = "discovery_fact_collection_remediation" -} - -// Data source arguments for list_scopes - -// Data source arguments for profileDetails -variable "profileDetails_id" { - description = "The id for the given API." - type = string -} -variable "profileDetails_profile_type" { - description = "The profile type ID. This will be 4 for profiles and 6 for group profiles." - type = string - default = "4" -} - -// Data source arguments for list_profiles - -// Data source arguments for list_latest_scans -variable "list_latest_scans_scan_id" { -} - -// Data source arguments for scans_summary -variable "scans_summary_scan_id" { - description = "Your Scan ID." - type = string -} -variable "scans_summary_profile_id" { - description = "The profile ID. This can be obtained from the Security and Compliance Center UI by clicking on the profile name. The URL contains the ID." - type = string -} - -// Data source arguments for scan_summaries -variable "scan_summaries_report_setting_id" { - description = "The report setting ID. This can be obtained from the /validations/latest_scans API call." - type = string -} - -// Data source arguments for group_profile_details -variable "group_profile_details_profile_id" { - description = "The profile ID. This can be obtained from the Security and Compliance Center UI by clicking on the profile name. The URL contains the ID." - type = string -} - -// Data source arguments for scope_correlation -variable "scope_correlation_correlation_id" { - description = "A correlation_Id is created when a scope is created and discovery task is triggered or when a validation is triggered on a Scope. This is used to get the status of the task(discovery or validation)." - type = string -} - -// Data source arguments for scope -variable "scope_id" { - description = "The scope ID. This can be obtained from the Security and Compliance Center UI by clicking on the scope name. The URL contains the ID." - type = string -} - -// Data source arguments for credential -variable "credential_id" { - description = "The collector ID. This can be obtained from the Security and Compliance Center UI by clicking on the credential name. The network tab contains the ID." - type = string -} - -// Data source arguments for collector -variable "collector_id" { - description = "The collector ID. This can be obtained from the Security and Compliance Center UI by clicking on the collector name. The network tab contains the ID." - type = string -} \ No newline at end of file diff --git a/examples/ibm-scc/posture-management/versions.tf b/examples/ibm-scc/posture-management/versions.tf deleted file mode 100644 index ee0f9705a2..0000000000 --- a/examples/ibm-scc/posture-management/versions.tf +++ /dev/null @@ -1,3 +0,0 @@ -terraform { - required_version = ">= 0.12" -} \ No newline at end of file diff --git a/examples/ibm-scc/profile/main.tf b/examples/ibm-scc/profile/main.tf new file mode 100644 index 0000000000..d9f4dcaf8d --- /dev/null +++ b/examples/ibm-scc/profile/main.tf @@ -0,0 +1,41 @@ +data "ibm_scc_control_library" "scc_control_library" { + control_library_id = var.ibm_scc_control_library_id +} + +resource "ibm_scc_profile" "scc_demo_profile" { + profile_type = "custom" + profile_description = var.ibm_scc_profile_description + profile_name = var.ibm_scc_profile_name + default_parameters { + } + controls { + control_library_id = var.ibm_scc_control_library_id + control_id = "032a81ca-6ef7-4ac2-81ac-20ee4a780e3b" + } +} + +resource "ibm_scc_profile_attachment" "scc_demo_profile_attachment" { + profile_id = resource.ibm_scc_profile.scc_demo_profile.id + name = var.ibm_scc_profile_attachment_name + description = var.ibm_scc_profile_attachment_description + scope { + environment = "ibm-cloud" + properties { + name = "scope_id" + value = "62ecf99b240144dea9125666249edfcb" + } + properties { + name = "scope_type" + value = "account" + } + } + schedule = "every_30_days" + status = "enabled" + notifications { + enabled = false + controls { + failed_control_ids = [] + threshold_limit = 14 + } + } +} diff --git a/examples/ibm-scc/profile/variables.tf b/examples/ibm-scc/profile/variables.tf new file mode 100644 index 0000000000..b61d5bde5c --- /dev/null +++ b/examples/ibm-scc/profile/variables.tf @@ -0,0 +1,29 @@ +variable "ibm_scc_control_library_id" { + description = "The id of the control library" + type = string + default = "" +} + +variable "ibm_scc_profile_name" { + description = "The name of the profile" + type = string + default = "scc_demo_profile" +} + +variable "ibm_scc_profile_description" { + description = "The description of the profile" + type = string + default = "This profile as a demo using Terraform" +} + +variable "ibm_scc_profile_attachment_name" { + description = "The name of the profile" + type = string + default = "scc_demo_profile_attachment" +} + +variable "ibm_scc_profile_attachment_desc" { + description = "The description of the profile attachment" + type = string + default = "This description of the profile attachnment made by Terraform" +} diff --git a/examples/ibm-scc/report/main.tf b/examples/ibm-scc/report/main.tf new file mode 100644 index 0000000000..c46dc8bc2d --- /dev/null +++ b/examples/ibm-scc/report/main.tf @@ -0,0 +1,32 @@ +data "ibm_scc_latest_reports" "scc_latest_reports_instance" { + sort = "profile_name" +} + +data "ibm_scc_report_rule" "scc_report_rule_instance" { + report_id = var.scc_report_id + rule_id = var.scc_rule_id +} + +data "ibm_scc_report_tags" "scc_report_tags_instance" { + report_id = var.scc_report_id +} + +data "ibm_scc_report_evaluations" "scc_report_evaluations_instance" { + report_id = var.scc_report_id +} + +data "ibm_scc_report_controls" "scc_report_controls_instance" { + report_id = var.scc_report_id +} + +data "ibm_scc_report_summary" "scc_report_summary_instance" { + report_id = var.scc_report_id +} + +data "ibm_scc_report_violation_drift" "scc_report_violation_drift_instance" { + report_id = var.scc_report_id +} + +data "ibm_scc_report" "scc_report_instance" { + report_id = var.scc_report_id +} diff --git a/examples/ibm-scc/report/variables.tf b/examples/ibm-scc/report/variables.tf new file mode 100644 index 0000000000..81187d976b --- /dev/null +++ b/examples/ibm-scc/report/variables.tf @@ -0,0 +1,11 @@ +variable "scc_report_id" { + description = "The ID of the report" + default = "" + type = string +} + +variable "scc_rule_id" { + description = "The ID of the rule to configure against " + default = "rule-f8722625-1968-4d7a-93cb-4b0f8da726da" + type = string +} diff --git a/examples/ibm-scc/rule/main.tf b/examples/ibm-scc/rule/main.tf new file mode 100644 index 0000000000..41f8348c68 --- /dev/null +++ b/examples/ibm-scc/rule/main.tf @@ -0,0 +1,16 @@ +// Provision scc_rule resource instance +resource "ibm_scc_rule" "scc_rule_tf_demo" { + description = var.scc_description + target { + service_name = "cloud-object-storage" + resource_kind = "bucket" + } + labels = ["SOC2"] + required_config { + description = "this is a terraform update to description" + // This is Terraform HCL, not JSON + property = "storage_class" + operator = "string_equals" + value = "smart" + } +} diff --git a/examples/ibm-scc/rule/variables.tf b/examples/ibm-scc/rule/variables.tf new file mode 100644 index 0000000000..a2baf63324 --- /dev/null +++ b/examples/ibm-scc/rule/variables.tf @@ -0,0 +1,5 @@ +variable "scc_desciption" { + description = "The name and description of the scc_rule" + type = string + default = "scc_tf_rule" +} diff --git a/go.mod b/go.mod index d03c2c4aa5..bcb8f5c6b4 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( github.com/IBM/continuous-delivery-go-sdk v1.1.2 github.com/IBM/event-notifications-go-admin-sdk v0.2.4 github.com/IBM/eventstreams-go-sdk v1.2.0 + github.com/IBM/go-sdk-core/v3 v3.2.4 github.com/IBM/go-sdk-core/v5 v5.14.1 github.com/IBM/ibm-cos-sdk-go v1.10.0 github.com/IBM/ibm-cos-sdk-go-config v1.2.0 @@ -23,20 +24,21 @@ require ( github.com/IBM/ibm-hpcs-uko-sdk v0.0.20-beta github.com/IBM/keyprotect-go-client v0.10.0 github.com/IBM/networking-go-sdk v0.42.2 + github.com/IBM/project-go-sdk v0.0.10 github.com/IBM/platform-services-go-sdk v0.48.1 github.com/IBM/push-notifications-go-sdk v0.0.0-20210310100607-5790b96c47f5 - github.com/IBM/scc-go-sdk/v3 v3.1.6 - github.com/IBM/scc-go-sdk/v4 v4.0.2 + github.com/IBM/scc-go-sdk/v5 v5.0.2 github.com/IBM/schematics-go-sdk v0.2.1 github.com/IBM/secrets-manager-go-sdk/v2 v2.0.0 github.com/IBM/vpc-beta-go-sdk v0.6.0 github.com/IBM/vpc-go-sdk v0.41.0 github.com/ScaleFT/sshkeys v0.0.0-20200327173127-6142f742bca5 github.com/Shopify/sarama v1.29.1 + github.com/akamai/AkamaiOPEN-edgegrid-golang v1.2.2 + 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/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32 - github.com/go-openapi/errors v0.20.3 // indirect github.com/go-openapi/strfmt v0.21.7 github.com/golang-jwt/jwt v3.2.2+incompatible github.com/google/go-cmp v0.5.9 @@ -49,57 +51,18 @@ require ( github.com/mitchellh/go-homedir v1.1.0 github.com/openshift/api v0.0.0-20230329202819-04d4fb776982 github.com/openshift/client-go v0.0.0-20230324103026-3f1513df25e0 + github.com/pkg/errors v0.9.1 + github.com/rook/rook v1.11.4 github.com/softlayer/softlayer-go v1.0.3 - go.mongodb.org/mongo-driver v1.11.6 // indirect golang.org/x/crypto v0.7.0 + gopkg.in/yaml.v3 v3.0.1 gotest.tools v2.2.0+incompatible k8s.io/api v0.26.3 k8s.io/apimachinery v0.26.3 k8s.io/client-go v0.26.1 -) - -require ( - github.com/IBM/go-sdk-core/v3 v3.2.4 - github.com/IBM/project-go-sdk v0.0.10 - github.com/akamai/AkamaiOPEN-edgegrid-golang v1.2.2 - github.com/akamai/AkamaiOPEN-edgegrid-golang/v5 v5.0.0 - github.com/pkg/errors v0.9.1 - github.com/rook/rook v1.11.4 - gopkg.in/yaml.v3 v3.0.1 sigs.k8s.io/controller-runtime v0.14.1 ) -require ( - github.com/armon/go-metrics v0.4.1 // indirect - github.com/beorn7/perks v1.0.1 // indirect - github.com/cenkalti/backoff/v3 v3.2.2 // indirect - github.com/cespare/xxhash/v2 v2.2.0 // indirect - github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf // indirect - github.com/coreos/pkg v0.0.0-20220810130054-c7d1c02cb6cf // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/hashicorp/go-immutable-radix v1.3.1 // indirect - github.com/hashicorp/go-rootcerts v1.0.2 // indirect - github.com/hashicorp/go-secure-stdlib/parseutil v0.1.7 // indirect - github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect - github.com/hashicorp/go-sockaddr v1.0.2 // indirect - github.com/hashicorp/golang-lru v0.5.4 // indirect - github.com/hashicorp/hcl v1.0.1-vault-5 // indirect - github.com/hashicorp/vault v1.13.5 // indirect - github.com/hashicorp/vault/api v1.9.0 // indirect - github.com/hashicorp/vault/api/auth/approle v0.3.0 // indirect - github.com/hashicorp/vault/sdk v0.8.1 // indirect - github.com/kube-object-storage/lib-bucket-provisioner v0.0.0-20221122204822-d1a8c34382f1 // indirect - github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect - github.com/prometheus/client_golang v1.14.0 // indirect - github.com/prometheus/client_model v0.3.0 // indirect - github.com/prometheus/common v0.37.0 // indirect - github.com/prometheus/procfs v0.8.0 // indirect - github.com/ryanuber/go-glob v1.0.0 // indirect - github.com/sirupsen/logrus v1.9.0 // indirect - gomodules.xyz/jsonpatch/v2 v2.2.0 // indirect - gopkg.in/square/go-jose.v2 v2.6.0 // indirect -) - require ( github.com/Logicalis/asn1 v0.0.0-20190312173541-d60463189a56 // indirect github.com/PromonLogicalis/asn1 v0.0.0-20190312173541-d60463189a56 // indirect @@ -107,8 +70,14 @@ require ( github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 // indirect github.com/apex/log v1.9.0 // indirect github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect + github.com/armon/go-metrics v0.4.1 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/cenkalti/backoff/v3 v3.2.2 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 // indirect + github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf // indirect + github.com/coreos/pkg v0.0.0-20220810130054-c7d1c02cb6cf // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a // indirect github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect @@ -119,8 +88,10 @@ require ( github.com/evanphx/json-patch/v5 v5.6.0 // indirect github.com/fatih/color v1.14.1 // indirect github.com/frankban/quicktest v1.14.3 // indirect + github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/go-logr/logr v1.2.3 // indirect github.com/go-openapi/analysis v0.21.2 // indirect + github.com/go-openapi/errors v0.20.3 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect github.com/go-openapi/jsonreference v0.20.0 // indirect github.com/go-openapi/loads v0.21.1 // indirect @@ -143,10 +114,17 @@ require ( github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 // indirect github.com/hashicorp/go-hclog v1.5.0 // indirect + github.com/hashicorp/go-immutable-radix v1.3.1 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-plugin v1.4.8 // indirect github.com/hashicorp/go-retryablehttp v0.7.2 // indirect + github.com/hashicorp/go-rootcerts v1.0.2 // indirect + github.com/hashicorp/go-secure-stdlib/parseutil v0.1.7 // indirect + github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect + github.com/hashicorp/go-sockaddr v1.0.2 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect github.com/hashicorp/hc-install v0.4.0 // indirect + github.com/hashicorp/hcl v1.0.1-vault-5 // indirect github.com/hashicorp/hcl/v2 v2.14.1 // indirect github.com/hashicorp/logutils v1.0.0 // indirect github.com/hashicorp/terraform-exec v0.17.3 // indirect @@ -155,6 +133,10 @@ require ( github.com/hashicorp/terraform-plugin-log v0.7.0 // indirect github.com/hashicorp/terraform-registry-address v0.0.0-20220623143253-7d51757b572c // indirect github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734 // indirect + github.com/hashicorp/vault v1.13.5 // indirect + github.com/hashicorp/vault/api v1.9.0 // indirect + github.com/hashicorp/vault/api/auth/approle v0.3.0 // indirect + github.com/hashicorp/vault/sdk v0.8.1 // indirect github.com/hashicorp/yamux v0.1.1 // indirect github.com/hokaccha/go-prettyjson v0.0.0-20170213120834-e6b9231a2b1c // indirect github.com/imdario/mergo v0.3.13 // indirect @@ -168,11 +150,13 @@ require ( github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.15.15 // indirect + github.com/kube-object-storage/lib-bucket-provisioner v0.0.0-20221122204822-d1a8c34382f1 // indirect github.com/leodido/go-urn v1.2.3 // indirect github.com/libopenstorage/secrets v0.0.0-20220823020833-2ecadaf59d8a // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.17 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/go-testing-interface v1.14.1 // indirect github.com/mitchellh/go-wordwrap v1.0.0 // indirect @@ -190,7 +174,13 @@ require ( github.com/pelletier/go-toml v1.7.0 // indirect github.com/pierrec/lz4 v2.6.1+incompatible // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/prometheus/client_golang v1.14.0 // indirect + github.com/prometheus/client_model v0.3.0 // indirect + github.com/prometheus/common v0.37.0 // indirect + github.com/prometheus/procfs v0.8.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect + github.com/ryanuber/go-glob v1.0.0 // indirect + github.com/sirupsen/logrus v1.9.0 // indirect github.com/softlayer/xmlrpc v0.0.0-20200409220501-5f089df7cb7e // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/stretchr/objx v0.5.0 // indirect @@ -199,6 +189,7 @@ require ( github.com/vmihailenco/msgpack/v4 v4.3.12 // indirect github.com/vmihailenco/tagparser v0.1.1 // indirect github.com/zclconf/go-cty v1.11.0 // indirect + go.mongodb.org/mongo-driver v1.11.6 // indirect go.uber.org/ratelimit v0.2.0 // indirect golang.org/x/net v0.10.0 // indirect golang.org/x/oauth2 v0.6.0 // indirect @@ -206,6 +197,7 @@ require ( golang.org/x/term v0.8.0 // indirect golang.org/x/text v0.9.0 // indirect golang.org/x/time v0.3.0 // indirect + gomodules.xyz/jsonpatch/v2 v2.2.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 // indirect google.golang.org/grpc v1.53.0 // indirect @@ -213,6 +205,7 @@ require ( gopkg.in/go-playground/validator.v9 v9.31.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/square/go-jose.v2 v2.6.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/klog/v2 v2.90.1 // indirect k8s.io/kube-openapi v0.0.0-20221110221610-a28e98eb7c70 // indirect diff --git a/go.sum b/go.sum index 17b4ec63b6..4586083320 100644 --- a/go.sum +++ b/go.sum @@ -159,10 +159,8 @@ github.com/IBM/project-go-sdk v0.0.10 h1:vHSuemwZ4S4c6BEb22tzsEcPTs/5LnZ0yKpP3GG github.com/IBM/project-go-sdk v0.0.10/go.mod h1:lqe0M4cKvABI1iHR1b+KfasVcxQL6nl2VJ8eOyQs8Ig= github.com/IBM/push-notifications-go-sdk v0.0.0-20210310100607-5790b96c47f5 h1:NPUhkoOCRuv3OFWt19PmwjXGGTKlvmbuPg9fUrBUNe4= github.com/IBM/push-notifications-go-sdk v0.0.0-20210310100607-5790b96c47f5/go.mod h1:b07XHUVh0XYnQE9s2mqgjYST1h9buaQNqN4EcKhOsX0= -github.com/IBM/scc-go-sdk/v3 v3.1.6 h1:wg7yujuJJ1O1pcGrIn8ITq6i6GeXb7GRBPNq6kLrkMU= -github.com/IBM/scc-go-sdk/v3 v3.1.6/go.mod h1:cBxkth9AIOcKQx4Gy9bWgyGYa7vYwHAalUBvY+O8xAE= -github.com/IBM/scc-go-sdk/v4 v4.0.2 h1:8BHMRobCFurZwKaUhxWi8CdAA9+CvyzmlBOmo7KmXC4= -github.com/IBM/scc-go-sdk/v4 v4.0.2/go.mod h1:ufqf/kBtRn3Pq/pFXF6zQGHXV2P2EzPsntw1Sw19clE= +github.com/IBM/scc-go-sdk/v5 v5.0.2 h1:OUqkzLfJqozp2aqylNurwaJd1SmY8o7KturFse6R2xM= +github.com/IBM/scc-go-sdk/v5 v5.0.2/go.mod h1:YtAVlzq10bwR82QX4ZavhDIwa1s85RuVO9N/KmXVcuk= github.com/IBM/schematics-go-sdk v0.2.1 h1:byATysGD+Z1k/wdtNqQmKALcAPjgSLuSyzcabh1jRAw= github.com/IBM/schematics-go-sdk v0.2.1/go.mod h1:Tw2OSAPdpC69AxcwoyqcYYaGTTW6YpERF9uNEU+BFRQ= github.com/IBM/secrets-manager-go-sdk/v2 v2.0.0 h1:Lx4Bvim/MfoHEYR+n312bty5DirAJypBGGS9YZo3zCw= @@ -217,7 +215,6 @@ github.com/akamai/AkamaiOPEN-edgegrid-golang v1.2.2 h1:F1j7z+/DKEsYqZNoxC6wvfmai github.com/akamai/AkamaiOPEN-edgegrid-golang v1.2.2/go.mod h1:QlXr/TrICfQ/ANa76sLeQyhAJyNR9sEcfNuZBkY9jgY= github.com/akamai/AkamaiOPEN-edgegrid-golang/v5 v5.0.0 h1:/NUI7xSyyV+lkexQ2gZmsw+Vgche5tpqchPRT2ywnN0= github.com/akamai/AkamaiOPEN-edgegrid-golang/v5 v5.0.0/go.mod h1:i7L7M3mZO+UryCzIsE2/HCqDTX7icCYKtRyvut/O6rU= -github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= @@ -456,11 +453,9 @@ github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkPro github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= github.com/go-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E= -github.com/go-git/go-billy/v5 v5.0.0/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= github.com/go-git/go-billy/v5 v5.2.0/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= github.com/go-git/go-billy/v5 v5.3.1 h1:CPiOUAzKtMRvolEKw+bG1PLRpT7D3LIs3/3ey4Aiu34= github.com/go-git/go-billy/v5 v5.3.1/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= -github.com/go-git/go-git-fixtures/v4 v4.0.1/go.mod h1:m+ICp2rF3jDhFgEZ/8yziagdT1C+ZpZcrJjappBCDSw= github.com/go-git/go-git-fixtures/v4 v4.2.1/go.mod h1:K8zd3kDUAykwTdDCr+I0per6Y6vMiRR/nnVTBtavnB0= github.com/go-git/go-git/v5 v5.0.0/go.mod h1:oYD8y9kWsGINPFJoLdaScGCN6dlKg23blmClfZwtUVA= github.com/go-git/go-git/v5 v5.4.2 h1:BXyZu9t0VkbiHtqrsvdq39UDhGJTl1h55VW6CSC4aY4= @@ -1830,7 +1825,6 @@ golang.org/x/sys v0.0.0-20181218192612-074acd46bca6/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190209173611-3b5209105503/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190221075227-b4e8571b14e0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190321052220-f7bb7a8bee54/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -2015,7 +2009,6 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.0.0-20201021000207-d49c4edd7d96/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= diff --git a/ibm/acctest/acctest.go b/ibm/acctest/acctest.go index cd30c4effc..03f2d507f4 100644 --- a/ibm/acctest/acctest.go +++ b/ibm/acctest/acctest.go @@ -211,12 +211,10 @@ var Tg_cross_network_id string // Enterprise Management var Account_to_be_imported string -// Secuity and Complinace Center, Governance -var Scc_gov_account_id string -var Scc_resource_group_id string - -// Security and Compliance Center, SI -var Scc_si_account string +// Secuity and Complinace Center +var SccApiEndpoint string +var SccProviderTypeAttributes string +var SccReportId string // ROKS Cluster var ClusterName string @@ -1215,19 +1213,19 @@ func init() { fmt.Println("[WARN] Set the environment variable IBM_HPCS_ROOTKEY_CRN with a VALID CRN for a root key created in the HPCS instance") } - Scc_gov_account_id = os.Getenv("SCC_GOVERNANCE_ACCOUNT_ID") - if Scc_gov_account_id == "" { - fmt.Println("[WARN] Set the environment variable SCC_GOVERNANCE_ACCOUNT_ID with a VALID account name") + SccApiEndpoint = os.Getenv("IBMCLOUD_SCC_API_ENDPOINT") + if SccApiEndpoint == "" { + fmt.Println("[WARN] Set the environment variable IBMCLOUD_SCC_API_ENDPOINT with a VALID endpoint") } - Scc_resource_group_id = os.Getenv("IBM_SCC_RESOURCE_GROUP") - if Scc_resource_group_id == "" { - fmt.Println("[WARN] Set the environment variable IBM_SCC_RESOURCE_GROUP with a VALID resource group id") + SccProviderTypeAttributes = os.Getenv("IBMCLOUD_SCC_PROVIDER_TYPE_ATTRIBUTES") + if SccProviderTypeAttributes == "" { + fmt.Println("[WARN] Set the environment variable IBMCLOUD_SCC_PROVIDER_TYPE_ATTRIBUTES with a VALID ATTRIBUTE") } - Scc_si_account = os.Getenv("SCC_SI_ACCOUNT") - if Scc_si_account == "" { - fmt.Println("[INFO] Set the environment variable SCC_SI_ACCOUNT for testing SCC SI resources resource else tests will fail if this is not set correctly") + SccReportId = os.Getenv("IBMCLOUD_SCC_REPORT_ID") + if SccApiEndpoint == "" { + fmt.Println("[WARN] Set the environment variable IBMCLOUD_SCC_REPORT_ID with a VALID REPORT_ID") } CloudShellAccountID = os.Getenv("IBM_CLOUD_SHELL_ACCOUNT_ID") diff --git a/ibm/conns/config.go b/ibm/conns/config.go index de4e231f28..a8fefc5e46 100644 --- a/ibm/conns/config.go +++ b/ibm/conns/config.go @@ -79,9 +79,6 @@ import ( resourcemanager "github.com/IBM/platform-services-go-sdk/resourcemanagerv2" project "github.com/IBM/project-go-sdk/projectv1" "github.com/IBM/push-notifications-go-sdk/pushservicev1" - "github.com/IBM/scc-go-sdk/v3/adminserviceapiv1" - "github.com/IBM/scc-go-sdk/v3/configurationgovernancev1" - "github.com/IBM/scc-go-sdk/v4/posturemanagementv2" schematicsv1 "github.com/IBM/schematics-go-sdk/schematicsv1" vpcbeta "github.com/IBM/vpc-beta-go-sdk/vpcbetav1" "github.com/IBM/vpc-go-sdk/common" @@ -119,7 +116,7 @@ import ( "github.com/IBM/event-notifications-go-admin-sdk/eventnotificationsv1" "github.com/IBM/eventstreams-go-sdk/pkg/schemaregistryv1" "github.com/IBM/ibm-hpcs-uko-sdk/ukov4" - "github.com/IBM/scc-go-sdk/v4/posturemanagementv1" + scc "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" "github.com/IBM/secrets-manager-go-sdk/v2/secretsmanagerv1" "github.com/IBM/secrets-manager-go-sdk/v2/secretsmanagerv2" ) @@ -130,9 +127,7 @@ const RetryAPIDelay = 5 * time.Second // BluemixRegion ... var BluemixRegion string -var ( - errEmptyBluemixCredentials = errors.New("ibmcloud_api_key or bluemix_api_key or iam_token and iam_refresh_token must be provided. Please see the documentation on how to configure it") -) +var errEmptyBluemixCredentials = errors.New("ibmcloud_api_key or bluemix_api_key or iam_token and iam_refresh_token must be provided. Please see the documentation on how to configure it") // UserConfig ... type UserConfig struct { @@ -146,19 +141,19 @@ type UserConfig struct { // Config stores user provider input type Config struct { - //BluemixAPIKey is the Bluemix api key + // BluemixAPIKey is the Bluemix api key BluemixAPIKey string - //Bluemix region + // Bluemix region Region string - //Resource group id + // Resource group id ResourceGroup string - //Bluemix API timeout + // Bluemix API timeout BluemixTimeout time.Duration - //Softlayer end point url + // Softlayer end point url SoftLayerEndpointURL string - //Softlayer API timeout + // Softlayer API timeout SoftLayerTimeout time.Duration // Softlayer User Name @@ -167,30 +162,30 @@ type Config struct { // Softlayer API Key SoftLayerAPIKey string - //Retry Count for API calls - //Unexposed in the schema at this point as they are used only during session creation for a few calls - //When sdk implements it we an expose them for expected behaviour - //https://github.com/softlayer/softlayer-go/issues/41 + // Retry Count for API calls + // Unexposed in the schema at this point as they are used only during session creation for a few calls + // When sdk implements it we an expose them for expected behaviour + // https://github.com/softlayer/softlayer-go/issues/41 RetryCount int - //Constant Retry Delay for API calls + // Constant Retry Delay for API calls RetryDelay time.Duration // FunctionNameSpace ... FunctionNameSpace string - //Riaas End point + // Riaas End point RiaasEndPoint string - //Generation + // Generation Generation int - //IAM Token + // IAM Token IAMToken string - //TrustedProfileToken Token + // TrustedProfileToken Token IAMTrustedProfileID string - //IAM Refresh Token + // IAM Refresh Token IAMRefreshToken string // Zone @@ -296,11 +291,8 @@ type ClientSession interface { AtrackerV2() (*atrackerv2.AtrackerV2, error) MetricsRouterV3() (*metricsrouterv3.MetricsRouterV3, error) ESschemaRegistrySession() (*schemaregistryv1.SchemaregistryV1, error) - AdminServiceApiV1() (*adminserviceapiv1.AdminServiceApiV1, error) - ConfigurationGovernanceV1() (*configurationgovernancev1.ConfigurationGovernanceV1, error) - PostureManagementV1() (*posturemanagementv1.PostureManagementV1, error) ContextBasedRestrictionsV1() (*contextbasedrestrictionsv1.ContextBasedRestrictionsV1, error) - PostureManagementV2() (*posturemanagementv2.PostureManagementV2, error) + SecurityAndComplianceCenterV3() (*scc.SecurityAndComplianceCenterApiV3, error) CdToolchainV2() (*cdtoolchainv2.CdToolchainV2, error) CdTektonPipelineV2() (*cdtektonpipelinev2.CdTektonPipelineV2, error) CodeEngineV2() (*codeengine.CodeEngineV2, error) @@ -526,22 +518,22 @@ type clientSession struct { // CIS WAF rule service options cisWAFRuleErr error cisWAFRuleClient *ciswafrulev1.WafRulesApiV1 - //IAM Identity Option + // IAM Identity Option iamIdentityErr error iamIdentityAPI *iamidentity.IamIdentityV1 - //Resource Manager Option + // Resource Manager Option resourceManagerErr error resourceManagerAPI *resourcemanager.ResourceManagerV2 - //Catalog Management Option + // Catalog Management Option catalogManagementClient *catalogmanagementv1.CatalogManagementV1 catalogManagementClientErr error enterpriseManagementClient *enterprisemanagementv1.EnterpriseManagementV1 enterpriseManagementClientErr error - //Resource Controller Option + // Resource Controller Option resourceControllerErr error resourceControllerAPI *resourcecontroller.ResourceControllerV2 secretsManagerClientV1 *secretsmanagerv1.SecretsManagerV1 @@ -552,15 +544,15 @@ type clientSession struct { schematicsClient *schematicsv1.SchematicsV1 schematicsClientErr error - //Satellite service + // Satellite service satelliteClient *kubernetesserviceapiv1.KubernetesServiceApiV1 satelliteClientErr error - //IAM Policy Management + // IAM Policy Management iamPolicyManagementErr error iamPolicyManagementAPI *iampolicymanagement.IamPolicyManagementV1 - //IAM Access Groups + // IAM Access Groups iamAccessGroupsErr error iamAccessGroupsAPI *iamaccessgroups.IamAccessGroupsV2 @@ -572,7 +564,7 @@ type clientSession struct { cisBotManagementClient *cisbotmanagementv1.BotManagementV1 cisBotManagementErr error - //Bot Analytics options + // Bot Analytics options cisBotAnalyticsClient *cisbotanalyticsv1.BotAnalyticsV1 cisBotAnalyticsErr error @@ -588,7 +580,7 @@ type clientSession struct { cisFirewallRulesClient *cisfirewallrulesv1.FirewallRulesV1 cisFirewallRulesErr error - //Atracker + // Atracker atrackerClientV2 *atrackerv2.AtrackerV2 atrackerClientV2Err error @@ -596,28 +588,16 @@ type clientSession struct { metricsRouterClient *metricsrouterv3.MetricsRouterV3 metricsRouterClientErr error - //Satellite link service + // Satellite link service satelliteLinkClient *satellitelinkv1.SatelliteLinkV1 satelliteLinkClientErr error esSchemaRegistryClient *schemaregistryv1.SchemaregistryV1 esSchemaRegistryErr error - // Security and Compliance Center (SCC) Admin - adminServiceApiClient *adminserviceapiv1.AdminServiceApiV1 - adminServiceApiClientErr error - - // Security and Compliance Center (SCC) Governance - configServiceApiClient *configurationgovernancev1.ConfigurationGovernanceV1 - configServiceApiClientErr error - - //Security and Compliance Center (SCC) Compliance posture - postureManagementClientErr error - postureManagementClient *posturemanagementv1.PostureManagementV1 - - //Security and Compliance Center (SCC) Compliance posture v2 - postureManagementClientv2 *posturemanagementv2.PostureManagementV2 - postureManagementClientErrv2 error + // Security and Compliance Center (SCC) + securityAndComplianceCenterClient *scc.SecurityAndComplianceCenterApiV3 + securityAndComplianceCenterClientErr error // context Based Restrictions (CBR) contextBasedRestrictionsClient *contextbasedrestrictionsv1.ContextBasedRestrictionsV1 @@ -815,14 +795,14 @@ func (sess clientSession) KeyManagementAPI() (*kp.Client, error) { if sess.kmsAPI.Config.APIKey != "" { clientConfig = &kp.ClientConfig{ BaseURL: EnvFallBack([]string{"IBMCLOUD_KP_API_ENDPOINT"}, sess.kmsAPI.Config.BaseURL), - APIKey: sess.kmsAPI.Config.APIKey, //pragma: allowlist secret + APIKey: sess.kmsAPI.Config.APIKey, // pragma: allowlist secret Verbose: kp.VerboseFailOnly, TokenURL: sess.kmsAPI.Config.TokenURL, } } else { clientConfig = &kp.ClientConfig{ BaseURL: EnvFallBack([]string{"IBMCLOUD_KP_API_ENDPOINT"}, sess.kmsAPI.Config.BaseURL), - Authorization: sess.session.BluemixSession.Config.IAMAccessToken, //pragma: allowlist secret + Authorization: sess.session.BluemixSession.Config.IAMAccessToken, // pragma: allowlist secret Verbose: kp.VerboseFailOnly, TokenURL: sess.kmsAPI.Config.TokenURL, } @@ -848,9 +828,11 @@ func (sess clientSession) VpcV1BetaAPI() (*vpcbeta.VpcbetaV1, error) { func (sess clientSession) DirectlinkV1API() (*dl.DirectLinkV1, error) { return sess.directlinkAPI, sess.directlinkErr } + func (sess clientSession) DirectlinkProviderV2API() (*dlProviderV2.DirectLinkProviderV2, error) { return sess.dlProviderAPI, sess.dlProviderErr } + func (sess clientSession) CosConfigV1API() (*cosconfig.ResourceConfigurationV1, error) { return sess.cosConfigAPI, sess.cosConfigErr } @@ -1181,28 +1163,8 @@ func (session clientSession) ESschemaRegistrySession() (*schemaregistryv1.Schema } // Security and Compliance center Admin API -func (session clientSession) AdminServiceApiV1() (*adminserviceapiv1.AdminServiceApiV1, error) { - return session.adminServiceApiClient, session.adminServiceApiClientErr -} - -func (session clientSession) ConfigurationGovernanceV1() (*configurationgovernancev1.ConfigurationGovernanceV1, error) { - return session.configServiceApiClient, session.configServiceApiClientErr -} - -// Security and Compliance center Posture Management -func (session clientSession) PostureManagementV1() (*posturemanagementv1.PostureManagementV1, error) { - if session.postureManagementClientErr != nil { - return session.postureManagementClient, session.postureManagementClientErr - } - return session.postureManagementClient.Clone(), nil -} - -// Security and Compliance center Posture Management v2 -func (session clientSession) PostureManagementV2() (*posturemanagementv2.PostureManagementV2, error) { - if session.postureManagementClientErrv2 != nil { - return session.postureManagementClientv2, session.postureManagementClientErrv2 - } - return session.postureManagementClientv2.Clone(), nil +func (session clientSession) SecurityAndComplianceCenterV3() (*scc.SecurityAndComplianceCenterApiV3, error) { + return session.securityAndComplianceCenterClient, session.securityAndComplianceCenterClientErr } // Context Based Restrictions @@ -1242,7 +1204,7 @@ func (c *Config) ClientSession() (interface{}, error) { } if sess.BluemixSession == nil { - //Can be nil only if bluemix_api_key is not provided + // Can be nil only if bluemix_api_key is not provided log.Println("Skipping Bluemix Clients configuration") session.bluemixSessionErr = errEmptyBluemixCredentials session.accountConfigErr = errEmptyBluemixCredentials @@ -1318,9 +1280,7 @@ func (c *Config) ClientSession() (interface{}, error) { session.satelliteLinkClientErr = errEmptyBluemixCredentials session.esSchemaRegistryErr = errEmptyBluemixCredentials session.contextBasedRestrictionsClientErr = errEmptyBluemixCredentials - session.postureManagementClientErr = errEmptyBluemixCredentials - session.postureManagementClientErrv2 = errEmptyBluemixCredentials - session.configServiceApiClientErr = errEmptyBluemixCredentials + session.securityAndComplianceCenterClientErr = errEmptyBluemixCredentials session.cdTektonPipelineClientErr = errEmptyBluemixCredentials session.cdToolchainClientErr = errEmptyBluemixCredentials session.codeEngineClientErr = errEmptyBluemixCredentials @@ -1456,11 +1416,10 @@ func (c *Config) ClientSession() (interface{}, error) { if c.BluemixAPIKey != "" { options = kp.ClientConfig{ BaseURL: EnvFallBack([]string{"IBMCLOUD_KP_API_ENDPOINT"}, kpurl), - APIKey: sess.BluemixSession.Config.BluemixAPIKey, //pragma: allowlist secret + APIKey: sess.BluemixSession.Config.BluemixAPIKey, // pragma: allowlist secret // InstanceID: "42fET57nnadurKXzXAedFLOhGqETfIGYxOmQXkFgkJV9", Verbose: kp.VerboseFailOnly, } - } else { options = kp.ClientConfig{ BaseURL: EnvFallBack([]string{"IBMCLOUD_KP_API_ENDPOINT"}, kpurl), @@ -1499,12 +1458,11 @@ func (c *Config) ClientSession() (interface{}, error) { if c.BluemixAPIKey != "" { kmsOptions = kp.ClientConfig{ BaseURL: EnvFallBack([]string{"IBMCLOUD_KP_API_ENDPOINT"}, kmsurl), - APIKey: sess.BluemixSession.Config.BluemixAPIKey, //pragma: allowlist secret + APIKey: sess.BluemixSession.Config.BluemixAPIKey, // pragma: allowlist secret // InstanceID: "5af62d5d-5d90-4b84-bbcd-90d2123ae6c8", Verbose: kp.VerboseFailOnly, TokenURL: EnvFallBack([]string{"IBMCLOUD_IAM_API_ENDPOINT"}, iamURL) + "/identity/token", } - } else { kmsOptions = kp.ClientConfig{ BaseURL: EnvFallBack([]string{"IBMCLOUD_KP_API_ENDPOINT"}, kmsurl), @@ -1747,35 +1705,26 @@ func (c *Config) ClientSession() (interface{}, error) { session.metricsRouterClientErr = fmt.Errorf("Error occurred while configuring Metrics Router API Version 3 service: %q", err) } - // SCC ADMIN Service - var adminServiceApiClientURL string - if c.Visibility == "private" || c.Visibility == "public-and-private" { - adminServiceApiClientURL, err = adminserviceapiv1.GetServiceURLForRegion("private." + c.Region) - if err != nil && c.Visibility == "public-and-private" { - adminServiceApiClientURL, err = adminserviceapiv1.GetServiceURLForRegion(c.Region) - } - } else { - adminServiceApiClientURL, err = adminserviceapiv1.GetServiceURLForRegion(c.Region) - } - if err != nil { - adminServiceApiClientURL = adminserviceapiv1.DefaultServiceURL - } - adminServiceApiClientOptions := &adminserviceapiv1.AdminServiceApiV1Options{ + // SCC Service + sccApiClientURL := scc.DefaultServiceURL + // Construct the service options. + + sccApiClientOptions := &scc.SecurityAndComplianceCenterApiV3Options{ Authenticator: authenticator, - URL: EnvFallBack([]string{"IBMCLOUD_SCC_ADMIN_API_ENDPOINT"}, adminServiceApiClientURL), + URL: EnvFallBack([]string{"IBMCLOUD_SCC_API_ENDPOINT"}, sccApiClientURL), } // Construct the service client. - session.adminServiceApiClient, err = adminserviceapiv1.NewAdminServiceApiV1(adminServiceApiClientOptions) + session.securityAndComplianceCenterClient, err = scc.NewSecurityAndComplianceCenterApiV3(sccApiClientOptions) if err == nil { // Enable retries for API calls - session.adminServiceApiClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) + session.securityAndComplianceCenterClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) // Add custom header for analytics - session.adminServiceApiClient.SetDefaultHeaders(gohttp.Header{ + session.securityAndComplianceCenterClient.SetDefaultHeaders(gohttp.Header{ "X-Original-User-Agent": {fmt.Sprintf("terraform-provider-ibm/%s", version.Version)}, }) } else { - session.adminServiceApiClientErr = fmt.Errorf("[ERROR] Error occurred while configuring Admin Service API service: %q", err) + session.securityAndComplianceCenterClientErr = fmt.Errorf("Error occurred while configuring Config Manager service: %q", err) } // SCHEMATICS Service @@ -2334,12 +2283,10 @@ func (c *Config) ClientSession() (interface{}, error) { Crn: core.StringPtr(""), Authenticator: authenticator, } - session.cisGLBPoolClient, session.cisGLBPoolErr = - cisglbpoolv0.NewGlobalLoadBalancerPoolsV0(cisGLBPoolOpt) + session.cisGLBPoolClient, session.cisGLBPoolErr = cisglbpoolv0.NewGlobalLoadBalancerPoolsV0(cisGLBPoolOpt) if session.cisGLBPoolErr != nil { - session.cisGLBPoolErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS GLB Pool service: %s", - session.cisGLBPoolErr) + session.cisGLBPoolErr = fmt.Errorf("[ERROR] Error occured while configuring CIS GLB Pool service: %s", + session.cisGLBPoolErr) } if session.cisGLBPoolClient != nil && session.cisGLBPoolClient.Service != nil { session.cisGLBPoolClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2357,9 +2304,8 @@ func (c *Config) ClientSession() (interface{}, error) { } session.cisGLBClient, session.cisGLBErr = cisglbv1.NewGlobalLoadBalancerV1(cisGLBOpt) if session.cisGLBErr != nil { - session.cisGLBErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS GLB service: %s", - session.cisGLBErr) + session.cisGLBErr = fmt.Errorf("[ERROR] Error occured while configuring CIS GLB service: %s", + session.cisGLBErr) } if session.cisGLBClient != nil && session.cisGLBClient.Service != nil { session.cisGLBClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2374,12 +2320,10 @@ func (c *Config) ClientSession() (interface{}, error) { Crn: core.StringPtr(""), Authenticator: authenticator, } - session.cisGLBHealthCheckClient, session.cisGLBHealthCheckErr = - cisglbhealthcheckv1.NewGlobalLoadBalancerMonitorV1(cisGLBHealthCheckOpt) + session.cisGLBHealthCheckClient, session.cisGLBHealthCheckErr = cisglbhealthcheckv1.NewGlobalLoadBalancerMonitorV1(cisGLBHealthCheckOpt) if session.cisGLBHealthCheckErr != nil { - session.cisGLBHealthCheckErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS GLB Health Check service: %s", - session.cisGLBHealthCheckErr) + session.cisGLBHealthCheckErr = fmt.Errorf("[ERROR] Error occured while configuring CIS GLB Health Check service: %s", + session.cisGLBHealthCheckErr) } if session.cisGLBHealthCheckClient != nil && session.cisGLBHealthCheckClient.Service != nil { session.cisGLBHealthCheckClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2432,9 +2376,8 @@ func (c *Config) ClientSession() (interface{}, error) { } session.cisAlertsClient, session.cisAlertsErr = cisalertsv1.NewAlertsV1(cisAlertsOpt) if session.cisAlertsErr != nil { - session.cisAlertsErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Alerts : %s", - session.cisAlertsErr) + session.cisAlertsErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Alerts : %s", + session.cisAlertsErr) } if session.cisAlertsClient != nil && session.cisAlertsClient.Service != nil { session.cisAlertsClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2470,12 +2413,10 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneIdentifier: core.StringPtr(""), Authenticator: authenticator, } - session.cisEdgeFunctionClient, session.cisEdgeFunctionErr = - cisedgefunctionv1.NewEdgeFunctionsApiV1(cisEdgeFunctionOpt) + session.cisEdgeFunctionClient, session.cisEdgeFunctionErr = cisedgefunctionv1.NewEdgeFunctionsApiV1(cisEdgeFunctionOpt) if session.cisEdgeFunctionErr != nil { - session.cisEdgeFunctionErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Edge Function service: %s", - session.cisEdgeFunctionErr) + session.cisEdgeFunctionErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Edge Function service: %s", + session.cisEdgeFunctionErr) } if session.cisEdgeFunctionClient != nil && session.cisEdgeFunctionClient.Service != nil { session.cisEdgeFunctionClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2494,9 +2435,8 @@ func (c *Config) ClientSession() (interface{}, error) { session.cisSSLClient, session.cisSSLErr = cissslv1.NewSslCertificateApiV1(cisSSLOpt) if session.cisSSLErr != nil { - session.cisSSLErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS SSL certificate service: %s", - session.cisSSLErr) + session.cisSSLErr = fmt.Errorf("[ERROR] Error occured while configuring CIS SSL certificate service: %s", + session.cisSSLErr) } if session.cisSSLClient != nil && session.cisSSLClient.Service != nil { session.cisSSLClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2512,12 +2452,10 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneID: core.StringPtr(""), Authenticator: authenticator, } - session.cisWAFPackageClient, session.cisWAFPackageErr = - ciswafpackagev1.NewWafRulePackagesApiV1(cisWAFPackageOpt) + session.cisWAFPackageClient, session.cisWAFPackageErr = ciswafpackagev1.NewWafRulePackagesApiV1(cisWAFPackageOpt) if session.cisWAFPackageErr != nil { - session.cisWAFPackageErr = - fmt.Errorf("[ERROR] Error occured while configuration CIS WAF Package service: %s", - session.cisWAFPackageErr) + session.cisWAFPackageErr = fmt.Errorf("[ERROR] Error occured while configuration CIS WAF Package service: %s", + session.cisWAFPackageErr) } if session.cisWAFPackageClient != nil && session.cisWAFPackageClient.Service != nil { session.cisWAFPackageClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2533,12 +2471,10 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneIdentifier: core.StringPtr(""), Authenticator: authenticator, } - session.cisDomainSettingsClient, session.cisDomainSettingsErr = - cisdomainsettingsv1.NewZonesSettingsV1(cisDomainSettingsOpt) + session.cisDomainSettingsClient, session.cisDomainSettingsErr = cisdomainsettingsv1.NewZonesSettingsV1(cisDomainSettingsOpt) if session.cisDomainSettingsErr != nil { - session.cisDomainSettingsErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Domain Settings service: %s", - session.cisDomainSettingsErr) + session.cisDomainSettingsErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Domain Settings service: %s", + session.cisDomainSettingsErr) } if session.cisDomainSettingsClient != nil && session.cisDomainSettingsClient.Service != nil { session.cisDomainSettingsClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2554,12 +2490,10 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneIdentifier: core.StringPtr(""), Authenticator: authenticator, } - session.cisRoutingClient, session.cisRoutingErr = - cisroutingv1.NewRoutingV1(cisRoutingOpt) + session.cisRoutingClient, session.cisRoutingErr = cisroutingv1.NewRoutingV1(cisRoutingOpt) if session.cisRoutingErr != nil { - session.cisRoutingErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Routing service: %s", - session.cisRoutingErr) + session.cisRoutingErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Routing service: %s", + session.cisRoutingErr) } if session.cisRoutingClient != nil && session.cisRoutingClient.Service != nil { session.cisRoutingClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2575,12 +2509,10 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneID: core.StringPtr(""), Authenticator: authenticator, } - session.cisWAFGroupClient, session.cisWAFGroupErr = - ciswafgroupv1.NewWafRuleGroupsApiV1(cisWAFGroupOpt) + session.cisWAFGroupClient, session.cisWAFGroupErr = ciswafgroupv1.NewWafRuleGroupsApiV1(cisWAFGroupOpt) if session.cisWAFGroupErr != nil { - session.cisWAFGroupErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS WAF Group service: %s", - session.cisWAFGroupErr) + session.cisWAFGroupErr = fmt.Errorf("[ERROR] Error occured while configuring CIS WAF Group service: %s", + session.cisWAFGroupErr) } if session.cisWAFGroupClient != nil && session.cisWAFGroupClient.Service != nil { session.cisWAFGroupClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2596,12 +2528,10 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneID: core.StringPtr(""), Authenticator: authenticator, } - session.cisCacheClient, session.cisCacheErr = - ciscachev1.NewCachingApiV1(cisCacheOpt) + session.cisCacheClient, session.cisCacheErr = ciscachev1.NewCachingApiV1(cisCacheOpt) if session.cisCacheErr != nil { - session.cisCacheErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Caching service: %s", - session.cisCacheErr) + session.cisCacheErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Caching service: %s", + session.cisCacheErr) } if session.cisCacheClient != nil && session.cisCacheClient.Service != nil { session.cisCacheClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2618,12 +2548,10 @@ func (c *Config) ClientSession() (interface{}, error) { Authenticator: authenticator, } - session.cisCustomPageClient, session.cisCustomPageErr = - ciscustompagev1.NewCustomPagesV1(cisCustomPageOpt) + session.cisCustomPageClient, session.cisCustomPageErr = ciscustompagev1.NewCustomPagesV1(cisCustomPageOpt) if session.cisCustomPageErr != nil { - session.cisCustomPageErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Custom Pages service: %s", - session.cisCustomPageErr) + session.cisCustomPageErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Custom Pages service: %s", + session.cisCustomPageErr) } if session.cisCustomPageClient != nil && session.cisCustomPageClient.Service != nil { session.cisCustomPageClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2639,12 +2567,10 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneIdentifier: core.StringPtr(""), Authenticator: authenticator, } - session.cisAccessRuleClient, session.cisAccessRuleErr = - cisaccessrulev1.NewZoneFirewallAccessRulesV1(cisAccessRuleOpt) + session.cisAccessRuleClient, session.cisAccessRuleErr = cisaccessrulev1.NewZoneFirewallAccessRulesV1(cisAccessRuleOpt) if session.cisAccessRuleErr != nil { - session.cisAccessRuleErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Firewall Access Rule service: %s", - session.cisAccessRuleErr) + session.cisAccessRuleErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Firewall Access Rule service: %s", + session.cisAccessRuleErr) } if session.cisAccessRuleClient != nil && session.cisAccessRuleClient.Service != nil { session.cisAccessRuleClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2660,12 +2586,10 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneIdentifier: core.StringPtr(""), Authenticator: authenticator, } - session.cisUARuleClient, session.cisUARuleErr = - cisuarulev1.NewUserAgentBlockingRulesV1(cisUARuleOpt) + session.cisUARuleClient, session.cisUARuleErr = cisuarulev1.NewUserAgentBlockingRulesV1(cisUARuleOpt) if session.cisUARuleErr != nil { - session.cisUARuleErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Firewall User Agent Blocking Rule service: %s", - session.cisUARuleErr) + session.cisUARuleErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Firewall User Agent Blocking Rule service: %s", + session.cisUARuleErr) } if session.cisUARuleClient != nil && session.cisUARuleClient.Service != nil { session.cisUARuleClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2681,12 +2605,10 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneIdentifier: core.StringPtr(""), Authenticator: authenticator, } - session.cisLockdownClient, session.cisLockdownErr = - cislockdownv1.NewZoneLockdownV1(cisLockdownOpt) + session.cisLockdownClient, session.cisLockdownErr = cislockdownv1.NewZoneLockdownV1(cisLockdownOpt) if session.cisLockdownErr != nil { - session.cisLockdownErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Firewall Lockdown Rule service: %s", - session.cisLockdownErr) + session.cisLockdownErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Firewall Lockdown Rule service: %s", + session.cisLockdownErr) } if session.cisLockdownClient != nil && session.cisLockdownClient.Service != nil { session.cisLockdownClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2702,12 +2624,10 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneIdentifier: core.StringPtr(""), Authenticator: authenticator, } - session.cisRangeAppClient, session.cisRangeAppErr = - cisrangeappv1.NewRangeApplicationsV1(cisRangeAppOpt) + session.cisRangeAppClient, session.cisRangeAppErr = cisrangeappv1.NewRangeApplicationsV1(cisRangeAppOpt) if session.cisRangeAppErr != nil { - session.cisRangeAppErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Range Application rule service: %s", - session.cisRangeAppErr) + session.cisRangeAppErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Range Application rule service: %s", + session.cisRangeAppErr) } if session.cisRangeAppClient != nil && session.cisRangeAppClient.Service != nil { session.cisRangeAppClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2723,8 +2643,7 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneID: core.StringPtr(""), Authenticator: authenticator, } - session.cisWAFRuleClient, session.cisWAFRuleErr = - ciswafrulev1.NewWafRulesApiV1(cisWAFRuleOpt) + session.cisWAFRuleClient, session.cisWAFRuleErr = ciswafrulev1.NewWafRulesApiV1(cisWAFRuleOpt) if session.cisWAFRuleErr != nil { session.cisWAFRuleErr = fmt.Errorf( "Error occured while configuring CIS WAF Rules service: %s", @@ -2747,9 +2666,8 @@ func (c *Config) ClientSession() (interface{}, error) { } session.cisLogpushJobsClient, session.cisLogpushJobsErr = cislogpushjobsapiv1.NewLogpushJobsApiV1(cisLogpushJobOpt) if session.cisLogpushJobsErr != nil { - session.cisLogpushJobsErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS LogpushJobs : %s", - session.cisLogpushJobsErr) + session.cisLogpushJobsErr = fmt.Errorf("[ERROR] Error occured while configuring CIS LogpushJobs : %s", + session.cisLogpushJobsErr) } if session.cisLogpushJobsClient != nil && session.cisLogpushJobsClient.Service != nil { session.cisLogpushJobsClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2766,9 +2684,8 @@ func (c *Config) ClientSession() (interface{}, error) { } session.cisMtlsClient, session.cisMtlsErr = cismtlsv1.NewMtlsV1(cisMtlsOpt) if session.cisMtlsErr != nil { - session.cisMtlsErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS MTLS : %s", - session.cisMtlsErr) + session.cisMtlsErr = fmt.Errorf("[ERROR] Error occured while configuring CIS MTLS : %s", + session.cisMtlsErr) } if session.cisMtlsClient != nil && session.cisMtlsClient.Service != nil { session.cisMtlsClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2786,9 +2703,8 @@ func (c *Config) ClientSession() (interface{}, error) { } session.cisBotManagementClient, session.cisBotManagementErr = cisbotmanagementv1.NewBotManagementV1(cisBotManagementOpt) if session.cisBotManagementErr != nil { - session.cisBotManagementErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Bot Management : %s", - session.cisBotManagementErr) + session.cisBotManagementErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Bot Management : %s", + session.cisBotManagementErr) } if session.cisBotManagementClient != nil && session.cisBotManagementClient.Service != nil { session.cisBotManagementClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2806,9 +2722,8 @@ func (c *Config) ClientSession() (interface{}, error) { } session.cisBotAnalyticsClient, session.cisBotAnalyticsErr = cisbotanalyticsv1.NewBotAnalyticsV1(cisBotAnalyticsOpt) if session.cisBotAnalyticsErr != nil { - session.cisBotAnalyticsErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Bot Anaytics : %s", - session.cisBotAnalyticsErr) + session.cisBotAnalyticsErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Bot Anaytics : %s", + session.cisBotAnalyticsErr) } if session.cisBotAnalyticsClient != nil && session.cisBotAnalyticsClient.Service != nil { session.cisBotAnalyticsClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2825,9 +2740,8 @@ func (c *Config) ClientSession() (interface{}, error) { } session.cisWebhooksClient, session.cisWebhooksErr = ciswebhooksv1.NewWebhooksV1(cisWebhooksOpt) if session.cisWebhooksErr != nil { - session.cisWebhooksErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Webhooks : %s", - session.cisWebhooksErr) + session.cisWebhooksErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Webhooks : %s", + session.cisWebhooksErr) } if session.cisWebhooksClient != nil && session.cisWebhooksClient.Service != nil { session.cisWebhooksClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2842,9 +2756,8 @@ func (c *Config) ClientSession() (interface{}, error) { } session.cisFiltersClient, session.cisFiltersErr = cisfiltersv1.NewFiltersV1(cisFiltersOpt) if session.cisFiltersErr != nil { - session.cisFiltersErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Filters : %s", - session.cisFiltersErr) + session.cisFiltersErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Filters : %s", + session.cisFiltersErr) } if session.cisFiltersClient != nil && session.cisFiltersClient.Service != nil { session.cisFiltersClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2860,9 +2773,8 @@ func (c *Config) ClientSession() (interface{}, error) { } session.cisFirewallRulesClient, session.cisFirewallRulesErr = cisfirewallrulesv1.NewFirewallRulesV1(cisFirewallrulesOpt) if session.cisFirewallRulesErr != nil { - session.cisFirewallRulesErr = - fmt.Errorf("[ERROR] Error occured while configuring CIS Firewall rules : %s", - session.cisFirewallRulesErr) + session.cisFirewallRulesErr = fmt.Errorf("[ERROR] Error occured while configuring CIS Firewall rules : %s", + session.cisFirewallRulesErr) } if session.cisFirewallRulesClient != nil && session.cisFirewallRulesClient.Service != nil { session.cisFirewallRulesClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) @@ -2879,8 +2791,7 @@ func (c *Config) ClientSession() (interface{}, error) { ZoneIdentifier: core.StringPtr(""), } - session.cisOriginAuthClient, session.cisOriginAuthPullErr = - cisoriginpull.NewAuthenticatedOriginPullApiV1(cisOriginAuthOptions) + session.cisOriginAuthClient, session.cisOriginAuthPullErr = cisoriginpull.NewAuthenticatedOriginPullApiV1(cisOriginAuthOptions) if session.cisOriginAuthPullErr != nil { session.cisOriginAuthPullErr = fmt.Errorf( "Error occured while configuring CIS Authenticated Origin Pullservice: %s", @@ -3014,7 +2925,7 @@ func (c *Config) ClientSession() (interface{}, error) { } session.resourceManagerAPI = resourceManagerClient - //CLOUD SHELL Service + // CLOUD SHELL Service cloudShellUrl := ibmcloudshellv1.DefaultServiceURL if fileMap != nil && c.Visibility != "public-and-private" { cloudShellUrl = fileFallBack(fileMap, c.Visibility, "IBMCLOUD_CLOUD_SHELL_API_ENDPOINT", c.Region, cloudShellUrl) @@ -3217,102 +3128,6 @@ func (c *Config) ClientSession() (interface{}, error) { }) } - // Governance Service - var configServiceApiClientURL string - if c.Visibility == "private" || c.Visibility == "public-and-private" { - configServiceApiClientURL, err = configurationgovernancev1.GetServiceURLForRegion("private." + c.Region) - if err != nil && c.Visibility == "public-and-private" { - configServiceApiClientURL, err = configurationgovernancev1.GetServiceURLForRegion(c.Region) - } - } else { - configServiceApiClientURL, err = configurationgovernancev1.GetServiceURLForRegion(c.Region) - } - if err != nil { - configServiceApiClientURL = configurationgovernancev1.DefaultServiceURL - } - configServiceApiClientOptions := &configurationgovernancev1.ConfigurationGovernanceV1Options{ - Authenticator: authenticator, - URL: EnvFallBack([]string{"IBMCLOUD_CONFIGURATION_GOVERNANCE_API_ENDPOINT"}, configServiceApiClientURL), - } - session.configServiceApiClient, err = configurationgovernancev1.NewConfigurationGovernanceV1(configServiceApiClientOptions) - if err == nil { - // Enable retries for API calls - session.configServiceApiClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) - // Add custom header for analytics - session.configServiceApiClient.SetDefaultHeaders(gohttp.Header{ - "X-Original-User-Agent": {fmt.Sprintf("terraform-provider-ibm/%s", version.Version)}, - }) - } else { - session.configServiceApiClientErr = fmt.Errorf("Error occurred while configuring Config Service API service: %q", err) - } - - //COMPLIANCE Service - // Construct an "options" struct for creating the service client. - var postureManagementClientURL string - if c.Visibility == "public" || c.Visibility == "public-and-private" { - postureManagementClientURL, err = posturemanagementv1.GetServiceURLForRegion(c.Region) - } else { - session.postureManagementClientErr = fmt.Errorf("[ERROR] Error occurred while configuring Security Insights Findings API service: `%v` visibility not supported", c.Visibility) - } - if err != nil { - postureManagementClientURL = posturemanagementv1.DefaultServiceURL - } - if fileMap != nil && c.Visibility != "public-and-private" { - postureManagementClientURL = fileFallBack(fileMap, c.Visibility, "IBMCLOUD_COMPLIANCE_API_ENDPOINT", c.Region, postureManagementClientURL) - } - postureManagementClientOptions := &posturemanagementv1.PostureManagementV1Options{ - Authenticator: authenticator, - URL: EnvFallBack([]string{"IBMCLOUD_COMPLIANCE_API_ENDPOINT"}, postureManagementClientURL), - AccountID: core.StringPtr(userConfig.UserAccount), - } - - // Construct the service client. - session.postureManagementClient, err = posturemanagementv1.NewPostureManagementV1(postureManagementClientOptions) - if err != nil { - session.postureManagementClientErr = fmt.Errorf("[ERROR] Error occurred while configuring Posture Management service: %q", err) - } - if session.postureManagementClient != nil && session.postureManagementClient.Service != nil { - // Enable retries for API calls - session.postureManagementClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) - // Add custom header for analytics - session.postureManagementClient.SetDefaultHeaders(gohttp.Header{ - "X-Original-User-Agent": {fmt.Sprintf("terraform-provider-ibm/%s", version.Version)}, - }) - } - - //COMPLIANCE Service v2 version - // Construct an "options" struct for creating the service client. - var postureManagementClientURLv2 string - if c.Visibility == "public" || c.Visibility == "public-and-private" { - postureManagementClientURLv2, err = posturemanagementv2.GetServiceURLForRegion(c.Region) - } else { - session.postureManagementClientErrv2 = fmt.Errorf("[ERROR] Error occurred while configuring Security Compliance Centre API service: `%v` visibility not supported", c.Visibility) - } - if err != nil { - session.postureManagementClientErrv2 = fmt.Errorf("[ERROR] Error occurred while configuring Security Posture Management API service: `%s` region not supported", c.Region) - } - if fileMap != nil && c.Visibility != "public-and-private" { - postureManagementClientURLv2 = fileFallBack(fileMap, c.Visibility, "IBMCLOUD_COMPLIANCE_API_ENDPOINT", c.Region, postureManagementClientURLv2) - } - postureManagementClientOptionsv2 := &posturemanagementv2.PostureManagementV2Options{ - Authenticator: authenticator, - URL: EnvFallBack([]string{"IBMCLOUD_COMPLIANCE_API_ENDPOINT"}, postureManagementClientURLv2), - } - - // Construct the service client. - session.postureManagementClientv2, err = posturemanagementv2.NewPostureManagementV2(postureManagementClientOptionsv2) - if err != nil { - session.postureManagementClientErrv2 = fmt.Errorf("[ERROR] Error occurred while configuring Posture Management v2 service: %q", err) - } - if session.postureManagementClientv2 != nil && session.postureManagementClientv2.Service != nil { - // Enable retries for API calls - session.postureManagementClientv2.Service.EnableRetries(c.RetryCount, c.RetryDelay) - // Add custom header for analytics - session.postureManagementClientv2.SetDefaultHeaders(gohttp.Header{ - "X-Original-User-Agent": {fmt.Sprintf("terraform-provider-ibm/%s", version.Version)}, - }) - } - // Construct an "options" struct for creating the service client. var cdToolchainClientURL string if c.Visibility == "private" || c.Visibility == "public-and-private" { @@ -3462,7 +3277,7 @@ func newSession(c *Config) (*Session, error) { bmxConfig := &bluemix.Config{ IAMAccessToken: c.IAMToken, IAMRefreshToken: c.IAMRefreshToken, - //Comment out debug mode for v0.12 + // Comment out debug mode for v0.12 Debug: os.Getenv("TF_LOG") != "", HTTPTimeout: c.BluemixTimeout, Region: c.Region, @@ -3485,7 +3300,7 @@ func newSession(c *Config) (*Session, error) { var sess *bxsession.Session bmxConfig := &bluemix.Config{ BluemixAPIKey: c.BluemixAPIKey, - //Comment out debug mode for v0.12 + // Comment out debug mode for v0.12 Debug: os.Getenv("TF_LOG") != "", HTTPTimeout: c.BluemixTimeout, Region: c.Region, @@ -3548,7 +3363,7 @@ func fetchUserDetails(sess *bxsession.Session, retries int, retryDelay time.Dura token, err := jwt.Parse(bluemixToken, func(token *jwt.Token) (interface{}, error) { return "", nil }) - //TODO validate with key + // TODO validate with key if err != nil && !strings.Contains(err.Error(), "key is of invalid type") { if retries > 0 { if config.BluemixAPIKey != "" { @@ -3601,6 +3416,7 @@ func EnvFallBack(envs []string, defaultValue string) string { } return defaultValue } + func fileFallBack(fileMap map[string]interface{}, visibility, key, region, defaultValue string) string { if val, ok := fileMap[key]; ok { if v, ok := val.(map[string]interface{})[visibility]; ok { diff --git a/ibm/provider/provider.go b/ibm/provider/provider.go index c2cf17eb5a..887ca918c9 100644 --- a/ibm/provider/provider.go +++ b/ibm/provider/provider.go @@ -179,7 +179,7 @@ func Provider() *schema.Provider { Type: schema.TypeInt, Optional: true, Description: "Generation of Virtual Private Cloud. Default is 2", - //DefaultFunc: schema.MultiEnvDefaultFunc([]string{"IC_GENERATION", "IBMCLOUD_GENERATION"}, nil), + // DefaultFunc: schema.MultiEnvDefaultFunc([]string{"IC_GENERATION", "IBMCLOUD_GENERATION"}, nil), Deprecated: "The generation field is deprecated and will be removed after couple of releases", }, "iam_profile_id": { @@ -374,7 +374,7 @@ func Provider() *schema.Provider { "ibm_iam_policy_assignments": iampolicy.DataSourceIBMIAMPolicyAssignments(), "ibm_iam_policy_assignment": iampolicy.DataSourceIBMIAMPolicyAssignment(), - //backup as Service + // backup as Service "ibm_is_backup_policy": vpc.DataSourceIBMIsBackupPolicy(), "ibm_is_backup_policies": vpc.DataSourceIBMIsBackupPolicies(), "ibm_is_backup_policy_plan": vpc.DataSourceIBMIsBackupPolicyPlan(), @@ -568,8 +568,7 @@ func Provider() *schema.Provider { "ibm_schematics_inventory": schematics.DataSourceIBMSchematicsInventory(), "ibm_schematics_resource_query": schematics.DataSourceIBMSchematicsResourceQuery(), - // // Added for Power Resources - + // Added for Power Resources "ibm_pi_catalog_images": power.DataSourceIBMPICatalogImages(), "ibm_pi_cloud_connection": power.DataSourceIBMPICloudConnection(), "ibm_pi_cloud_connections": power.DataSourceIBMPICloudConnections(), @@ -618,7 +617,7 @@ func Provider() *schema.Provider { "ibm_pi_volume_onboardings": power.DataSourceIBMPIVolumeOnboardings(), "ibm_pi_volume_onboarding": power.DataSourceIBMPIVolumeOnboarding(), - // // Added for private dns zones + // Added for private dns zones "ibm_dns_zones": dnsservices.DataSourceIBMPrivateDNSZones(), "ibm_dns_permitted_networks": dnsservices.DataSourceIBMPrivateDNSPermittedNetworks(), @@ -630,7 +629,7 @@ func Provider() *schema.Provider { "ibm_dns_custom_resolver_forwarding_rules": dnsservices.DataSourceIBMPrivateDNSForwardingRules(), "ibm_dns_custom_resolver_secondary_zones": dnsservices.DataSourceIBMPrivateDNSSecondaryZones(), - // // Added for Direct Link + // Added for Direct Link "ibm_dl_gateways": directlink.DataSourceIBMDLGateways(), "ibm_dl_offering_speeds": directlink.DataSourceIBMDLOfferingSpeeds(), @@ -648,7 +647,7 @@ func Provider() *schema.Provider { "ibm_dl_import_route_filters": directlink.DataSourceIBMDLImportRouteFilters(), "ibm_dl_import_route_filter": directlink.DataSourceIBMDLImportRouteFilter(), - // //Added for Transit Gateway + // Added for Transit Gateway "ibm_tg_gateway": transitgateway.DataSourceIBMTransitGateway(), "ibm_tg_gateways": transitgateway.DataSourceIBMTransitGateways(), "ibm_tg_connection_prefix_filter": transitgateway.DataSourceIBMTransitGatewayConnectionPrefixFilter(), @@ -658,12 +657,12 @@ func Provider() *schema.Provider { "ibm_tg_route_report": transitgateway.DataSourceIBMTransitGatewayRouteReport(), "ibm_tg_route_reports": transitgateway.DataSourceIBMTransitGatewayRouteReports(), - // //Added for BSS Enterprise + // Added for BSS Enterprise "ibm_enterprises": enterprise.DataSourceIBMEnterprises(), "ibm_enterprise_account_groups": enterprise.DataSourceIBMEnterpriseAccountGroups(), "ibm_enterprise_accounts": enterprise.DataSourceIBMEnterpriseAccounts(), - // //Added for Secrets Manager + // Added for Secrets Manager // V1 data sources: "ibm_secrets_manager_secrets": secretsmanager.DataSourceIBMSecretsManagerSecrets(), "ibm_secrets_manager_secret": secretsmanager.DataSourceIBMSecretsManagerSecret(), @@ -706,7 +705,7 @@ func Provider() *schema.Provider { "ibm_satellite_endpoint": satellite.DataSourceIBMSatelliteEndpoint(), "ibm_satellite_cluster_worker_pool_zone_attachment": satellite.DataSourceIBMSatelliteClusterWorkerPoolAttachment(), - // // Catalog related resources + // Catalog related resources "ibm_cm_catalog": catalogmanagement.DataSourceIBMCmCatalog(), "ibm_cm_offering": catalogmanagement.DataSourceIBMCmOffering(), "ibm_cm_version": catalogmanagement.DataSourceIBMCmVersion(), @@ -714,28 +713,47 @@ func Provider() *schema.Provider { "ibm_cm_preset": catalogmanagement.DataSourceIBMCmPreset(), "ibm_cm_object": catalogmanagement.DataSourceIBMCmObject(), - // //Added for Resource Tag + // Added for Resource Tag "ibm_resource_tag": globaltagging.DataSourceIBMResourceTag(), - // // Atracker + // Atracker "ibm_atracker_targets": atracker.DataSourceIBMAtrackerTargets(), "ibm_atracker_routes": atracker.DataSourceIBMAtrackerRoutes(), - // Metrics Router + // Metrics Router "ibm_metrics_router_targets": metricsrouter.DataSourceIBMMetricsRouterTargets(), "ibm_metrics_router_routes": metricsrouter.DataSourceIBMMetricsRouterRoutes(), - //Security and Compliance Center + // Security and Complaince Center(soon to be deprecated) "ibm_scc_account_location": scc.DataSourceIBMSccAccountLocation(), "ibm_scc_account_locations": scc.DataSourceIBMSccAccountLocations(), "ibm_scc_account_location_settings": scc.DataSourceIBMSccAccountLocationSettings(), "ibm_scc_account_notification_settings": scc.DataSourceIBMSccNotificationSettings(), - // // Added for Context Based Restrictions + // Security and Compliance Center + "ibm_scc_instance_settings": scc.DataSourceIbmSccInstanceSettings(), + "ibm_scc_control_library": scc.DataSourceIbmSccControlLibrary(), + "ibm_scc_profile": scc.DataSourceIbmSccProfile(), + "ibm_scc_profile_attachment": scc.DataSourceIbmSccProfileAttachment(), + "ibm_scc_provider_type": scc.DataSourceIbmSccProviderType(), + "ibm_scc_provider_type_collection": scc.DataSourceIbmSccProviderTypeCollection(), + "ibm_scc_provider_type_instance": scc.DataSourceIbmSccProviderTypeInstance(), + "ibm_scc_latest_reports": scc.DataSourceIbmSccLatestReports(), + "ibm_scc_report": scc.DataSourceIbmSccReport(), + "ibm_scc_report_controls": scc.DataSourceIbmSccReportControls(), + "ibm_scc_report_evaluations": scc.DataSourceIbmSccReportEvaluations(), + "ibm_scc_report_resources": scc.DataSourceIbmSccReportResources(), + "ibm_scc_report_rule": scc.DataSourceIbmSccReportRule(), + "ibm_scc_report_summary": scc.DataSourceIbmSccReportSummary(), + "ibm_scc_report_tags": scc.DataSourceIbmSccReportTags(), + "ibm_scc_report_violation_drift": scc.DataSourceIbmSccReportViolationDrift(), + "ibm_scc_rule": scc.DataSourceIbmSccRule(), + + // Added for Context Based Restrictions "ibm_cbr_zone": contextbasedrestrictions.DataSourceIBMCbrZone(), "ibm_cbr_rule": contextbasedrestrictions.DataSourceIBMCbrRule(), - // // Added for Event Notifications + // Added for Event Notifications "ibm_en_source": eventnotification.DataSourceIBMEnSource(), "ibm_en_destinations": eventnotification.DataSourceIBMEnDestinations(), "ibm_en_topic": eventnotification.DataSourceIBMEnTopic(), @@ -775,7 +793,7 @@ func Provider() *schema.Provider { "ibm_en_subscription_huawei": eventnotification.DataSourceIBMEnFCMSubscription(), "ibm_en_sources": eventnotification.DataSourceIBMEnSources(), - // // Added for Toolchain + // Added for Toolchain "ibm_cd_toolchain": cdtoolchain.DataSourceIBMCdToolchain(), "ibm_cd_toolchain_tool_keyprotect": cdtoolchain.DataSourceIBMCdToolchainToolKeyprotect(), "ibm_cd_toolchain_tool_secretsmanager": cdtoolchain.DataSourceIBMCdToolchainToolSecretsmanager(), @@ -828,7 +846,7 @@ func Provider() *schema.Provider { "ibm_app_domain_shared": cloudfoundry.ResourceIBMAppDomainShared(), "ibm_app_route": cloudfoundry.ResourceIBMAppRoute(), - // // AppID + // AppID "ibm_appid_action_url": appid.ResourceIBMAppIDActionURL(), "ibm_appid_apm": appid.ResourceIBMAppIDAPM(), "ibm_appid_application": appid.ResourceIBMAppIDApplication(), @@ -1100,8 +1118,7 @@ func Provider() *schema.Provider { "ibm_cdn": classicinfrastructure.ResourceIBMCDN(), "ibm_hardware_firewall_shared": classicinfrastructure.ResourceIBMFirewallShared(), - // //Added for Power Colo - + // Added for Power Colo "ibm_pi_key": power.ResourceIBMPIKey(), "ibm_pi_volume": power.ResourceIBMPIVolume(), "ibm_pi_volume_onboarding": power.ResourceIBMPIVolumeOnboarding(), @@ -1128,7 +1145,7 @@ func Provider() *schema.Provider { "ibm_pi_spp_placement_group": power.ResourceIBMPISPPPlacementGroup(), "ibm_pi_shared_processor_pool": power.ResourceIBMPISharedProcessorPool(), - // //Private DNS related resources + // Private DNS related resources "ibm_dns_zone": dnsservices.ResourceIBMPrivateDNSZone(), "ibm_dns_permitted_network": dnsservices.ResourceIBMPrivateDNSPermittedNetwork(), "ibm_dns_resource_record": dnsservices.ResourceIBMPrivateDNSResourceRecord(), @@ -1136,28 +1153,28 @@ func Provider() *schema.Provider { "ibm_dns_glb_pool": dnsservices.ResourceIBMPrivateDNSGLBPool(), "ibm_dns_glb": dnsservices.ResourceIBMPrivateDNSGLB(), - // //Added for Custom Resolver + // Added for Custom Resolver "ibm_dns_custom_resolver": dnsservices.ResourceIBMPrivateDNSCustomResolver(), "ibm_dns_custom_resolver_location": dnsservices.ResourceIBMPrivateDNSCRLocation(), "ibm_dns_custom_resolver_forwarding_rule": dnsservices.ResourceIBMPrivateDNSForwardingRule(), "ibm_dns_custom_resolver_secondary_zone": dnsservices.ResourceIBMPrivateDNSSecondaryZone(), "ibm_dns_linked_zone": dnsservices.ResourceIBMDNSLinkedZone(), - // //Direct Link related resources + // Direct Link related resources "ibm_dl_gateway": directlink.ResourceIBMDLGateway(), "ibm_dl_virtual_connection": directlink.ResourceIBMDLGatewayVC(), "ibm_dl_provider_gateway": directlink.ResourceIBMDLProviderGateway(), "ibm_dl_route_report": directlink.ResourceIBMDLGatewayRouteReport(), "ibm_dl_gateway_action": directlink.ResourceIBMDLGatewayAction(), - // //Added for Transit Gateway + // Added for Transit Gateway "ibm_tg_gateway": transitgateway.ResourceIBMTransitGateway(), "ibm_tg_connection": transitgateway.ResourceIBMTransitGatewayConnection(), "ibm_tg_connection_action": transitgateway.ResourceIBMTransitGatewayConnectionAction(), "ibm_tg_connection_prefix_filter": transitgateway.ResourceIBMTransitGatewayConnectionPrefixFilter(), "ibm_tg_route_report": transitgateway.ResourceIBMTransitGatewayRouteReport(), - // //Catalog related resources + // Catalog related resources "ibm_cm_offering_instance": catalogmanagement.ResourceIBMCmOfferingInstance(), "ibm_cm_catalog": catalogmanagement.ResourceIBMCmCatalog(), "ibm_cm_offering": catalogmanagement.ResourceIBMCmOffering(), @@ -1165,19 +1182,19 @@ func Provider() *schema.Provider { "ibm_cm_validation": catalogmanagement.ResourceIBMCmValidation(), "ibm_cm_object": catalogmanagement.ResourceIBMCmObject(), - // //Added for enterprise + // Added for enterprise "ibm_enterprise": enterprise.ResourceIBMEnterprise(), "ibm_enterprise_account_group": enterprise.ResourceIBMEnterpriseAccountGroup(), "ibm_enterprise_account": enterprise.ResourceIBMEnterpriseAccount(), - //Added for Schematics + // Added for Schematics "ibm_schematics_workspace": schematics.ResourceIBMSchematicsWorkspace(), "ibm_schematics_action": schematics.ResourceIBMSchematicsAction(), "ibm_schematics_job": schematics.ResourceIBMSchematicsJob(), "ibm_schematics_inventory": schematics.ResourceIBMSchematicsInventory(), "ibm_schematics_resource_query": schematics.ResourceIBMSchematicsResourceQuery(), - // //Added for Secrets Manager + // Added for Secrets Manager "ibm_sm_secret_group": secretsmanager.AddInstanceFields(secretsmanager.ResourceIbmSmSecretGroup()), "ibm_sm_arbitrary_secret": secretsmanager.AddInstanceFields(secretsmanager.ResourceIbmSmArbitrarySecret()), "ibm_sm_imported_certificate": secretsmanager.AddInstanceFields(secretsmanager.ResourceIbmSmImportedCertificate()), @@ -1198,7 +1215,7 @@ func Provider() *schema.Provider { "ibm_sm_private_certificate_configuration_action_sign_csr": secretsmanager.AddInstanceFields(secretsmanager.ResourceIbmSmPrivateCertificateConfigurationActionSignCsr()), "ibm_sm_private_certificate_configuration_action_set_signed": secretsmanager.AddInstanceFields(secretsmanager.ResourceIbmSmPrivateCertificateConfigurationActionSetSigned()), - // //satellite resources + // satellite resources "ibm_satellite_location": satellite.ResourceIBMSatelliteLocation(), "ibm_satellite_host": satellite.ResourceIBMSatelliteHost(), "ibm_satellite_cluster": satellite.ResourceIBMSatelliteCluster(), @@ -1208,10 +1225,10 @@ func Provider() *schema.Provider { "ibm_satellite_location_nlb_dns": satellite.ResourceIBMSatelliteLocationNlbDns(), "ibm_satellite_cluster_worker_pool_zone_attachment": satellite.ResourceIbmSatelliteClusterWorkerPoolZoneAttachment(), - //Added for Resource Tag + // Added for Resource Tag "ibm_resource_tag": globaltagging.ResourceIBMResourceTag(), - // // Atracker + // Atracker "ibm_atracker_target": atracker.ResourceIBMAtrackerTarget(), "ibm_atracker_route": atracker.ResourceIBMAtrackerRoute(), "ibm_atracker_settings": atracker.ResourceIBMAtrackerSettings(), @@ -1221,18 +1238,24 @@ func Provider() *schema.Provider { "ibm_metrics_router_route": metricsrouter.ResourceIBMMetricsRouterRoute(), "ibm_metrics_router_settings": metricsrouter.ResourceIBMMetricsRouterSettings(), - // //Security and Compliance Center + // Security and Compliance Center(soon to be deprecated) "ibm_scc_account_settings": scc.ResourceIBMSccAccountSettings(), - "ibm_scc_rule": scc.ResourceIBMSccRule(), "ibm_scc_rule_attachment": scc.ResourceIBMSccRuleAttachment(), "ibm_scc_template": scc.ResourceIBMSccTemplate(), "ibm_scc_template_attachment": scc.ResourceIBMSccTemplateAttachment(), - // // Added for Context Based Restrictions + // Security and Compliance Center + "ibm_scc_rule": scc.ResourceIbmSccRule(), + "ibm_scc_control_library": scc.ResourceIbmSccControlLibrary(), + "ibm_scc_profile": scc.ResourceIbmSccProfile(), + "ibm_scc_profile_attachment": scc.ResourceIbmSccProfileAttachment(), + "ibm_scc_provider_type_instance": scc.ResourceIbmSccProviderTypeInstance(), + + // Added for Context Based Restrictions "ibm_cbr_zone": contextbasedrestrictions.ResourceIBMCbrZone(), "ibm_cbr_rule": contextbasedrestrictions.ResourceIBMCbrRule(), - // // Added for Event Notifications + // Added for Event Notifications "ibm_en_source": eventnotification.ResourceIBMEnSource(), "ibm_en_topic": eventnotification.ResourceIBMEnTopic(), "ibm_en_destination_webhook": eventnotification.ResourceIBMEnWebhookDestination(), @@ -1268,7 +1291,7 @@ func Provider() *schema.Provider { "ibm_en_subscription_huawei": eventnotification.ResourceIBMEnFCMSubscription(), "ibm_en_ibmsource": eventnotification.ResourceIBMEnIBMSource(), - // // Added for Toolchain + // Added for Toolchain "ibm_cd_toolchain": cdtoolchain.ResourceIBMCdToolchain(), "ibm_cd_toolchain_tool_keyprotect": cdtoolchain.ResourceIBMCdToolchainToolKeyprotect(), "ibm_cd_toolchain_tool_secretsmanager": cdtoolchain.ResourceIBMCdToolchainToolSecretsmanager(), @@ -1293,14 +1316,14 @@ func Provider() *schema.Provider { "ibm_cd_toolchain_tool_jira": cdtoolchain.ResourceIBMCdToolchainToolJira(), "ibm_cd_toolchain_tool_eventnotifications": cdtoolchain.ResourceIBMCdToolchainToolEventnotifications(), - // // Added for Tekton Pipeline + // Added for Tekton Pipeline "ibm_cd_tekton_pipeline_definition": cdtektonpipeline.ResourceIBMCdTektonPipelineDefinition(), "ibm_cd_tekton_pipeline_trigger_property": cdtektonpipeline.ResourceIBMCdTektonPipelineTriggerProperty(), "ibm_cd_tekton_pipeline_property": cdtektonpipeline.ResourceIBMCdTektonPipelineProperty(), "ibm_cd_tekton_pipeline_trigger": cdtektonpipeline.ResourceIBMCdTektonPipelineTrigger(), "ibm_cd_tekton_pipeline": cdtektonpipeline.ResourceIBMCdTektonPipeline(), - // // Added for Code Engine + // Added for Code Engine "ibm_code_engine_app": codeengine.ResourceIbmCodeEngineApp(), "ibm_code_engine_binding": codeengine.ResourceIbmCodeEngineBinding(), "ibm_code_engine_build": codeengine.ResourceIbmCodeEngineBuild(), @@ -1317,8 +1340,10 @@ func Provider() *schema.Provider { } } -var globalValidatorDict validate.ValidatorDict -var initOnce sync.Once +var ( + globalValidatorDict validate.ValidatorDict + initOnce sync.Once +) func init() { validate.SetValidatorDict(Validator()) @@ -1472,16 +1497,18 @@ func Validator() validate.ValidatorDict { "ibm_metrics_router_route": metricsrouter.ResourceIBMMetricsRouterRouteValidator(), "ibm_metrics_router_settings": metricsrouter.ResourceIBMMetricsRouterSettingsValidator(), "ibm_satellite_endpoint": satellite.ResourceIBMSatelliteEndpointValidator(), - "ibm_scc_account_settings": scc.ResourceIBMSccAccountSettingsValidator(), - "ibm_scc_rule": scc.ResourceIBMSccRuleValidator(), - "ibm_scc_rule_attachment": scc.ResourceIBMSccRuleAttachmentValidator(), - "ibm_scc_template": scc.ResourceIBMSccTemplateValidator(), - "ibm_scc_template_attachment": scc.ResourceIBMSccTemplateAttachmentValidator(), "ibm_cbr_zone": contextbasedrestrictions.ResourceIBMCbrZoneValidator(), "ibm_cbr_rule": contextbasedrestrictions.ResourceIBMCbrRuleValidator(), "ibm_satellite_host": satellite.ResourceIBMSatelliteHostValidator(), - // // Added for Toolchains + // Added for SCC + "ibm_scc_rule": scc.ResourceIbmSccRuleValidator(), + "ibm_scc_control_library": scc.ResourceIbmSccControlLibraryValidator(), + "ibm_scc_profile": scc.ResourceIbmSccProfileValidator(), + "ibm_scc_profile_attachment": scc.ResourceIbmSccProfileAttachmentValidator(), + "ibm_scc_provider_type_instance": scc.ResourceIbmSccProviderTypeInstanceValidator(), + + // Added for Toolchains "ibm_cd_toolchain": cdtoolchain.ResourceIBMCdToolchainValidator(), "ibm_cd_toolchain_tool_keyprotect": cdtoolchain.ResourceIBMCdToolchainToolKeyprotectValidator(), "ibm_cd_toolchain_tool_secretsmanager": cdtoolchain.ResourceIBMCdToolchainToolSecretsmanagerValidator(), @@ -1721,7 +1748,7 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) { if err != nil { return nil, err } - //Set environment variable to be used in DiffSupressFunction + // Set environment variable to be used in DiffSupressFunction if wskEnvVal.(string) == "" { os.Setenv("FUNCTION_NAMESPACE", wskNameSpace) } diff --git a/ibm/service/scc/README.md b/ibm/service/scc/README.md index b6d110aaa9..89e10f20f3 100644 --- a/ibm/service/scc/README.md +++ b/ibm/service/scc/README.md @@ -1,4 +1,4 @@ -# Terraform IBM Provider Security and Compliance Center +# Terraform IBM Provider This area is primarily for IBM provider contributors and maintainers. For information on _using_ Terraform and the IBM provider, see the links below. @@ -6,7 +6,6 @@ This area is primarily for IBM provider contributors and maintainers. For inform ## Handy Links * [Find out about contributing](../../../CONTRIBUTING.md) to the IBM provider! * IBM Provider Docs: [Home](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs) -* IBM Provider Docs: [One of the SCC resources](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/resources/scc_account_settings) -* IBM API Docs: [IBM API Docs for SCC Admin](https://cloud.ibm.com/apidocs/security-compliance/admin) -* IBM API Docs: [IBM API Docs for SCC Posture Management](https://cloud.ibm.com/apidocs/security-compliance/posture) -* IBM SCC SDK: [IBM SDK for SCC](https://github.com/IBM/scc-go-sdk) +* IBM Provider Docs: [One of the resources](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/resources/scc_provider_type_instance) +* IBM API Docs: [IBM API Docs for ]() +* IBM SDK: [IBM SDK for ](https://github.com/IBM/appconfiguration-go-admin-sdk/tree/master/securityandcompliancecenterapisv1) diff --git a/ibm/service/scc/data_source_ibm_scc_account_location.go b/ibm/service/scc/data_source_ibm_scc_account_location.go index 06cd29f0fa..cb7f2a88cf 100644 --- a/ibm/service/scc/data_source_ibm_scc_account_location.go +++ b/ibm/service/scc/data_source_ibm_scc_account_location.go @@ -4,133 +4,11 @@ package scc import ( - "context" - "fmt" - "log" - - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/IBM/scc-go-sdk/v3/adminserviceapiv1" ) func DataSourceIBMSccAccountLocation() *schema.Resource { return &schema.Resource{ - ReadContext: dataSourceIbmSccAccountLocationRead, - Schema: map[string]*schema.Schema{ - "location_id": { - Type: schema.TypeString, - Required: true, - Description: "The programatic ID of the location that you want to work in.", - }, - "main_endpoint_url": { - Type: schema.TypeString, - Computed: true, - Description: "The base URL for the service.", - }, - "governance_endpoint_url": { - Type: schema.TypeString, - Computed: true, - Description: "The endpoint that is used to call the Configuration Governance APIs.", - }, - "results_endpoint_url": { - Type: schema.TypeString, - Computed: true, - Description: "The endpoint that is used to get the results for the Configuration Governance component.", - }, - "compliance_endpoint_url": { - Type: schema.TypeString, - Computed: true, - Description: "The endpoint that is used to call the Posture Management APIs.", - }, - "analytics_endpoint_url": { - Type: schema.TypeString, - Computed: true, - Description: "The endpoint that is used to generate analytics for the Posture Management component.", - }, - "si_endpoint_url": { - Type: schema.TypeString, - Computed: true, - Description: "The endpoint that is used to call the Security Insights APIs.", - }, - "regions": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - Description: "The programatic ID of the available regions.", - }, - }, - }, - }, - }, - } -} - -func dataSourceIbmSccAccountLocationRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - adminServiceApiClient, err := meta.(conns.ClientSession).AdminServiceApiV1() - if err != nil { - return diag.FromErr(err) - } - - getLocationOptions := &adminserviceapiv1.GetLocationOptions{} - - getLocationOptions.SetLocationID(d.Get("location_id").(string)) - - location, response, err := adminServiceApiClient.GetLocationWithContext(context, getLocationOptions) - if err != nil { - log.Printf("[DEBUG] GetLocationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetLocationWithContext failed %s\n%s", err, response)) - } - - d.SetId(*location.ID) - if err = d.Set("main_endpoint_url", location.MainEndpointURL); err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting main_endpoint_url: %s", err)) - } - if err = d.Set("governance_endpoint_url", location.GovernanceEndpointURL); err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting governance_endpoint_url: %s", err)) - } - if err = d.Set("results_endpoint_url", location.ResultsEndpointURL); err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting results_endpoint_url: %s", err)) - } - if err = d.Set("compliance_endpoint_url", location.ComplianceEndpointURL); err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting compliance_endpoint_url: %s", err)) + DeprecationMessage: "ibm_scc_account_location is no longer supported.", } - if err = d.Set("analytics_endpoint_url", location.AnalyticsEndpointURL); err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting analytics_endpoint_url: %s", err)) - } - if err = d.Set("si_endpoint_url", location.SiEndpointURL); err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting si_endpoint_url: %s", err)) - } - - if location.Regions != nil { - err = d.Set("regions", dataSourceLocationFlattenRegions(location.Regions)) - if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting regions %s", err)) - } - } - - return nil -} - -func dataSourceLocationFlattenRegions(result []adminserviceapiv1.Region) (regions []map[string]interface{}) { - for _, regionsItem := range result { - regions = append(regions, dataSourceLocationRegionsToMap(regionsItem)) - } - - return regions -} - -func dataSourceLocationRegionsToMap(regionsItem adminserviceapiv1.Region) (regionsMap map[string]interface{}) { - regionsMap = map[string]interface{}{} - - if regionsItem.ID != nil { - regionsMap["id"] = regionsItem.ID - } - - return regionsMap } diff --git a/ibm/service/scc/data_source_ibm_scc_account_location_settings.go b/ibm/service/scc/data_source_ibm_scc_account_location_settings.go index 0e8f34f8e0..b55df0b6ce 100644 --- a/ibm/service/scc/data_source_ibm_scc_account_location_settings.go +++ b/ibm/service/scc/data_source_ibm_scc_account_location_settings.go @@ -4,67 +4,11 @@ package scc import ( - "context" - "fmt" - "log" - "time" - - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/IBM/scc-go-sdk/v3/adminserviceapiv1" ) func DataSourceIBMSccAccountLocationSettings() *schema.Resource { return &schema.Resource{ - ReadContext: dataSourceIbmSccAccountLocationSettingsRead, - - Schema: map[string]*schema.Schema{ - "id": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The programatic ID of the location that you want to work in.", - }, - }, - } -} - -func dataSourceIbmSccAccountLocationSettingsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - adminServiceApiClient, err := meta.(conns.ClientSession).AdminServiceApiV1() - if err != nil { - return diag.FromErr(err) - } - - getSettingsOptions := &adminserviceapiv1.GetSettingsOptions{} - - userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() - if err != nil { - return diag.FromErr(err) - } - - getSettingsOptions.SetAccountID(userDetails.UserAccount) - - accountSettings, response, err := adminServiceApiClient.GetSettingsWithContext(context, getSettingsOptions) - if err != nil { - log.Printf("[DEBUG] GetSettingsWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSettingsWithContext failed %s\n%s", err, response)) - } - - locationSettings := accountSettings.Location - d.SetId(*accountSettings.Location.ID) - - if err = d.Set("id", locationSettings.ID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting id: %s", err)) + DeprecationMessage: "ibm_scc_account_location_settings is no longer supported.", } - - if d.HasChanges() { - d.SetId(dataSourceIbmSccAccountLocationSettingsID(d)) - } - - return nil -} - -func dataSourceIbmSccAccountLocationSettingsID(d *schema.ResourceData) string { - return time.Now().UTC().String() } diff --git a/ibm/service/scc/data_source_ibm_scc_account_location_test.go b/ibm/service/scc/data_source_ibm_scc_account_location_test.go deleted file mode 100644 index 1dc6a3ad1f..0000000000 --- a/ibm/service/scc/data_source_ibm_scc_account_location_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright IBM Corp. 2021 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc_test - -import ( - "testing" - - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" -) - -func TestAccIbmSccAccountLocationDataSourceBasic(t *testing.T) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccCheckIbmSccAccountLocationDataSourceConfigBasic(), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("data.ibm_scc_account_location.scc_account_location", "id"), - resource.TestCheckResourceAttrSet("data.ibm_scc_account_location.scc_account_location", "location_id"), - ), - }, - }, - }) -} - -func testAccCheckIbmSccAccountLocationDataSourceConfigBasic() string { - return ` - data "ibm_scc_account_location" "scc_account_location" { - location_id = "us" - } - ` -} diff --git a/ibm/service/scc/data_source_ibm_scc_account_locations.go b/ibm/service/scc/data_source_ibm_scc_account_locations.go index 15ff98ac4d..7ac6508a7c 100644 --- a/ibm/service/scc/data_source_ibm_scc_account_locations.go +++ b/ibm/service/scc/data_source_ibm_scc_account_locations.go @@ -4,162 +4,11 @@ package scc import ( - "context" - "fmt" - "log" - "time" - - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/IBM/scc-go-sdk/v3/adminserviceapiv1" ) func DataSourceIBMSccAccountLocations() *schema.Resource { return &schema.Resource{ - ReadContext: dataSourceIbmSccAccountLocationsRead, - - Schema: map[string]*schema.Schema{ - "locations": &schema.Schema{ - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The programatic ID of the location that you want to work in.", - }, - "main_endpoint_url": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The base URL for the service.", - }, - "governance_endpoint_url": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The endpoint that is used to call the Configuration Governance APIs.", - }, - "results_endpoint_url": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The endpoint that is used to get the results for the Configuration Governance component.", - }, - "compliance_endpoint_url": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The endpoint that is used to call the Posture Management APIs.", - }, - "analytics_endpoint_url": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The endpoint that is used to generate analytics for the Posture Management component.", - }, - "si_endpoint_url": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The endpoint that is used to call the Security Insights APIs.", - }, - "regions": &schema.Schema{ - Type: schema.TypeList, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The programatic ID of the available regions.", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func dataSourceIbmSccAccountLocationsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - adminServiceApiClient, err := meta.(conns.ClientSession).AdminServiceApiV1() - if err != nil { - return diag.FromErr(err) - } - - listLocationsOptions := &adminserviceapiv1.ListLocationsOptions{} - - locations, response, err := adminServiceApiClient.ListLocationsWithContext(context, listLocationsOptions) - if err != nil { - log.Printf("[DEBUG] ListLocationsWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("ListLocationsWithContext failed %s\n%s", err, response)) - } - - d.SetId(dataSourceIbmSccAccountLocationsID(d)) - - locations_lst := []map[string]interface{}{} - if locations.Locations != nil { - for _, modelItem := range locations.Locations { - modelMap, err := dataSourceIbmSccAccountLocationsLocationToMap(&modelItem) - if err != nil { - return diag.FromErr(err) - } - locations_lst = append(locations_lst, modelMap) - } - } - if err = d.Set("locations", locations_lst); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locations %s", err)) - } - - return nil -} - -// dataSourceIbmSccAccountLocationsID returns a reasonable ID for the list. -func dataSourceIbmSccAccountLocationsID(d *schema.ResourceData) string { - return time.Now().UTC().String() -} - -func dataSourceIbmSccAccountLocationsLocationToMap(model *adminserviceapiv1.Location) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - if model.ID != nil { - modelMap["id"] = *model.ID - } - if model.MainEndpointURL != nil { - modelMap["main_endpoint_url"] = *model.MainEndpointURL - } - if model.GovernanceEndpointURL != nil { - modelMap["governance_endpoint_url"] = *model.GovernanceEndpointURL - } - if model.ResultsEndpointURL != nil { - modelMap["results_endpoint_url"] = *model.ResultsEndpointURL - } - if model.ComplianceEndpointURL != nil { - modelMap["compliance_endpoint_url"] = *model.ComplianceEndpointURL - } - if model.AnalyticsEndpointURL != nil { - modelMap["analytics_endpoint_url"] = *model.AnalyticsEndpointURL - } - if model.SiEndpointURL != nil { - modelMap["si_endpoint_url"] = *model.SiEndpointURL - } - if model.Regions != nil { - regions := []map[string]interface{}{} - for _, regionsItem := range model.Regions { - regionsItemMap, err := dataSourceIbmSccAccountLocationsRegionToMap(®ionsItem) - if err != nil { - return modelMap, err - } - regions = append(regions, regionsItemMap) - } - modelMap["regions"] = regions - } - return modelMap, nil -} - -func dataSourceIbmSccAccountLocationsRegionToMap(model *adminserviceapiv1.Region) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - if model.ID != nil { - modelMap["id"] = *model.ID + DeprecationMessage: "ibm_scc_account_locations is no longer supported", } - return modelMap, nil } diff --git a/ibm/service/scc/data_source_ibm_scc_account_notification_settings.go b/ibm/service/scc/data_source_ibm_scc_account_notification_settings.go index 6732928e89..f1f07fcf87 100644 --- a/ibm/service/scc/data_source_ibm_scc_account_notification_settings.go +++ b/ibm/service/scc/data_source_ibm_scc_account_notification_settings.go @@ -4,64 +4,11 @@ package scc import ( - "context" - "fmt" - "log" - "time" - - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/IBM/scc-go-sdk/v3/adminserviceapiv1" ) func DataSourceIBMSccNotificationSettings() *schema.Resource { return &schema.Resource{ - ReadContext: dataSourceIbmSccAccountNotificationSettingsRead, - - Schema: map[string]*schema.Schema{ - "instance_crn": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The Cloud Resource Name (CRN) of the Event Notifications instance that you want to connect.", - }, - }, - } -} - -func dataSourceIbmSccAccountNotificationSettingsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - adminServiceApiClient, err := meta.(conns.ClientSession).AdminServiceApiV1() - if err != nil { - return diag.FromErr(err) - } - - getSettingsOptions := &adminserviceapiv1.GetSettingsOptions{} - - userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() - if err != nil { - return diag.FromErr(err) + DeprecationMessage: "ibm_scc_account_notification_settings is no longer supported", } - - getSettingsOptions.SetAccountID(userDetails.UserAccount) - - accountSettings, response, err := adminServiceApiClient.GetSettingsWithContext(context, getSettingsOptions) - if err != nil { - log.Printf("[DEBUG] GetSettingsWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSettingsWithContext failed %s\n%s", err, response)) - } - notificationsSettings := accountSettings.EventNotifications - - if err = d.Set("instance_crn", notificationsSettings.InstanceCrn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_crn: %s", err)) - } - - d.SetId("scc_admin_notification_settings") - - return nil -} - -// dataSourceIbmSccAccountNotificationSettingsID returns a reasonable ID for the list. -func dataSourceIbmSccAccountNotificationSettingsID(d *schema.ResourceData) string { - return time.Now().UTC().String() } diff --git a/ibm/service/scc/data_source_ibm_scc_account_notification_settings_test.go b/ibm/service/scc/data_source_ibm_scc_account_notification_settings_test.go deleted file mode 100644 index 2376102697..0000000000 --- a/ibm/service/scc/data_source_ibm_scc_account_notification_settings_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc_test - -import ( - "fmt" - "testing" - - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" -) - -func TestAccIbmSccAccountNotificationSettingsDataSourceBasic(t *testing.T) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckIbmSccAccountNotificationSettingsDataSourceConfigBasic(), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("data.ibm_scc_account_notification_settings.scc_account_notification_settings", "id"), - ), - }, - }, - }) -} - -func testAccCheckIbmSccAccountNotificationSettingsDataSourceConfigBasic() string { - return fmt.Sprintf(` - data "ibm_scc_account_notification_settings" "scc_account_notification_settings" { - } - `) -} diff --git a/ibm/service/scc/data_source_ibm_scc_control_library.go b/ibm/service/scc/data_source_ibm_scc_control_library.go new file mode 100644 index 0000000000..e5958811ec --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_control_library.go @@ -0,0 +1,505 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccControlLibrary() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccControlLibraryRead, + + Schema: map[string]*schema.Schema{ + "control_library_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The control library ID.", + }, + "account_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account ID.", + }, + "control_library_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control library name.", + }, + "control_library_description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control library description.", + }, + "control_library_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control library type.", + }, + "version_group_label": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The version group label.", + }, + "control_library_version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control library version.", + }, + "created_on": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the control library was created.", + }, + "created_by": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The user who created the control library.", + }, + "updated_on": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the control library was updated.", + }, + "updated_by": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The user who updated the control library.", + }, + "latest": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + Description: "The latest version of the control library.", + }, + "hierarchy_enabled": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + Description: "The indication of whether hierarchy is enabled for the control library.", + }, + "controls_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of controls.", + }, + "control_parents_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of parent controls in the control library.", + }, + "controls": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of controls in a control library.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the control library that contains the profile.", + }, + "control_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control name.", + }, + "control_description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control description.", + }, + "control_category": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control category.", + }, + "control_parent": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The parent control.", + }, + "control_tags": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The control tags.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "control_specifications": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The control specifications.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_specification_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control specification ID.", + }, + "responsibility": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The responsibility for managing the control.", + }, + "component_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The component ID.", + }, + "component_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The component name.", + }, + "environment": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control specifications environment.", + }, + "control_specification_description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control specifications description.", + }, + "assessments_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of assessments.", + }, + "assessments": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The assessments.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "assessment_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The assessment ID.", + }, + "assessment_method": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The assessment method.", + }, + "assessment_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The assessment type.", + }, + "assessment_description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The assessment description.", + }, + "parameter_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The parameter count.", + }, + "parameters": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The parameters.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "parameter_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The parameter name.", + }, + "parameter_display_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The parameter display name.", + }, + "parameter_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The parameter type.", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + "control_docs": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The control documentation.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_docs_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the control documentation.", + }, + "control_docs_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The type of control documentation.", + }, + }, + }, + }, + "control_requirement": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + Description: "Is this a control that can be automated or manually evaluated.", + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control status.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccControlLibraryRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getControlLibraryOptions := &securityandcompliancecenterapiv3.GetControlLibraryOptions{} + + getControlLibraryOptions.SetControlLibrariesID(d.Get("control_library_id").(string)) + + controlLibrary, response, err := securityandcompliancecenterapiClient.GetControlLibraryWithContext(context, getControlLibraryOptions) + if err != nil { + log.Printf("[DEBUG] GetControlLibraryWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetControlLibraryWithContext failed %s\n%s", err, response)) + } + + d.SetId(fmt.Sprintf("%s", *getControlLibraryOptions.ControlLibrariesID)) + + if err = d.Set("account_id", controlLibrary.AccountID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) + } + + if err = d.Set("control_library_name", controlLibrary.ControlLibraryName); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_library_name: %s", err)) + } + + if err = d.Set("control_library_description", controlLibrary.ControlLibraryDescription); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_library_description: %s", err)) + } + + if err = d.Set("control_library_type", controlLibrary.ControlLibraryType); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_library_type: %s", err)) + } + + if err = d.Set("version_group_label", controlLibrary.VersionGroupLabel); err != nil { + return diag.FromErr(fmt.Errorf("Error setting version_group_label: %s", err)) + } + + if err = d.Set("control_library_version", controlLibrary.ControlLibraryVersion); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_library_version: %s", err)) + } + + if err = d.Set("created_on", flex.DateTimeToString(controlLibrary.CreatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_on: %s", err)) + } + + if err = d.Set("created_by", controlLibrary.CreatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + } + + if err = d.Set("updated_on", flex.DateTimeToString(controlLibrary.UpdatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_on: %s", err)) + } + + if err = d.Set("updated_by", controlLibrary.UpdatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_by: %s", err)) + } + + if err = d.Set("latest", controlLibrary.Latest); err != nil { + return diag.FromErr(fmt.Errorf("Error setting latest: %s", err)) + } + + if err = d.Set("hierarchy_enabled", controlLibrary.HierarchyEnabled); err != nil { + return diag.FromErr(fmt.Errorf("Error setting hierarchy_enabled: %s", err)) + } + + if err = d.Set("controls_count", flex.IntValue(controlLibrary.ControlsCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls_count: %s", err)) + } + + if err = d.Set("control_parents_count", flex.IntValue(controlLibrary.ControlParentsCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_parents_count: %s", err)) + } + + controls := []map[string]interface{}{} + if controlLibrary.Controls != nil { + for _, modelItem := range controlLibrary.Controls { + modelMap, err := dataSourceIbmSccControlLibraryControlsInControlLibToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + controls = append(controls, modelMap) + } + } + if err = d.Set("controls", controls); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls %s", err)) + } + + return nil +} + +func dataSourceIbmSccControlLibraryControlsInControlLibToMap(model *securityandcompliancecenterapiv3.ControlsInControlLib) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlName != nil { + modelMap["control_name"] = model.ControlName + } + if model.ControlID != nil { + modelMap["control_id"] = model.ControlID + } + if model.ControlDescription != nil { + modelMap["control_description"] = model.ControlDescription + } + if model.ControlCategory != nil { + modelMap["control_category"] = model.ControlCategory + } + if model.ControlParent != nil { + modelMap["control_parent"] = model.ControlParent + } + if model.ControlTags != nil { + modelMap["control_tags"] = model.ControlTags + } + if model.ControlSpecifications != nil { + controlSpecifications := []map[string]interface{}{} + for _, controlSpecificationsItem := range model.ControlSpecifications { + controlSpecificationsItemMap, err := dataSourceIbmSccControlLibraryControlSpecificationsToMap(&controlSpecificationsItem) + if err != nil { + return modelMap, err + } + controlSpecifications = append(controlSpecifications, controlSpecificationsItemMap) + } + modelMap["control_specifications"] = controlSpecifications + } + if model.ControlDocs != nil { + controlDocsMap, err := dataSourceIbmSccControlLibraryControlDocsToMap(model.ControlDocs) + if err != nil { + return modelMap, err + } + modelMap["control_docs"] = []map[string]interface{}{controlDocsMap} + } + if model.ControlRequirement != nil { + modelMap["control_requirement"] = model.ControlRequirement + } + if model.Status != nil { + modelMap["status"] = model.Status + } + return modelMap, nil +} + +func dataSourceIbmSccControlLibraryControlSpecificationsToMap(model *securityandcompliancecenterapiv3.ControlSpecifications) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlSpecificationID != nil { + modelMap["control_specification_id"] = model.ControlSpecificationID + } + if model.Responsibility != nil { + modelMap["responsibility"] = model.Responsibility + } + if model.ComponentID != nil { + modelMap["component_id"] = model.ComponentID + } + if model.ComponentName != nil { + modelMap["component_name"] = model.ComponentName + } + if model.Environment != nil { + modelMap["environment"] = model.Environment + } + if model.ControlSpecificationDescription != nil { + modelMap["control_specification_description"] = model.ControlSpecificationDescription + } + if model.AssessmentsCount != nil { + modelMap["assessments_count"] = flex.IntValue(model.AssessmentsCount) + } + if model.Assessments != nil { + assessments := []map[string]interface{}{} + for _, assessmentsItem := range model.Assessments { + assessmentsItemMap, err := dataSourceIbmSccControlLibraryImplementationToMap(&assessmentsItem) + if err != nil { + return modelMap, err + } + assessments = append(assessments, assessmentsItemMap) + } + modelMap["assessments"] = assessments + } + return modelMap, nil +} + +func dataSourceIbmSccControlLibraryImplementationToMap(model *securityandcompliancecenterapiv3.Implementation) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AssessmentID != nil { + modelMap["assessment_id"] = model.AssessmentID + } + if model.AssessmentMethod != nil { + modelMap["assessment_method"] = model.AssessmentMethod + } + if model.AssessmentType != nil { + modelMap["assessment_type"] = model.AssessmentType + } + if model.AssessmentDescription != nil { + modelMap["assessment_description"] = model.AssessmentDescription + } + if model.ParameterCount != nil { + modelMap["parameter_count"] = flex.IntValue(model.ParameterCount) + } + if model.Parameters != nil { + parameters := []map[string]interface{}{} + for _, parametersItem := range model.Parameters { + parametersItemMap, err := dataSourceIbmSccControlLibraryParameterInfoToMap(¶metersItem) + if err != nil { + return modelMap, err + } + parameters = append(parameters, parametersItemMap) + } + modelMap["parameters"] = parameters + } + return modelMap, nil +} + +func dataSourceIbmSccControlLibraryParameterInfoToMap(model *securityandcompliancecenterapiv3.ParameterInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ParameterName != nil { + modelMap["parameter_name"] = model.ParameterName + } + if model.ParameterDisplayName != nil { + modelMap["parameter_display_name"] = model.ParameterDisplayName + } + if model.ParameterType != nil { + modelMap["parameter_type"] = model.ParameterType + } + return modelMap, nil +} + +func dataSourceIbmSccControlLibraryControlDocsToMap(model *securityandcompliancecenterapiv3.ControlDocs) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlDocsID != nil { + modelMap["control_docs_id"] = model.ControlDocsID + } + if model.ControlDocsType != nil { + modelMap["control_docs_type"] = model.ControlDocsType + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_control_library_test.go b/ibm/service/scc/data_source_ibm_scc_control_library_test.go new file mode 100644 index 0000000000..47caefc5b8 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_control_library_test.go @@ -0,0 +1,177 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccControlLibraryDataSourceBasic(t *testing.T) { + controlLibraryControlLibraryName := fmt.Sprintf("tf_control_library_name_%d", acctest.RandIntRange(10, 100)) + controlLibraryControlLibraryDescription := fmt.Sprintf("tf_control_library_description_%d", acctest.RandIntRange(10, 100)) + controlLibraryControlLibraryType := "custom" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccControlLibraryDataSourceConfigBasic(controlLibraryControlLibraryName, controlLibraryControlLibraryDescription, controlLibraryControlLibraryType), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "control_library_id"), + ), + }, + }, + }) +} + +func TestAccIbmSccControlLibraryDataSourceAllArgs(t *testing.T) { + controlLibraryControlLibraryName := fmt.Sprintf("tf_control_library_name_%d", acctest.RandIntRange(10, 100)) + controlLibraryControlLibraryDescription := fmt.Sprintf("tf_control_library_description_%d", acctest.RandIntRange(10, 100)) + controlLibraryControlLibraryType := "custom" + controlLibraryVersionGroupLabel := fmt.Sprintf("d755830f-1d83-4fab-b5d5-1dfb2b0dad1%d", acctest.RandIntRange(1, 9)) + + controlLibraryControlLibraryVersion := fmt.Sprintf("0.0.%d", acctest.RandIntRange(1, 100)) + controlLibraryLatest := "true" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccControlLibraryDataSourceConfig(controlLibraryControlLibraryName, controlLibraryControlLibraryDescription, controlLibraryControlLibraryType, controlLibraryVersionGroupLabel, controlLibraryControlLibraryVersion, controlLibraryLatest), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "account_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "control_library_name"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "control_library_description"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "control_library_type"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "version_group_label"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "control_library_version"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "created_on"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "created_by"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "updated_on"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "updated_by"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "latest"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "hierarchy_enabled"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "controls_count"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "control_parents_count"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "controls.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "controls.0.control_name"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "controls.0.control_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "controls.0.control_description"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "controls.0.control_category"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "controls.0.control_requirement"), + resource.TestCheckResourceAttrSet("data.ibm_scc_control_library.scc_control_library", "controls.0.status"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccControlLibraryDataSourceConfigBasic(controlLibraryControlLibraryName string, controlLibraryControlLibraryDescription string, controlLibraryControlLibraryType string) string { + return fmt.Sprintf(` + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "%s" + control_library_description = "%s" + control_library_type = "%s" + version_group_label = "03354ab4-03be-41c0-a469-826fc0262e78" + latest = true + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + + data "ibm_scc_control_library" "scc_control_library" { + control_library_id = ibm_scc_control_library.scc_control_library_instance.id + } + + `, controlLibraryControlLibraryName, controlLibraryControlLibraryDescription, controlLibraryControlLibraryType) +} + +func testAccCheckIbmSccControlLibraryDataSourceConfig(controlLibraryControlLibraryName string, controlLibraryControlLibraryDescription string, controlLibraryControlLibraryType string, controlLibraryVersionGroupLabel string, controlLibraryControlLibraryVersion string, controlLibraryLatest string) string { + return fmt.Sprintf(` + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "%s" + control_library_description = "%s" + control_library_type = "%s" + version_group_label = "%s" + control_library_version = "%s" + latest = %s + controls { + control_name = "SC-7" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + + data "ibm_scc_control_library" "scc_control_library" { + control_library_id = ibm_scc_control_library.scc_control_library_instance.id + } + + `, controlLibraryControlLibraryName, controlLibraryControlLibraryDescription, controlLibraryControlLibraryType, controlLibraryVersionGroupLabel, controlLibraryControlLibraryVersion, controlLibraryLatest) +} diff --git a/ibm/service/scc/data_source_ibm_scc_instance_settings.go b/ibm/service/scc/data_source_ibm_scc_instance_settings.go new file mode 100644 index 0000000000..25b0a4cf5e --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_instance_settings.go @@ -0,0 +1,162 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM/go-sdk-core/v5/core" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccInstanceSettings() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccInstanceSettingsRead, + + Schema: map[string]*schema.Schema{ + "event_notifications": { + Type: schema.TypeList, + Computed: true, + Description: "The Event Notifications settings.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "instance_crn": { + Type: schema.TypeString, + Computed: true, + Description: "The Event Notifications instance CRN.", + }, + "updated_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the Event Notifications connection was updated.", + }, + "source_id": { + Type: schema.TypeString, + Computed: true, + Description: "The connected Security and Compliance Center instance CRN.", + }, + }, + }, + }, + "object_storage": { + Type: schema.TypeList, + Computed: true, + Description: "The Cloud Object Storage settings.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "instance_crn": { + Type: schema.TypeString, + Computed: true, + Description: "The connected Cloud Object Storage instance CRN.", + }, + "bucket": { + Type: schema.TypeString, + Computed: true, + Description: "The connected Cloud Object Storage bucket name.", + }, + "bucket_location": { + Type: schema.TypeString, + Computed: true, + Description: "The connected Cloud Object Storage bucket location.", + }, + "bucket_endpoint": { + Type: schema.TypeString, + Computed: true, + Description: "The connected Cloud Object Storage bucket endpoint.", + }, + "updated_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the bucket connection was updated.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccInstanceSettingsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + adminClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getSettingsOptions := &securityandcompliancecenterapiv3.GetSettingsOptions{} + + settings, response, err := adminClient.GetSettingsWithContext(context, getSettingsOptions) + + service_url := adminClient.GetServiceURL() + d.SetId(service_url) + + if err != nil { + if response != nil && response.StatusCode == 404 { + d.SetId("") + return nil + } + log.Printf("[DEBUG] GetSettingsWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetSettingsWithContext failed %s\n%s", err, response)) + } + + if !core.IsNil(settings.EventNotifications) { + eventNotificationsMap, err := dataSourceIbmSccInstanceSettingsEventNotificationsToMap(settings.EventNotifications) + if err != nil { + return diag.FromErr(err) + } + + if err = d.Set("event_notifications", []map[string]interface{}{eventNotificationsMap}); err != nil { + return diag.FromErr(fmt.Errorf("Error setting event_notifications: %s", err)) + } + } + if !core.IsNil(settings.ObjectStorage) { + objectStorageMap, err := dataSourceIbmSccInstanceSettingsObjectStorageToMap(settings.ObjectStorage) + if err != nil { + return diag.FromErr(err) + } + if err = d.Set("object_storage", []map[string]interface{}{objectStorageMap}); err != nil { + return diag.FromErr(fmt.Errorf("Error setting object_storage: %s", err)) + } + } + return nil +} + +func dataSourceIbmSccInstanceSettingsEventNotificationsToMap(model *securityandcompliancecenterapiv3.EventNotifications) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.InstanceCrn != nil { + modelMap["instance_crn"] = model.InstanceCrn + } + if model.UpdatedOn != nil { + modelMap["updated_on"] = model.UpdatedOn.String() + } + if model.SourceID != nil { + modelMap["source_id"] = model.SourceID + } + return modelMap, nil +} + +func dataSourceIbmSccInstanceSettingsObjectStorageToMap(model *securityandcompliancecenterapiv3.ObjectStorage) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.InstanceCrn != nil { + modelMap["instance_crn"] = model.InstanceCrn + } + if model.Bucket != nil { + modelMap["bucket"] = model.Bucket + } + if model.BucketLocation != nil { + modelMap["bucket_location"] = model.BucketLocation + } + if model.BucketEndpoint != nil { + modelMap["bucket_endpoint"] = model.BucketEndpoint + } + if model.UpdatedOn != nil { + modelMap["updated_on"] = model.UpdatedOn.String() + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_instance_settings_test.go b/ibm/service/scc/data_source_ibm_scc_instance_settings_test.go new file mode 100644 index 0000000000..94f7127479 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_instance_settings_test.go @@ -0,0 +1,37 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccInstanceSettingsDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccInstanceSettingsDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_instance_settings.scc_instance_settings_tf", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_instance_settings.scc_instance_settings_tf", "event_notifications.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_instance_settings.scc_instance_settings_tf", "object_storage.#"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccInstanceSettingsDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_scc_instance_settings" "scc_instance_settings_tf" { + } + `) +} diff --git a/ibm/service/scc/data_source_ibm_scc_latest_reports.go b/ibm/service/scc/data_source_ibm_scc_latest_reports.go new file mode 100644 index 0000000000..48a732e6bb --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_latest_reports.go @@ -0,0 +1,576 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +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/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccLatestReports() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccLatestReportsRead, + + Schema: map[string]*schema.Schema{ + "sort": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "This field sorts results by using a valid sort field. To learn more, see [Sorting](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-sorting).", + }, + "home_account_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the home account.", + }, + "controls_summary": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The compliance stats.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an aggregated status for controls, specifications, assessments, and resources.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of checks.", + }, + "compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of compliant checks.", + }, + "not_compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are not compliant.", + }, + "unable_to_perform_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are unable to perform.", + }, + "user_evaluation_required_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that require a user evaluation.", + }, + }, + }, + }, + "evaluations_summary": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The evaluation stats.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an aggregated status for controls, specifications, assessments, and resources.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of evaluations.", + }, + "pass_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of passed evaluations.", + }, + "failure_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of failed evaluations.", + }, + "error_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of evaluations that started, but did not finish, and ended with errors.", + }, + "completed_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of completed evaluations.", + }, + }, + }, + }, + "score": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The compliance score.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "passed": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of successful evaluations.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of evaluations.", + }, + "percent": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The percentage of successful evaluations.", + }, + }, + }, + }, + "reports": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of reports.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the report.", + }, + "group_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The group ID that is associated with the report. The group ID combines profile, scope, and attachment IDs.", + }, + "created_on": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the report was created.", + }, + "scan_time": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the scan was run.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The type of the scan.", + }, + "cos_object": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The Cloud Object Storage object that is associated with the report.", + }, + "instance_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Instance ID.", + }, + "account": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The account that is associated with a report.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account ID.", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account name.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account type.", + }, + }, + }, + }, + "profile": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The profile information.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The profile ID.", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The profile name.", + }, + "version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The profile version.", + }, + }, + }, + }, + "attachment": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The attachment that is associated with a report.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The attachment ID.", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The name of the attachment.", + }, + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The description of the attachment.", + }, + "schedule": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The attachment schedule.", + }, + "scope": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The scope of the attachment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The unique identifier for this scope.", + }, + "environment": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The environment that relates to this scope.", + }, + "properties": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The properties that are supported for scoping by this environment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property name.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property value.", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccLatestReportsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + resultsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getLatestReportsOptions := &securityandcompliancecenterapiv3.GetLatestReportsOptions{} + + if _, ok := d.GetOk("sort"); ok { + getLatestReportsOptions.SetSort(d.Get("sort").(string)) + } + + reportLatest, response, err := resultsClient.GetLatestReportsWithContext(context, getLatestReportsOptions) + if err != nil { + log.Printf("[DEBUG] GetLatestReportsWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetLatestReportsWithContext failed %s\n%s", err, response)) + } + + d.SetId(dataSourceIbmSccLatestReportsID(d)) + + if err = d.Set("home_account_id", reportLatest.HomeAccountID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting home_account_id: %s", err)) + } + + controlsSummary := []map[string]interface{}{} + if reportLatest.ControlsSummary != nil { + modelMap, err := dataSourceIbmSccLatestReportsComplianceStatsToMap(reportLatest.ControlsSummary) + if err != nil { + return diag.FromErr(err) + } + controlsSummary = append(controlsSummary, modelMap) + } + if err = d.Set("controls_summary", controlsSummary); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls_summary %s", err)) + } + + evaluationsSummary := []map[string]interface{}{} + if reportLatest.EvaluationsSummary != nil { + modelMap, err := dataSourceIbmSccLatestReportsEvalStatsToMap(reportLatest.EvaluationsSummary) + if err != nil { + return diag.FromErr(err) + } + evaluationsSummary = append(evaluationsSummary, modelMap) + } + if err = d.Set("evaluations_summary", evaluationsSummary); err != nil { + return diag.FromErr(fmt.Errorf("Error setting evaluations_summary %s", err)) + } + + score := []map[string]interface{}{} + if reportLatest.Score != nil { + modelMap, err := dataSourceIbmSccLatestReportsComplianceScoreToMap(reportLatest.Score) + if err != nil { + return diag.FromErr(err) + } + score = append(score, modelMap) + } + if err = d.Set("score", score); err != nil { + return diag.FromErr(fmt.Errorf("Error setting score %s", err)) + } + + reports := []map[string]interface{}{} + if reportLatest.Reports != nil { + for _, modelItem := range reportLatest.Reports { + modelMap, err := dataSourceIbmSccLatestReportsReportToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + reports = append(reports, modelMap) + } + } + if err = d.Set("reports", reports); err != nil { + return diag.FromErr(fmt.Errorf("Error setting reports %s", err)) + } + + return nil +} + +// dataSourceIbmSccLatestReportsID returns a reasonable ID for the list. +func dataSourceIbmSccLatestReportsID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func dataSourceIbmSccLatestReportsComplianceStatsToMap(model *securityandcompliancecenterapiv3.ComplianceStats) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.CompliantCount != nil { + modelMap["compliant_count"] = flex.IntValue(model.CompliantCount) + } + if model.NotCompliantCount != nil { + modelMap["not_compliant_count"] = flex.IntValue(model.NotCompliantCount) + } + if model.UnableToPerformCount != nil { + modelMap["unable_to_perform_count"] = flex.IntValue(model.UnableToPerformCount) + } + if model.UserEvaluationRequiredCount != nil { + modelMap["user_evaluation_required_count"] = flex.IntValue(model.UserEvaluationRequiredCount) + } + return modelMap, nil +} + +func dataSourceIbmSccLatestReportsEvalStatsToMap(model *securityandcompliancecenterapiv3.EvalStats) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.PassCount != nil { + modelMap["pass_count"] = flex.IntValue(model.PassCount) + } + if model.FailureCount != nil { + modelMap["failure_count"] = flex.IntValue(model.FailureCount) + } + if model.ErrorCount != nil { + modelMap["error_count"] = flex.IntValue(model.ErrorCount) + } + if model.CompletedCount != nil { + modelMap["completed_count"] = flex.IntValue(model.CompletedCount) + } + return modelMap, nil +} + +func dataSourceIbmSccLatestReportsComplianceScoreToMap(model *securityandcompliancecenterapiv3.ComplianceScore) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Passed != nil { + modelMap["passed"] = flex.IntValue(model.Passed) + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.Percent != nil { + modelMap["percent"] = flex.IntValue(model.Percent) + } + return modelMap, nil +} + +func dataSourceIbmSccLatestReportsReportToMap(model *securityandcompliancecenterapiv3.Report) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.GroupID != nil { + modelMap["group_id"] = model.GroupID + } + if model.CreatedOn != nil { + modelMap["created_on"] = model.CreatedOn + } + if model.ScanTime != nil { + modelMap["scan_time"] = model.ScanTime + } + if model.Type != nil { + modelMap["type"] = model.Type + } + if model.CosObject != nil { + modelMap["cos_object"] = model.CosObject + } + if model.InstanceID != nil { + modelMap["instance_id"] = model.InstanceID + } + if model.Account != nil { + accountMap, err := dataSourceIbmSccLatestReportsAccountToMap(model.Account) + if err != nil { + return modelMap, err + } + modelMap["account"] = []map[string]interface{}{accountMap} + } + if model.Profile != nil { + profileMap, err := dataSourceIbmSccLatestReportsProfileInfoToMap(model.Profile) + if err != nil { + return modelMap, err + } + modelMap["profile"] = []map[string]interface{}{profileMap} + } + if model.Attachment != nil { + attachmentMap, err := dataSourceIbmSccLatestReportsAttachmentToMap(model.Attachment) + if err != nil { + return modelMap, err + } + modelMap["attachment"] = []map[string]interface{}{attachmentMap} + } + return modelMap, nil +} + +func dataSourceIbmSccLatestReportsAccountToMap(model *securityandcompliancecenterapiv3.Account) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Type != nil { + modelMap["type"] = model.Type + } + return modelMap, nil +} + +func dataSourceIbmSccLatestReportsProfileInfoToMap(model *securityandcompliancecenterapiv3.ProfileInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Version != nil { + modelMap["version"] = model.Version + } + return modelMap, nil +} + +func dataSourceIbmSccLatestReportsAttachmentToMap(model *securityandcompliancecenterapiv3.Attachment) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Description != nil { + modelMap["description"] = model.Description + } + if model.Schedule != nil { + modelMap["schedule"] = model.Schedule + } + if model.Scope != nil { + scope := []map[string]interface{}{} + for _, scopeItem := range model.Scope { + scopeItemMap, err := dataSourceIbmSccLatestReportsAttachmentScopeToMap(&scopeItem) + if err != nil { + return modelMap, err + } + scope = append(scope, scopeItemMap) + } + modelMap["scope"] = scope + } + return modelMap, nil +} + +func dataSourceIbmSccLatestReportsAttachmentScopeToMap(model *securityandcompliancecenterapiv3.AttachmentScope) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Environment != nil { + modelMap["environment"] = model.Environment + } + if model.Properties != nil { + properties := []map[string]interface{}{} + for _, propertiesItem := range model.Properties { + propertiesItemMap, err := dataSourceIbmSccLatestReportsScopePropertyToMap(&propertiesItem) + if err != nil { + return modelMap, err + } + properties = append(properties, propertiesItemMap) + } + modelMap["properties"] = properties + } + return modelMap, nil +} + +func dataSourceIbmSccLatestReportsScopePropertyToMap(model *securityandcompliancecenterapiv3.ScopeProperty) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Value != nil { + modelMap["value"] = model.Value + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_account_locations_test.go b/ibm/service/scc/data_source_ibm_scc_latest_reports_test.go similarity index 52% rename from ibm/service/scc/data_source_ibm_scc_account_locations_test.go rename to ibm/service/scc/data_source_ibm_scc_latest_reports_test.go index 1f539fc638..9e5babbac8 100644 --- a/ibm/service/scc/data_source_ibm_scc_account_locations_test.go +++ b/ibm/service/scc/data_source_ibm_scc_latest_reports_test.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package scc_test @@ -7,28 +7,30 @@ import ( "fmt" "testing" - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" ) -func TestAccIbmSccAccountLocationsDataSourceBasic(t *testing.T) { +func TestAccIbmSccLatestReportsDataSourceBasic(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acc.TestAccPreCheck(t) }, Providers: acc.TestAccProviders, Steps: []resource.TestStep{ resource.TestStep{ - Config: testAccCheckIbmSccAccountLocationsDataSourceConfigBasic(), + Config: testAccCheckIbmSccLatestReportsDataSourceConfigBasic(), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("data.ibm_scc_account_locations.scc_account_locations", "locations.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_latest_reports.scc_latest_reports_instance", "id"), ), }, }, }) } -func testAccCheckIbmSccAccountLocationsDataSourceConfigBasic() string { +func testAccCheckIbmSccLatestReportsDataSourceConfigBasic() string { return fmt.Sprintf(` - data "ibm_scc_account_locations" "scc_account_locations" { + data "ibm_scc_latest_reports" "scc_latest_reports_instance" { + sort = "profile_name" } `) } diff --git a/ibm/service/scc/data_source_ibm_scc_profile.go b/ibm/service/scc/data_source_ibm_scc_profile.go new file mode 100644 index 0000000000..e15120cd4d --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_profile.go @@ -0,0 +1,595 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccProfile() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccProfileRead, + + Schema: map[string]*schema.Schema{ + "profile_id": { + Type: schema.TypeString, + Required: true, + Description: "The profile ID.", + }, + "profile_name": { + Type: schema.TypeString, + Computed: true, + Description: "The profile name.", + }, + "profile_description": { + Type: schema.TypeString, + Computed: true, + Description: "The profile description.", + }, + "profile_type": { + Type: schema.TypeString, + Computed: true, + Description: "The profile type, such as custom or predefined.", + }, + "profile_version": { + Type: schema.TypeString, + Computed: true, + Description: "The version status of the profile.", + }, + "version_group_label": { + Type: schema.TypeString, + Computed: true, + Description: "The version group label of the profile.", + }, + "instance_id": { + Type: schema.TypeString, + Computed: true, + Description: "The instance ID.", + }, + "latest": { + Type: schema.TypeBool, + Computed: true, + Description: "The latest version of the profile.", + }, + "hierarchy_enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "The indication of whether hierarchy is enabled for the profile.", + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who created the profile.", + }, + "created_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the profile was created.", + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who updated the profile.", + }, + "updated_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the profile was updated.", + }, + "controls_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of controls for the profile.", + }, + "control_parents_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of parent controls for the profile.", + }, + "attachments_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of attachments related to this profile.", + }, + "controls": { + Type: schema.TypeList, + Computed: true, + Description: "The array of controls that are used to create the profile.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_library_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of the control library that contains the profile.", + }, + "control_id": { + Type: schema.TypeString, + Computed: true, + Description: "The unique ID of the control library that contains the profile.", + }, + "control_library_version": { + Type: schema.TypeString, + Computed: true, + Description: "The most recent version of the control library.", + }, + "control_name": { + Type: schema.TypeString, + Computed: true, + Description: "The control name.", + }, + "control_description": { + Type: schema.TypeString, + Computed: true, + Description: "The control description.", + }, + "control_category": { + Type: schema.TypeString, + Computed: true, + Description: "The control category.", + }, + "control_parent": { + Type: schema.TypeString, + Computed: true, + Description: "The parent control.", + }, + "control_requirement": { + Type: schema.TypeBool, + Computed: true, + Description: "Is this a control that can be automated or manually evaluated.", + }, + "control_docs": { + Type: schema.TypeList, + Computed: true, + Description: "The control documentation.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_docs_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of the control documentation.", + }, + "control_docs_type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of control documentation.", + }, + }, + }, + }, + "control_specifications_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of control specifications.", + }, + "control_specifications": { + Type: schema.TypeList, + Computed: true, + Description: "The control specifications.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_specification_id": { + Type: schema.TypeString, + Computed: true, + Description: "The control specification ID.", + }, + "responsibility": { + Type: schema.TypeString, + Computed: true, + Description: "The responsibility for managing the control.", + }, + "component_id": { + Type: schema.TypeString, + Computed: true, + Description: "The component ID.", + }, + "component_name": { + Type: schema.TypeString, + Computed: true, + Description: "The component name.", + }, + "environment": { + Type: schema.TypeString, + Computed: true, + Description: "The control specifications environment.", + }, + "control_specification_description": { + Type: schema.TypeString, + Computed: true, + Description: "The control specifications description.", + }, + "assessments_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of assessments.", + }, + "assessments": { + Type: schema.TypeList, + Computed: true, + Description: "The assessments.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "assessment_id": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment ID.", + }, + "assessment_method": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment method.", + }, + "assessment_type": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment type.", + }, + "assessment_description": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment description.", + }, + "parameter_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The parameter count.", + }, + "parameters": { + Type: schema.TypeList, + Computed: true, + Description: "The parameters.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "parameter_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter name.", + }, + "parameter_display_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter display name.", + }, + "parameter_type": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter type.", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + "default_parameters": { + Type: schema.TypeList, + Computed: true, + Description: "The default parameters of the profile.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "assessment_type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of the implementation.", + }, + "assessment_id": { + Type: schema.TypeString, + Computed: true, + Description: "The implementation ID of the parameter.", + }, + "parameter_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter name.", + }, + "parameter_default_value": { + Type: schema.TypeString, + Computed: true, + Description: "The default value of the parameter.", + }, + "parameter_display_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter display name.", + }, + "parameter_type": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter type.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccProfileRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getProfileOptions := &securityandcompliancecenterapiv3.GetProfileOptions{} + + getProfileOptions.SetProfileID(d.Get("profile_id").(string)) + + profile, response, err := securityandcompliancecenterapiClient.GetProfileWithContext(context, getProfileOptions) + if err != nil { + log.Printf("[DEBUG] GetProfileWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetProfileWithContext failed %s\n%s", err, response)) + } + + d.SetId(fmt.Sprintf("%s", *getProfileOptions.ProfileID)) + + if err = d.Set("profile_name", profile.ProfileName); err != nil { + return diag.FromErr(fmt.Errorf("Error setting profile_name: %s", err)) + } + + if err = d.Set("profile_description", profile.ProfileDescription); err != nil { + return diag.FromErr(fmt.Errorf("Error setting profile_description: %s", err)) + } + + if err = d.Set("profile_type", profile.ProfileType); err != nil { + return diag.FromErr(fmt.Errorf("Error setting profile_type: %s", err)) + } + + if err = d.Set("profile_version", profile.ProfileVersion); err != nil { + return diag.FromErr(fmt.Errorf("Error setting profile_version: %s", err)) + } + + if err = d.Set("version_group_label", profile.VersionGroupLabel); err != nil { + return diag.FromErr(fmt.Errorf("Error setting version_group_label: %s", err)) + } + + if err = d.Set("instance_id", profile.InstanceID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + } + + if err = d.Set("latest", profile.Latest); err != nil { + return diag.FromErr(fmt.Errorf("Error setting latest: %s", err)) + } + + if err = d.Set("hierarchy_enabled", profile.HierarchyEnabled); err != nil { + return diag.FromErr(fmt.Errorf("Error setting hierarchy_enabled: %s", err)) + } + + if err = d.Set("created_by", profile.CreatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + } + + if err = d.Set("created_on", flex.DateTimeToString(profile.CreatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_on: %s", err)) + } + + if err = d.Set("updated_by", profile.UpdatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_by: %s", err)) + } + + if err = d.Set("updated_on", flex.DateTimeToString(profile.UpdatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_on: %s", err)) + } + + if err = d.Set("controls_count", flex.IntValue(profile.ControlsCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls_count: %s", err)) + } + + if err = d.Set("control_parents_count", flex.IntValue(profile.ControlParentsCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_parents_count: %s", err)) + } + + if err = d.Set("attachments_count", flex.IntValue(profile.AttachmentsCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting attachments_count: %s", err)) + } + + controls := []map[string]interface{}{} + if profile.Controls != nil { + for _, modelItem := range profile.Controls { + modelMap, err := dataSourceIbmSccProfileProfileControlsToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + controls = append(controls, modelMap) + } + } + if err = d.Set("controls", controls); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls %s", err)) + } + + defaultParameters := []map[string]interface{}{} + if profile.DefaultParameters != nil { + for _, modelItem := range profile.DefaultParameters { + modelMap, err := dataSourceIbmSccProfileDefaultParametersPrototypeToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + defaultParameters = append(defaultParameters, modelMap) + } + } + if err = d.Set("default_parameters", defaultParameters); err != nil { + return diag.FromErr(fmt.Errorf("Error setting default_parameters %s", err)) + } + + return nil +} + +func dataSourceIbmSccProfileProfileControlsToMap(model *securityandcompliancecenterapiv3.ProfileControls) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlLibraryID != nil { + modelMap["control_library_id"] = model.ControlLibraryID + } + if model.ControlID != nil { + modelMap["control_id"] = model.ControlID + } + if model.ControlLibraryVersion != nil { + modelMap["control_library_version"] = model.ControlLibraryVersion + } + if model.ControlName != nil { + modelMap["control_name"] = model.ControlName + } + if model.ControlDescription != nil { + modelMap["control_description"] = model.ControlDescription + } + if model.ControlCategory != nil { + modelMap["control_category"] = model.ControlCategory + } + if model.ControlParent != nil { + modelMap["control_parent"] = model.ControlParent + } + if model.ControlRequirement != nil { + modelMap["control_requirement"] = model.ControlRequirement + } + if model.ControlDocs != nil { + controlDocsMap, err := dataSourceIbmSccProfileControlDocsToMap(model.ControlDocs) + if err != nil { + return modelMap, err + } + modelMap["control_docs"] = []map[string]interface{}{controlDocsMap} + } + if model.ControlSpecificationsCount != nil { + modelMap["control_specifications_count"] = flex.IntValue(model.ControlSpecificationsCount) + } + if model.ControlSpecifications != nil { + controlSpecifications := []map[string]interface{}{} + for _, controlSpecificationsItem := range model.ControlSpecifications { + controlSpecificationsItemMap, err := dataSourceIbmSccProfileControlSpecificationsToMap(&controlSpecificationsItem) + if err != nil { + return modelMap, err + } + controlSpecifications = append(controlSpecifications, controlSpecificationsItemMap) + } + modelMap["control_specifications"] = controlSpecifications + } + return modelMap, nil +} + +func dataSourceIbmSccProfileControlDocsToMap(model *securityandcompliancecenterapiv3.ControlDocs) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlDocsID != nil { + modelMap["control_docs_id"] = model.ControlDocsID + } + if model.ControlDocsType != nil { + modelMap["control_docs_type"] = model.ControlDocsType + } + return modelMap, nil +} + +func dataSourceIbmSccProfileControlSpecificationsToMap(model *securityandcompliancecenterapiv3.ControlSpecifications) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlSpecificationID != nil { + modelMap["control_specification_id"] = model.ControlSpecificationID + } + if model.Responsibility != nil { + modelMap["responsibility"] = model.Responsibility + } + if model.ComponentID != nil { + modelMap["component_id"] = model.ComponentID + } + if model.ComponentName != nil { + modelMap["component_name"] = model.ComponentName + } + if model.Environment != nil { + modelMap["environment"] = model.Environment + } + if model.ControlSpecificationDescription != nil { + modelMap["control_specification_description"] = model.ControlSpecificationDescription + } + if model.AssessmentsCount != nil { + modelMap["assessments_count"] = flex.IntValue(model.AssessmentsCount) + } + if model.Assessments != nil { + assessments := []map[string]interface{}{} + for _, assessmentsItem := range model.Assessments { + assessmentsItemMap, err := dataSourceIbmSccProfileImplementationToMap(&assessmentsItem) + if err != nil { + return modelMap, err + } + assessments = append(assessments, assessmentsItemMap) + } + modelMap["assessments"] = assessments + } + return modelMap, nil +} + +func dataSourceIbmSccProfileImplementationToMap(model *securityandcompliancecenterapiv3.Implementation) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AssessmentID != nil { + modelMap["assessment_id"] = model.AssessmentID + } + if model.AssessmentMethod != nil { + modelMap["assessment_method"] = model.AssessmentMethod + } + if model.AssessmentType != nil { + modelMap["assessment_type"] = model.AssessmentType + } + if model.AssessmentDescription != nil { + modelMap["assessment_description"] = model.AssessmentDescription + } + if model.ParameterCount != nil { + modelMap["parameter_count"] = flex.IntValue(model.ParameterCount) + } + if model.Parameters != nil { + parameters := []map[string]interface{}{} + for _, parametersItem := range model.Parameters { + parametersItemMap, err := dataSourceIbmSccProfileParameterInfoToMap(¶metersItem) + if err != nil { + return modelMap, err + } + parameters = append(parameters, parametersItemMap) + } + modelMap["parameters"] = parameters + } + return modelMap, nil +} + +func dataSourceIbmSccProfileParameterInfoToMap(model *securityandcompliancecenterapiv3.ParameterInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ParameterName != nil { + modelMap["parameter_name"] = model.ParameterName + } + if model.ParameterDisplayName != nil { + modelMap["parameter_display_name"] = model.ParameterDisplayName + } + if model.ParameterType != nil { + modelMap["parameter_type"] = model.ParameterType + } + return modelMap, nil +} + +func dataSourceIbmSccProfileDefaultParametersPrototypeToMap(model *securityandcompliancecenterapiv3.DefaultParametersPrototype) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AssessmentType != nil { + modelMap["assessment_type"] = model.AssessmentType + } + if model.AssessmentID != nil { + modelMap["assessment_id"] = model.AssessmentID + } + if model.ParameterName != nil { + modelMap["parameter_name"] = model.ParameterName + } + if model.ParameterDefaultValue != nil { + modelMap["parameter_default_value"] = model.ParameterDefaultValue + } + if model.ParameterDisplayName != nil { + modelMap["parameter_display_name"] = model.ParameterDisplayName + } + if model.ParameterType != nil { + modelMap["parameter_type"] = model.ParameterType + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_profile_attachment.go b/ibm/service/scc/data_source_ibm_scc_profile_attachment.go new file mode 100644 index 0000000000..c8b54847c5 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_profile_attachment.go @@ -0,0 +1,435 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccProfileAttachment() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccProfileAttachmentRead, + + Schema: map[string]*schema.Schema{ + "attachment_id": { + Type: schema.TypeString, + Required: true, + Description: "The attachment ID.", + }, + "profile_id": { + Type: schema.TypeString, + Required: true, + Description: "The profile ID.", + }, + "attachment_item_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of the attachment.", + }, + "account_id": { + Type: schema.TypeString, + Computed: true, + Description: "The account ID that is associated to the attachment.", + }, + "instance_id": { + Type: schema.TypeString, + Computed: true, + Description: "The instance ID of the account that is associated to the attachment.", + }, + "scope": { + Type: schema.TypeList, + Computed: true, + Description: "The scope payload for the multi cloud feature.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "environment": { + Type: schema.TypeString, + Computed: true, + Description: "The environment that relates to this scope.", + }, + "properties": { + Type: schema.TypeList, + Computed: true, + Description: "The properties supported for scoping by this environment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the property.", + }, + "value": { + Type: schema.TypeString, + Computed: true, + Description: "The value of the property.", + }, + }, + }, + }, + }, + }, + }, + "created_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the attachment was created.", + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who created the attachment.", + }, + "updated_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the attachment was updated.", + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who updated the attachment.", + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "The status of an attachment evaluation.", + }, + "schedule": { + Type: schema.TypeString, + Computed: true, + Description: "The schedule of an attachment evaluation.", + }, + "notifications": { + Type: schema.TypeList, + Computed: true, + Description: "The request payload of the attachment notifications.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "enabled notifications.", + }, + "controls": { + Type: schema.TypeList, + Computed: true, + Description: "The failed controls.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "threshold_limit": { + Type: schema.TypeInt, + Computed: true, + Description: "The threshold limit.", + }, + "failed_control_ids": { + Type: schema.TypeList, + Computed: true, + Description: "The failed control IDs.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + }, + }, + }, + "attachment_parameters": { + Type: schema.TypeList, + Computed: true, + Description: "The profile parameters for the attachment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "assessment_type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of the implementation.", + }, + "assessment_id": { + Type: schema.TypeString, + Computed: true, + Description: "The implementation ID of the parameter.", + }, + "parameter_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter name.", + }, + "parameter_value": { + Type: schema.TypeString, + Computed: true, + Description: "The value of the parameter.", + }, + "parameter_display_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter display name.", + }, + "parameter_type": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter type.", + }, + }, + }, + }, + "last_scan": { + Type: schema.TypeList, + Computed: true, + Description: "The details of the last scan of an attachment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of the last scan of an attachment.", + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "The status of the last scan of an attachment.", + }, + "time": { + Type: schema.TypeString, + Computed: true, + Description: "The time when the last scan started.", + }, + }, + }, + }, + "next_scan_time": { + Type: schema.TypeString, + Computed: true, + Description: "The start time of the next scan.", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the attachment.", + }, + "description": { + Type: schema.TypeString, + Computed: true, + Description: "The description for the attachment.", + }, + }, + } +} + +func dataSourceIbmSccProfileAttachmentRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getProfileAttachmentOptions := &securityandcompliancecenterapiv3.GetProfileAttachmentOptions{} + + getProfileAttachmentOptions.SetAttachmentID(d.Get("attachment_id").(string)) + getProfileAttachmentOptions.SetProfileID(d.Get("profile_id").(string)) + + attachmentItem, response, err := securityandcompliancecenterapiClient.GetProfileAttachmentWithContext(context, getProfileAttachmentOptions) + if err != nil { + log.Printf("[DEBUG] GetProfileAttachmentWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetProfileAttachmentWithContext failed %s\n%s", err, response)) + } + + d.SetId(fmt.Sprintf("%s/%s", *getProfileAttachmentOptions.AttachmentID, *getProfileAttachmentOptions.ProfileID)) + + if err = d.Set("attachment_item_id", attachmentItem.ID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting attachment_item_id: %s", err)) + } + + if err = d.Set("account_id", attachmentItem.AccountID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) + } + + if err = d.Set("instance_id", attachmentItem.InstanceID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + } + + scope := []map[string]interface{}{} + if attachmentItem.Scope != nil { + for _, modelItem := range attachmentItem.Scope { + modelMap, err := dataSourceIbmSccProfileAttachmentMultiCloudScopeToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + scope = append(scope, modelMap) + } + } + if err = d.Set("scope", scope); err != nil { + return diag.FromErr(fmt.Errorf("Error setting scope %s", err)) + } + + if err = d.Set("created_on", flex.DateTimeToString(attachmentItem.CreatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_on: %s", err)) + } + + if err = d.Set("created_by", attachmentItem.CreatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + } + + if err = d.Set("updated_on", flex.DateTimeToString(attachmentItem.UpdatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_on: %s", err)) + } + + if err = d.Set("updated_by", attachmentItem.UpdatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_by: %s", err)) + } + + if err = d.Set("status", attachmentItem.Status); err != nil { + return diag.FromErr(fmt.Errorf("Error setting status: %s", err)) + } + + if err = d.Set("schedule", attachmentItem.Schedule); err != nil { + return diag.FromErr(fmt.Errorf("Error setting schedule: %s", err)) + } + + notifications := []map[string]interface{}{} + if attachmentItem.Notifications != nil { + modelMap, err := dataSourceIbmSccProfileAttachmentAttachmentsNotificationsPrototypeToMap(attachmentItem.Notifications) + if err != nil { + return diag.FromErr(err) + } + notifications = append(notifications, modelMap) + } + if err = d.Set("notifications", notifications); err != nil { + return diag.FromErr(fmt.Errorf("Error setting notifications %s", err)) + } + + attachmentParameters := []map[string]interface{}{} + if attachmentItem.AttachmentParameters != nil { + for _, modelItem := range attachmentItem.AttachmentParameters { + modelMap, err := dataSourceIbmSccProfileAttachmentAttachmentParameterPrototypeToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + attachmentParameters = append(attachmentParameters, modelMap) + } + } + if err = d.Set("attachment_parameters", attachmentParameters); err != nil { + return diag.FromErr(fmt.Errorf("Error setting attachment_parameters %s", err)) + } + + lastScan := []map[string]interface{}{} + if attachmentItem.LastScan != nil { + modelMap, err := dataSourceIbmSccProfileAttachmentLastScanToMap(attachmentItem.LastScan) + if err != nil { + return diag.FromErr(err) + } + lastScan = append(lastScan, modelMap) + } + if err = d.Set("last_scan", lastScan); err != nil { + return diag.FromErr(fmt.Errorf("Error setting last_scan %s", err)) + } + + if err = d.Set("next_scan_time", flex.DateTimeToString(attachmentItem.NextScanTime)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting next_scan_time: %s", err)) + } + + if err = d.Set("name", attachmentItem.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + + if err = d.Set("description", attachmentItem.Description); err != nil { + return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + } + + return nil +} + +func dataSourceIbmSccProfileAttachmentMultiCloudScopeToMap(model *securityandcompliancecenterapiv3.MultiCloudScope) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["environment"] = model.Environment + properties := []map[string]interface{}{} + for _, propertiesItem := range model.Properties { + propertiesItemMap, err := dataSourceIbmSccProfileAttachmentPropertyItemToMap(&propertiesItem) + if err != nil { + return modelMap, err + } + properties = append(properties, propertiesItemMap) + } + modelMap["properties"] = properties + return modelMap, nil +} + +func dataSourceIbmSccProfileAttachmentPropertyItemToMap(model *securityandcompliancecenterapiv3.PropertyItem) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Value != nil { + modelMap["value"] = model.Value + } + return modelMap, nil +} + +func dataSourceIbmSccProfileAttachmentAttachmentsNotificationsPrototypeToMap(model *securityandcompliancecenterapiv3.AttachmentsNotificationsPrototype) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["enabled"] = model.Enabled + controlsMap, err := dataSourceIbmSccProfileAttachmentFailedControlsToMap(model.Controls) + if err != nil { + return modelMap, err + } + modelMap["controls"] = []map[string]interface{}{controlsMap} + return modelMap, nil +} + +func dataSourceIbmSccProfileAttachmentFailedControlsToMap(model *securityandcompliancecenterapiv3.FailedControls) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ThresholdLimit != nil { + modelMap["threshold_limit"] = flex.IntValue(model.ThresholdLimit) + } + if model.FailedControlIds != nil { + modelMap["failed_control_ids"] = model.FailedControlIds + } + return modelMap, nil +} + +func dataSourceIbmSccProfileAttachmentAttachmentParameterPrototypeToMap(model *securityandcompliancecenterapiv3.AttachmentParameterPrototype) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AssessmentType != nil { + modelMap["assessment_type"] = model.AssessmentType + } + if model.AssessmentID != nil { + modelMap["assessment_id"] = model.AssessmentID + } + if model.ParameterName != nil { + modelMap["parameter_name"] = model.ParameterName + } + if model.ParameterValue != nil { + modelMap["parameter_value"] = model.ParameterValue + } + if model.ParameterDisplayName != nil { + modelMap["parameter_display_name"] = model.ParameterDisplayName + } + if model.ParameterType != nil { + modelMap["parameter_type"] = model.ParameterType + } + return modelMap, nil +} + +func dataSourceIbmSccProfileAttachmentLastScanToMap(model *securityandcompliancecenterapiv3.LastScan) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.Time != nil { + modelMap["time"] = model.Time.String() + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_profile_attachment_test.go b/ibm/service/scc/data_source_ibm_scc_profile_attachment_test.go new file mode 100644 index 0000000000..b6c438b563 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_profile_attachment_test.go @@ -0,0 +1,239 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccProfileAttachmentDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccProfileAttachmentDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "attachment_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "profile_id"), + ), + }, + }, + }) +} + +func TestAccIbmSccProfileAttachmentDataSourceAllArgs(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccProfileAttachmentDataSourceConfig(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "attachment_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "profile_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "account_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "instance_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "scope.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "scope.0.environment"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "created_on"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "created_by"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "updated_on"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "updated_by"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "status"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "schedule"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "notifications.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "attachment_parameters.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "last_scan.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "next_scan_time"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "name"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile_attachment.scc_profile_attachment_instance", "description"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccProfileAttachmentDataSourceConfigBasic() string { + return fmt.Sprintf(` + + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "control_library_name" + control_library_description = "control_library_description" + control_library_type = "custom" + version_group_label = "03354ab4-03be-41c0-a469-826fc0262e78" + latest = true + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + + resource "ibm_scc_profile" "scc_profile_instance" { + profile_name = "profile_name" + profile_description = "profile_description" + profile_type = "custom" + controls { + control_library_id = resource.ibm_scc_control_library.scc_control_library_instance.id + control_id = resource.ibm_scc_control_library.scc_control_library_instance.controls[0].control_id + } + default_parameters { + } + } + + resource "ibm_scc_profile_attachment" "scc_profile_attachment_instance" { + profile_id = ibm_scc_profile.scc_profile_instance.id + name = "profile_attachment_name" + description = "profile_attachment_description" + scope { + environment = "ibm-cloud" + properties { + name = "scope_id" + value = resource.ibm_scc_control_library.scc_control_library_instance.account_id + } + properties { + name = "scope_type" + value = "account" + } + } + schedule = "every_30_days" + status = "enabled" + notifications { + enabled = false + controls { + failed_control_ids = [] + threshold_limit = 14 + } + } + } + + data "ibm_scc_profile_attachment" "scc_profile_attachment_instance" { + attachment_id = ibm_scc_profile_attachment.scc_profile_attachment_instance.attachment_id + profile_id = ibm_scc_profile_attachment.scc_profile_attachment_instance.profile_id + } + `) +} + +func testAccCheckIbmSccProfileAttachmentDataSourceConfig() string { + return fmt.Sprint(` + + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "control_library_name" + control_library_description = "control_library_description" + control_library_type = "custom" + version_group_label = "03354ab4-03be-41c0-a469-826fc0262e78" + latest = true + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + + resource "ibm_scc_profile" "scc_profile_instance" { + profile_name = "profile_name" + profile_description = "profile_description" + profile_type = "custom" + controls { + control_library_id = resource.ibm_scc_control_library.scc_control_library_instance.id + control_id = resource.ibm_scc_control_library.scc_control_library_instance.controls[0].control_id + } + default_parameters { + } + } + + resource "ibm_scc_profile_attachment" "scc_profile_attachment_instance" { + profile_id = ibm_scc_profile.scc_profile_instance.id + name = "profile_attachment_name" + description = "profile_attachment_description" + scope { + environment = "ibm-cloud" + properties { + name = "scope_id" + value = resource.ibm_scc_control_library.scc_control_library_instance.account_id + } + properties { + name = "scope_type" + value = "account" + } + } + schedule = "every_30_days" + status = "enabled" + notifications { + enabled = false + controls { + failed_control_ids = [] + threshold_limit = 14 + } + } + } + + data "ibm_scc_profile_attachment" "scc_profile_attachment_instance" { + attachment_id = ibm_scc_profile_attachment.scc_profile_attachment_instance.attachment_id + profile_id = ibm_scc_profile_attachment.scc_profile_attachment_instance.profile_id + } + `) +} diff --git a/ibm/service/scc/data_source_ibm_scc_profile_test.go b/ibm/service/scc/data_source_ibm_scc_profile_test.go new file mode 100644 index 0000000000..1d17c0abd2 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_profile_test.go @@ -0,0 +1,189 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccProfileDataSourceBasic(t *testing.T) { + profileProfileName := fmt.Sprintf("tf_profile_name_%d", acctest.RandIntRange(10, 100)) + profileProfileDescription := fmt.Sprintf("tf_profile_description_%d", acctest.RandIntRange(10, 100)) + profileProfileType := "custom" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccProfileDataSourceConfigBasic(profileProfileName, profileProfileDescription, profileProfileType), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "profile_id"), + ), + }, + }, + }) +} + +func TestAccIbmSccProfileDataSourceAllArgs(t *testing.T) { + profileProfileName := fmt.Sprintf("tf_profile_name_%d", acctest.RandIntRange(10, 100)) + profileProfileDescription := fmt.Sprintf("tf_profile_description_%d", acctest.RandIntRange(10, 100)) + profileProfileType := "custom" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccProfileDataSourceConfig(profileProfileName, profileProfileDescription, profileProfileType), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "profile_name"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "profile_description"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "profile_type"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "profile_version"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "version_group_label"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "instance_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "latest"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "hierarchy_enabled"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "created_by"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "created_on"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "updated_by"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "updated_on"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "controls_count"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "control_parents_count"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "attachments_count"), + resource.TestCheckResourceAttrSet("data.ibm_scc_profile.scc_profile_instance", "controls.#"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccProfileDataSourceConfigBasic(profileProfileName string, profileProfileDescription string, profileProfileType string) string { + return fmt.Sprintf(` + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "control_library_name" + control_library_description = "control_library_description" + control_library_type = "custom" + version_group_label = "03354ab4-03be-41c0-a469-826fc0262e78" + latest = true + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + + resource "ibm_scc_profile" "scc_profile_instance" { + profile_name = "%s" + profile_description = "%s" + profile_type = "%s" + controls { + control_library_id = resource.ibm_scc_control_library.scc_control_library_instance.id + control_id = resource.ibm_scc_control_library.scc_control_library_instance.controls[0].control_id + } + default_parameters { + } + } + + data "ibm_scc_profile" "scc_profile_instance" { + profile_id = ibm_scc_profile.scc_profile_instance.id + } + `, profileProfileName, profileProfileDescription, profileProfileType) +} + +func testAccCheckIbmSccProfileDataSourceConfig(profileProfileName string, profileProfileDescription string, profileProfileType string) string { + return fmt.Sprintf(` + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "control_library_name" + control_library_description = "control_library_description" + control_library_type = "custom" + version_group_label = "03354ab4-03be-41c0-a469-826fc0262e78" + latest = true + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + + resource "ibm_scc_profile" "scc_profile_instance" { + profile_name = "%s" + profile_description = "%s" + profile_type = "%s" + controls { + control_library_id = resource.ibm_scc_control_library.scc_control_library_instance.id + control_id = resource.ibm_scc_control_library.scc_control_library_instance.controls[0].control_id + } + default_parameters { + } + } + + data "ibm_scc_profile" "scc_profile_instance" { + profile_id = ibm_scc_profile.scc_profile_instance.id + } + `, profileProfileName, profileProfileDescription, profileProfileType) +} diff --git a/ibm/service/scc/data_source_ibm_scc_provider_type.go b/ibm/service/scc/data_source_ibm_scc_provider_type.go new file mode 100644 index 0000000000..6e3bfffe0c --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_provider_type.go @@ -0,0 +1,222 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccProviderType() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccProviderTypeRead, + + Schema: map[string]*schema.Schema{ + "provider_type_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The provider type ID.", + }, + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The unique identifier of the provider type.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The type of the provider type.", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The name of the provider type.", + }, + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The provider type description.", + }, + "s2s_enabled": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + Description: "A boolean that indicates whether the provider type is s2s-enabled.", + }, + "instance_limit": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The maximum number of instances that can be created for the provider type.", + }, + "mode": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The mode that is used to get results from provider (`PUSH` or `PULL`).", + }, + "data_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The format of the results that a provider supports.", + }, + "icon": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The icon of a provider in .svg format that is encoded as a base64 string.", + }, + "label": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The label that is associated with the provider type.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "text": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The text of the label.", + }, + "tip": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The text to be shown when user hover overs the label.", + }, + }, + }, + }, + "attributes": &schema.Schema{ + Type: schema.TypeMap, + Computed: true, + Description: "The attributes that are required when you're creating an instance of a provider type. The attributes field can have multiple keys in its value. Each of those keys has a value object that includes the type, and display name as keys. For example, `{type:\"\", display_name:\"\"}`. **NOTE;** If the provider type is s2s-enabled, which means that if the `s2s_enabled` field is set to `true`, then a CRN field of type text is required in the attributes value object.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "created_at": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Time at which resource was created.", + }, + "updated_at": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Time at which resource was updated.", + }, + }, + } +} + +func dataSourceIbmSccProviderTypeRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityAndComplianceCenterApIsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getProviderTypeByIdOptions := &securityandcompliancecenterapiv3.GetProviderTypeByIdOptions{} + + getProviderTypeByIdOptions.SetProviderTypeID(d.Get("provider_type_id").(string)) + + providerTypeItem, response, err := securityAndComplianceCenterApIsClient.GetProviderTypeByIDWithContext(context, getProviderTypeByIdOptions) + if err != nil { + log.Printf("[DEBUG] GetProviderTypeByIDWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetProviderTypeByIDWithContext failed %s\n%s", err, response)) + } + + d.SetId(*providerTypeItem.ID) + + if err = d.Set("id", providerTypeItem.ID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting id: %s", err)) + } + + if err = d.Set("type", providerTypeItem.Type); err != nil { + return diag.FromErr(fmt.Errorf("Error setting type: %s", err)) + } + + if err = d.Set("name", providerTypeItem.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + + if err = d.Set("description", providerTypeItem.Description); err != nil { + return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + } + + if err = d.Set("s2s_enabled", providerTypeItem.S2sEnabled); err != nil { + return diag.FromErr(fmt.Errorf("Error setting s2s_enabled: %s", err)) + } + + if err = d.Set("instance_limit", flex.IntValue(providerTypeItem.InstanceLimit)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting instance_limit: %s", err)) + } + + if err = d.Set("mode", providerTypeItem.Mode); err != nil { + return diag.FromErr(fmt.Errorf("Error setting mode: %s", err)) + } + + if err = d.Set("data_type", providerTypeItem.DataType); err != nil { + return diag.FromErr(fmt.Errorf("Error setting data_type: %s", err)) + } + + if err = d.Set("icon", providerTypeItem.Icon); err != nil { + return diag.FromErr(fmt.Errorf("Error setting icon: %s", err)) + } + + label := []map[string]interface{}{} + if providerTypeItem.Label != nil { + modelMap, err := dataSourceIbmSccProviderTypeLabelTypeToMap(providerTypeItem.Label) + if err != nil { + return diag.FromErr(err) + } + label = append(label, modelMap) + } + if err = d.Set("label", label); err != nil { + return diag.FromErr(fmt.Errorf("Error setting label %s", err)) + } + + if providerTypeItem.Attributes != nil { + convertedMap := make(map[string]interface{}, len(providerTypeItem.Attributes)) + for k, v := range providerTypeItem.Attributes { + convertedMap[k] = v + } + + if err = d.Set("attributes", flex.Flatten(convertedMap)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting attributes: %s", err)) + } + if err != nil { + return diag.FromErr(fmt.Errorf("Error setting attributes %s", err)) + } + } + + if err = d.Set("created_at", flex.DateTimeToString(providerTypeItem.CreatedAt)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + } + + if err = d.Set("updated_at", flex.DateTimeToString(providerTypeItem.UpdatedAt)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + } + + return nil +} + +func dataSourceIbmSccProviderTypeLabelTypeToMap(model *securityandcompliancecenterapiv3.LabelType) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Text != nil { + modelMap["text"] = model.Text + } + if model.Tip != nil { + modelMap["tip"] = model.Tip + } + return modelMap, nil +} + +func dataSourceIbmSccProviderTypeAdditionalPropertyToMap(model *securityandcompliancecenterapiv3.AdditionalProperty) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["type"] = model.Type + modelMap["display_name"] = model.DisplayName + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_provider_type_collection.go b/ibm/service/scc/data_source_ibm_scc_provider_type_collection.go new file mode 100644 index 0000000000..6cd8ad1e0f --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_provider_type_collection.go @@ -0,0 +1,211 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "encoding/json" + "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/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccProviderTypeCollection() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccProviderTypeCollectionRead, + + Schema: map[string]*schema.Schema{ + "provider_types": { + Type: schema.TypeList, + Computed: true, + Description: "The array of provder type.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + Description: "The unique identifier of the provider type.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of the provider type.", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the provider type.", + }, + "description": { + Type: schema.TypeString, + Computed: true, + Description: "The provider type description.", + }, + "s2s_enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "A boolean that indicates whether the provider type is s2s-enabled.", + }, + "instance_limit": { + Type: schema.TypeInt, + Computed: true, + Description: "The maximum number of instances that can be created for the provider type.", + }, + "mode": { + Type: schema.TypeString, + Computed: true, + Description: "The mode that is used to get results from provider (`PUSH` or `PULL`).", + }, + "data_type": { + Type: schema.TypeString, + Computed: true, + Description: "The format of the results that a provider supports.", + }, + "icon": { + Type: schema.TypeString, + Computed: true, + Description: "The icon of a provider in .svg format that is encoded as a base64 string.", + }, + "label": { + Type: schema.TypeList, + Computed: true, + Description: "The label that is associated with the provider type.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "text": { + Type: schema.TypeString, + Computed: true, + Description: "The text of the label.", + }, + "tip": { + Type: schema.TypeString, + Computed: true, + Description: "The text to be shown when user hover overs the label.", + }, + }, + }, + }, + "attributes": { + Type: schema.TypeMap, + Computed: true, + Description: "The attributes that are required when you're creating an instance of a provider type. The attributes field can have multiple keys in its value. Each of those keys has a value object that includes the type, and display name as keys. For example, `{type:\"\", display_name:\"\"}`. **NOTE;** If the provider type is s2s-enabled, which means that if the `s2s_enabled` field is set to `true`, then a CRN field of type text is required in the attributes value object.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "created_at": { + Type: schema.TypeString, + Computed: true, + Description: "Time at which resource was created.", + }, + "updated_at": { + Type: schema.TypeString, + Computed: true, + Description: "Time at which resource was updated.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccProviderTypeCollectionRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityAndComplianceCenterApIsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + listProviderTypesOptions := &securityandcompliancecenterapiv3.ListProviderTypesOptions{} + + providerTypesCollection, response, err := securityAndComplianceCenterApIsClient.ListProviderTypesWithContext(context, listProviderTypesOptions) + if err != nil { + log.Printf("[DEBUG] ListProviderTypesWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("ListProviderTypesWithContext failed %s\n%s", err, response)) + } + + d.SetId(dataSourceIbmSccProviderTypeCollectionID(d)) + + providerTypes := []map[string]interface{}{} + if providerTypesCollection.ProviderTypes != nil { + for _, modelItem := range providerTypesCollection.ProviderTypes { + modelMap, err := dataSourceIbmSccProviderTypeCollectionProviderTypeItemToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + providerTypes = append(providerTypes, modelMap) + } + } + if err = d.Set("provider_types", providerTypes); err != nil { + return diag.FromErr(fmt.Errorf("Error setting provider_types %s", err)) + } + + return nil +} + +// dataSourceIbmSccProviderTypeCollectionID returns a reasonable ID for the list. +func dataSourceIbmSccProviderTypeCollectionID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func dataSourceIbmSccProviderTypeCollectionProviderTypeItemToMap(model *securityandcompliancecenterapiv3.ProviderTypeItem) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["id"] = model.ID + modelMap["type"] = model.Type + modelMap["name"] = model.Name + modelMap["description"] = model.Description + modelMap["s2s_enabled"] = model.S2sEnabled + modelMap["instance_limit"] = flex.IntValue(model.InstanceLimit) + modelMap["mode"] = model.Mode + modelMap["data_type"] = model.DataType + modelMap["icon"] = model.Icon + if model.Label != nil { + labelMap, err := dataSourceIbmSccProviderTypeCollectionLabelTypeToMap(model.Label) + if err != nil { + return modelMap, err + } + modelMap["label"] = []map[string]interface{}{labelMap} + } + attributes := make(map[string]interface{}) + for k, v := range model.Attributes { + bytes, err := json.Marshal(v) + if err != nil { + return modelMap, err + } + attributes[k] = string(bytes) + } + modelMap["attributes"] = attributes + if model.CreatedAt != nil { + modelMap["created_at"] = model.CreatedAt.String() + } + if model.UpdatedAt != nil { + modelMap["updated_at"] = model.UpdatedAt.String() + } + return modelMap, nil +} + +func dataSourceIbmSccProviderTypeCollectionLabelTypeToMap(model *securityandcompliancecenterapiv3.LabelType) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Text != nil { + modelMap["text"] = model.Text + } + if model.Tip != nil { + modelMap["tip"] = model.Tip + } + return modelMap, nil +} + +func dataSourceIbmSccProviderTypeCollectionAdditionalPropertyToMap(model *securityandcompliancecenterapiv3.AdditionalProperty) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["type"] = model.Type + modelMap["display_name"] = model.DisplayName + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_account_location_settings_test.go b/ibm/service/scc/data_source_ibm_scc_provider_type_collection_test.go similarity index 50% rename from ibm/service/scc/data_source_ibm_scc_account_location_settings_test.go rename to ibm/service/scc/data_source_ibm_scc_provider_type_collection_test.go index 40a66ed239..e40969244f 100644 --- a/ibm/service/scc/data_source_ibm_scc_account_location_settings_test.go +++ b/ibm/service/scc/data_source_ibm_scc_provider_type_collection_test.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package scc_test @@ -7,28 +7,29 @@ import ( "fmt" "testing" - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" ) -func TestAccIbmSccAccountLocationSettingsDataSourceBasic(t *testing.T) { +func TestAccIbmSccProviderTypeCollectionDataSourceBasic(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acc.TestAccPreCheck(t) }, Providers: acc.TestAccProviders, Steps: []resource.TestStep{ resource.TestStep{ - Config: testAccCheckIbmSccAccountLocationSettingsDataSourceConfigBasic(), + Config: testAccCheckIbmSccProviderTypeCollectionDataSourceConfigBasic(), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("data.ibm_scc_account_location_settings.scc_account_location_settings", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_collection.scc_provider_type_collection_instance", "id"), ), }, }, }) } -func testAccCheckIbmSccAccountLocationSettingsDataSourceConfigBasic() string { +func testAccCheckIbmSccProviderTypeCollectionDataSourceConfigBasic() string { return fmt.Sprintf(` - data "ibm_scc_account_location_settings" "scc_account_location_settings" { + data "ibm_scc_provider_type_collection" "scc_provider_type_collection_instance" { } `) } diff --git a/ibm/service/scc/data_source_ibm_scc_provider_type_instance.go b/ibm/service/scc/data_source_ibm_scc_provider_type_instance.go new file mode 100644 index 0000000000..ce129f670b --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_provider_type_instance.go @@ -0,0 +1,115 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccProviderTypeInstance() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccProviderTypeInstanceRead, + + Schema: map[string]*schema.Schema{ + "provider_type_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The provider type ID.", + }, + "provider_type_instance_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The provider type instance ID.", + }, + "provider_type_instance_item_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The unique identifier of the provider type instance.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The type of the provider type.", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The name of the provider type instance.", + }, + "attributes": &schema.Schema{ + Type: schema.TypeMap, + Computed: true, + }, + "created_at": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Time at which resource was created.", + }, + "updated_at": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Time at which resource was updated.", + }, + }, + } +} + +func dataSourceIbmSccProviderTypeInstanceRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityAndComplianceCenterApIsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getProviderTypeInstanceOptions := &securityandcompliancecenterapiv3.GetProviderTypeInstanceOptions{} + + getProviderTypeInstanceOptions.SetProviderTypeID(d.Get("provider_type_id").(string)) + getProviderTypeInstanceOptions.SetProviderTypeInstanceID(d.Get("provider_type_instance_id").(string)) + + providerTypeInstanceItem, response, err := securityAndComplianceCenterApIsClient.GetProviderTypeInstanceWithContext(context, getProviderTypeInstanceOptions) + if err != nil { + log.Printf("[DEBUG] GetProviderTypeInstanceWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetProviderTypeInstanceWithContext failed %s\n%s", err, response)) + } + + d.SetId(fmt.Sprintf("%s/%s", *getProviderTypeInstanceOptions.ProviderTypeID, *getProviderTypeInstanceOptions.ProviderTypeInstanceID)) + + if err = d.Set("provider_type_instance_item_id", providerTypeInstanceItem.ID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting provider_type_instance_item_id: %s", err)) + } + + if err = d.Set("type", providerTypeInstanceItem.Type); err != nil { + return diag.FromErr(fmt.Errorf("Error setting type: %s", err)) + } + + if err = d.Set("name", providerTypeInstanceItem.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + + attributes := map[string]interface{}{} + if providerTypeInstanceItem.Attributes != nil { + attributes = providerTypeInstanceItem.Attributes + } + if err = d.Set("attributes", attributes); err != nil { + return diag.FromErr(fmt.Errorf("Error setting attributes %s", err)) + } + + if err = d.Set("created_at", flex.DateTimeToString(providerTypeInstanceItem.CreatedAt)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + } + + if err = d.Set("updated_at", flex.DateTimeToString(providerTypeInstanceItem.UpdatedAt)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + } + + return nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_provider_type_instance_test.go b/ibm/service/scc/data_source_ibm_scc_provider_type_instance_test.go new file mode 100644 index 0000000000..11a592e4f5 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_provider_type_instance_test.go @@ -0,0 +1,90 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccProviderTypeInstanceDataSourceBasic(t *testing.T) { + providerTypeInstanceName := fmt.Sprintf("tf_provider_type_instance_name_%d", acctest.RandIntRange(10, 100)) + providerTypeInstanceAttributes := os.Getenv("IBMCLOUD_SCC_PROVIDER_TYPE_ATTRIBUTES") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccProviderTypeInstanceDataSourceConfigBasic(providerTypeInstanceName, providerTypeInstanceAttributes), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "provider_type_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "provider_type_instance_id"), + ), + }, + }, + }) +} + +func TestAccIbmSccProviderTypeInstanceDataSourceAllArgs(t *testing.T) { + providerTypeInstanceName := fmt.Sprintf("tf_provider_type_instance_name_%d", acctest.RandIntRange(10, 100)) + providerTypeInstanceAttributes := os.Getenv("IBMCLOUD_SCC_PROVIDER_TYPE_ATTRIBUTES") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccProviderTypeInstanceDataSourceConfig(providerTypeInstanceName, providerTypeInstanceAttributes), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "provider_type_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "provider_type_instance_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "type"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "name"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "attributes.%"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "created_at"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type_instance.scc_provider_type_instance_tf", "updated_at"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccProviderTypeInstanceDataSourceConfigBasic(providerTypeInstanceName string, providerTypeInstanceAttributes string) string { + return fmt.Sprintf(` + resource "ibm_scc_provider_type_instance" "scc_provider_type_instance" { + provider_type_id = "afa2476ecfa5f09af248492fe991b4d1" + name = "%s" + attributes = %s + } + + data "ibm_scc_provider_type_instance" "scc_provider_type_instance_tf" { + provider_type_id = ibm_scc_provider_type_instance.scc_provider_type_instance.provider_type_id + provider_type_instance_id = ibm_scc_provider_type_instance.scc_provider_type_instance.provider_type_instance_id + } + `, providerTypeInstanceName, providerTypeInstanceAttributes) +} + +func testAccCheckIbmSccProviderTypeInstanceDataSourceConfig(providerTypeInstanceName string, providerTypeInstanceAttributes string) string { + return fmt.Sprintf(` + resource "ibm_scc_provider_type_instance" "scc_provider_type_instance" { + provider_type_id = "afa2476ecfa5f09af248492fe991b4d1" + name = "%s" + attributes = %s + } + + data "ibm_scc_provider_type_instance" "scc_provider_type_instance_tf" { + provider_type_id = ibm_scc_provider_type_instance.scc_provider_type_instance.provider_type_id + provider_type_instance_id = ibm_scc_provider_type_instance.scc_provider_type_instance.provider_type_instance_id + } + `, providerTypeInstanceName, providerTypeInstanceAttributes) +} diff --git a/ibm/service/scc/data_source_ibm_scc_provider_type_test.go b/ibm/service/scc/data_source_ibm_scc_provider_type_test.go new file mode 100644 index 0000000000..ded3202436 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_provider_type_test.go @@ -0,0 +1,46 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccProviderTypeDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccProviderTypeDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "provider_type_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "type"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "name"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "description"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "s2s_enabled"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "instance_limit"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "mode"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "data_type"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "icon"), + resource.TestCheckResourceAttrSet("data.ibm_scc_provider_type.scc_provider_type_instance", "attributes.%"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccProviderTypeDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_scc_provider_type" "scc_provider_type_instance" { + provider_type_id = "afa2476ecfa5f09af248492fe991b4d1" + } + `) +} diff --git a/ibm/service/scc/data_source_ibm_scc_report.go b/ibm/service/scc/data_source_ibm_scc_report.go new file mode 100644 index 0000000000..f7f03ebac4 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report.go @@ -0,0 +1,354 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccReport() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccReportRead, + + Schema: map[string]*schema.Schema{ + "report_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The ID of the scan that is associated with a report.", + }, + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the report.", + }, + "group_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The group ID that is associated with the report. The group ID combines profile, scope, and attachment IDs.", + }, + "created_on": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the report was created.", + }, + "scan_time": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the scan was run.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The type of the scan.", + }, + "cos_object": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The Cloud Object Storage object that is associated with the report.", + }, + "instance_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Instance ID.", + }, + "account": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The account that is associated with a report.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account ID.", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account name.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account type.", + }, + }, + }, + }, + "profile": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The profile information.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The profile ID.", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The profile name.", + }, + "version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The profile version.", + }, + }, + }, + }, + "attachment": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The attachment that is associated with a report.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The attachment ID.", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The name of the attachment.", + }, + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The description of the attachment.", + }, + "schedule": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The attachment schedule.", + }, + "scope": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The scope of the attachment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The unique identifier for this scope.", + }, + "environment": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The environment that relates to this scope.", + }, + "properties": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The properties that are supported for scoping by this environment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property name.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property value.", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccReportRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + resultsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getReportOptions := &securityandcompliancecenterapiv3.GetReportOptions{} + + getReportOptions.SetReportID(d.Get("report_id").(string)) + + report, response, err := resultsClient.GetReportWithContext(context, getReportOptions) + if err != nil { + log.Printf("[DEBUG] GetReportWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetReportWithContext failed %s\n%s", err, response)) + } + + d.SetId(*report.ID) + + if err = d.Set("id", report.ID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting id: %s", err)) + } + + if err = d.Set("group_id", report.GroupID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting group_id: %s", err)) + } + + if err = d.Set("created_on", report.CreatedOn); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_on: %s", err)) + } + + if err = d.Set("scan_time", report.ScanTime); err != nil { + return diag.FromErr(fmt.Errorf("Error setting scan_time: %s", err)) + } + + if err = d.Set("type", report.Type); err != nil { + return diag.FromErr(fmt.Errorf("Error setting type: %s", err)) + } + + if err = d.Set("cos_object", report.CosObject); err != nil { + return diag.FromErr(fmt.Errorf("Error setting cos_object: %s", err)) + } + + if err = d.Set("instance_id", report.InstanceID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + } + + account := []map[string]interface{}{} + if report.Account != nil { + modelMap, err := dataSourceIbmSccReportAccountToMap(report.Account) + if err != nil { + return diag.FromErr(err) + } + account = append(account, modelMap) + } + if err = d.Set("account", account); err != nil { + return diag.FromErr(fmt.Errorf("Error setting account %s", err)) + } + + profile := []map[string]interface{}{} + if report.Profile != nil { + modelMap, err := dataSourceIbmSccReportProfileInfoToMap(report.Profile) + if err != nil { + return diag.FromErr(err) + } + profile = append(profile, modelMap) + } + if err = d.Set("profile", profile); err != nil { + return diag.FromErr(fmt.Errorf("Error setting profile %s", err)) + } + + attachment := []map[string]interface{}{} + if report.Attachment != nil { + modelMap, err := dataSourceIbmSccReportAttachmentToMap(report.Attachment) + if err != nil { + return diag.FromErr(err) + } + attachment = append(attachment, modelMap) + } + if err = d.Set("attachment", attachment); err != nil { + return diag.FromErr(fmt.Errorf("Error setting attachment %s", err)) + } + + return nil +} + +func dataSourceIbmSccReportAccountToMap(model *securityandcompliancecenterapiv3.Account) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Type != nil { + modelMap["type"] = model.Type + } + return modelMap, nil +} + +func dataSourceIbmSccReportProfileInfoToMap(model *securityandcompliancecenterapiv3.ProfileInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Version != nil { + modelMap["version"] = model.Version + } + return modelMap, nil +} + +func dataSourceIbmSccReportAttachmentToMap(model *securityandcompliancecenterapiv3.Attachment) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Description != nil { + modelMap["description"] = model.Description + } + if model.Schedule != nil { + modelMap["schedule"] = model.Schedule + } + if model.Scope != nil { + scope := []map[string]interface{}{} + for _, scopeItem := range model.Scope { + scopeItemMap, err := dataSourceIbmSccReportAttachmentScopeToMap(&scopeItem) + if err != nil { + return modelMap, err + } + scope = append(scope, scopeItemMap) + } + modelMap["scope"] = scope + } + return modelMap, nil +} + +func dataSourceIbmSccReportAttachmentScopeToMap(model *securityandcompliancecenterapiv3.AttachmentScope) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Environment != nil { + modelMap["environment"] = model.Environment + } + if model.Properties != nil { + properties := []map[string]interface{}{} + for _, propertiesItem := range model.Properties { + propertiesItemMap, err := dataSourceIbmSccReportScopePropertyToMap(&propertiesItem) + if err != nil { + return modelMap, err + } + properties = append(properties, propertiesItemMap) + } + modelMap["properties"] = properties + } + return modelMap, nil +} + +func dataSourceIbmSccReportScopePropertyToMap(model *securityandcompliancecenterapiv3.ScopeProperty) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Value != nil { + modelMap["value"] = model.Value + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_controls.go b/ibm/service/scc/data_source_ibm_scc_report_controls.go new file mode 100644 index 0000000000..141213fc3f --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_controls.go @@ -0,0 +1,527 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +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/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccReportControls() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccReportControlsRead, + + Schema: map[string]*schema.Schema{ + "report_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The ID of the scan that is associated with a report.", + }, + "control_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The ID of the control.", + }, + "control_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The name of the control.", + }, + "control_description": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The description of the control.", + }, + "control_category": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "A control category value.", + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The compliance status value.", + }, + "sort": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "This field sorts controls by using a valid sort field. To learn more, see [Sorting](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-sorting).", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of checks.", + }, + "compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of compliant checks.", + }, + "not_compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are not compliant.", + }, + "unable_to_perform_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are unable to perform.", + }, + "user_evaluation_required_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that require a user evaluation.", + }, + "home_account_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the home account.", + }, + "controls": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of controls that are in the report.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control ID.", + }, + "control_library_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control library ID.", + }, + "control_library_version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control library version.", + }, + "control_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control name.", + }, + "control_description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control description.", + }, + "control_category": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control category.", + }, + "control_path": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control path.", + }, + "control_specifications": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of specifications that are on the page.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_specification_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The control specification ID.", + }, + "component_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The component ID.", + }, + "control_specification_description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The component description.", + }, + "environment": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The environment.", + }, + "responsibility": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The responsibility for managing control specifications.", + }, + "assessments": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of assessments.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "assessment_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The assessment ID.", + }, + "assessment_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The assessment type.", + }, + "assessment_method": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The assessment method.", + }, + "assessment_description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The assessment description.", + }, + "parameter_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of parameters of this assessment.", + }, + "parameters": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of parameters of this assessment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "parameter_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The parameter name.", + }, + "parameter_display_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The parameter display name.", + }, + "parameter_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The parameter type.", + }, + "parameter_value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property value.", + }, + }, + }, + }, + }, + }, + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an aggregated status for controls, specifications, assessments, and resources.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of checks.", + }, + "compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of compliant checks.", + }, + "not_compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are not compliant.", + }, + "unable_to_perform_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are unable to perform.", + }, + "user_evaluation_required_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that require a user evaluation.", + }, + }, + }, + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an aggregated status for controls, specifications, assessments, and resources.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of checks.", + }, + "compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of compliant checks.", + }, + "not_compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are not compliant.", + }, + "unable_to_perform_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are unable to perform.", + }, + "user_evaluation_required_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that require a user evaluation.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccReportControlsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + resultsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getReportControlsOptions := &securityandcompliancecenterapiv3.GetReportControlsOptions{} + + getReportControlsOptions.SetReportID(d.Get("report_id").(string)) + if _, ok := d.GetOk("control_id"); ok { + getReportControlsOptions.SetControlID(d.Get("control_id").(string)) + } + if _, ok := d.GetOk("control_name"); ok { + getReportControlsOptions.SetControlName(d.Get("control_name").(string)) + } + if _, ok := d.GetOk("control_description"); ok { + getReportControlsOptions.SetControlDescription(d.Get("control_description").(string)) + } + if _, ok := d.GetOk("control_category"); ok { + getReportControlsOptions.SetControlCategory(d.Get("control_category").(string)) + } + if _, ok := d.GetOk("status"); ok { + getReportControlsOptions.SetStatus(d.Get("status").(string)) + } + if _, ok := d.GetOk("sort"); ok { + getReportControlsOptions.SetSort(d.Get("sort").(string)) + } + + reportControls, response, err := resultsClient.GetReportControlsWithContext(context, getReportControlsOptions) + if err != nil { + log.Printf("[DEBUG] GetReportControlsWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetReportControlsWithContext failed %s\n%s", err, response)) + } + + d.SetId(dataSourceIbmSccReportControlsID(d)) + + if err = d.Set("total_count", flex.IntValue(reportControls.TotalCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting total_count: %s", err)) + } + + if err = d.Set("compliant_count", flex.IntValue(reportControls.CompliantCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting compliant_count: %s", err)) + } + + if err = d.Set("not_compliant_count", flex.IntValue(reportControls.NotCompliantCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting not_compliant_count: %s", err)) + } + + if err = d.Set("unable_to_perform_count", flex.IntValue(reportControls.UnableToPerformCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting unable_to_perform_count: %s", err)) + } + + if err = d.Set("user_evaluation_required_count", flex.IntValue(reportControls.UserEvaluationRequiredCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting user_evaluation_required_count: %s", err)) + } + + if err = d.Set("home_account_id", reportControls.HomeAccountID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting home_account_id: %s", err)) + } + + controls := []map[string]interface{}{} + if reportControls.Controls != nil { + for _, modelItem := range reportControls.Controls { + modelMap, err := dataSourceIbmSccReportControlsControlWithStatsToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + controls = append(controls, modelMap) + } + } + if err = d.Set("controls", controls); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls %s", err)) + } + + return nil +} + +// dataSourceIbmSccReportControlsID returns a reasonable ID for the list. +func dataSourceIbmSccReportControlsID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func dataSourceIbmSccReportControlsControlWithStatsToMap(model *securityandcompliancecenterapiv3.ControlWithStats) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.ControlLibraryID != nil { + modelMap["control_library_id"] = model.ControlLibraryID + } + if model.ControlLibraryVersion != nil { + modelMap["control_library_version"] = model.ControlLibraryVersion + } + if model.ControlName != nil { + modelMap["control_name"] = model.ControlName + } + if model.ControlDescription != nil { + modelMap["control_description"] = model.ControlDescription + } + if model.ControlCategory != nil { + modelMap["control_category"] = model.ControlCategory + } + if model.ControlPath != nil { + modelMap["control_path"] = model.ControlPath + } + if model.ControlSpecifications != nil { + controlSpecifications := []map[string]interface{}{} + for _, controlSpecificationsItem := range model.ControlSpecifications { + controlSpecificationsItemMap, err := dataSourceIbmSccReportControlsControlSpecificationWithStatsToMap(&controlSpecificationsItem) + if err != nil { + return modelMap, err + } + controlSpecifications = append(controlSpecifications, controlSpecificationsItemMap) + } + modelMap["control_specifications"] = controlSpecifications + } + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.CompliantCount != nil { + modelMap["compliant_count"] = flex.IntValue(model.CompliantCount) + } + if model.NotCompliantCount != nil { + modelMap["not_compliant_count"] = flex.IntValue(model.NotCompliantCount) + } + if model.UnableToPerformCount != nil { + modelMap["unable_to_perform_count"] = flex.IntValue(model.UnableToPerformCount) + } + if model.UserEvaluationRequiredCount != nil { + modelMap["user_evaluation_required_count"] = flex.IntValue(model.UserEvaluationRequiredCount) + } + return modelMap, nil +} + +func dataSourceIbmSccReportControlsControlSpecificationWithStatsToMap(model *securityandcompliancecenterapiv3.ControlSpecificationWithStats) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlSpecificationID != nil { + modelMap["control_specification_id"] = model.ControlSpecificationID + } + if model.ComponentID != nil { + modelMap["component_id"] = model.ComponentID + } + if model.ControlSpecificationDescription != nil { + modelMap["control_specification_description"] = model.ControlSpecificationDescription + } + if model.Environment != nil { + modelMap["environment"] = model.Environment + } + if model.Responsibility != nil { + modelMap["responsibility"] = model.Responsibility + } + if model.Assessments != nil { + assessments := []map[string]interface{}{} + for _, assessmentsItem := range model.Assessments { + assessmentsItemMap, err := dataSourceIbmSccReportControlsAssessmentToMap(&assessmentsItem) + if err != nil { + return modelMap, err + } + assessments = append(assessments, assessmentsItemMap) + } + modelMap["assessments"] = assessments + } + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.CompliantCount != nil { + modelMap["compliant_count"] = flex.IntValue(model.CompliantCount) + } + if model.NotCompliantCount != nil { + modelMap["not_compliant_count"] = flex.IntValue(model.NotCompliantCount) + } + if model.UnableToPerformCount != nil { + modelMap["unable_to_perform_count"] = flex.IntValue(model.UnableToPerformCount) + } + if model.UserEvaluationRequiredCount != nil { + modelMap["user_evaluation_required_count"] = flex.IntValue(model.UserEvaluationRequiredCount) + } + return modelMap, nil +} + +func dataSourceIbmSccReportControlsAssessmentToMap(model *securityandcompliancecenterapiv3.Assessment) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AssessmentID != nil { + modelMap["assessment_id"] = model.AssessmentID + } + if model.AssessmentType != nil { + modelMap["assessment_type"] = model.AssessmentType + } + if model.AssessmentMethod != nil { + modelMap["assessment_method"] = model.AssessmentMethod + } + if model.AssessmentDescription != nil { + modelMap["assessment_description"] = model.AssessmentDescription + } + if model.ParameterCount != nil { + modelMap["parameter_count"] = flex.IntValue(model.ParameterCount) + } + if model.Parameters != nil { + parameters := []map[string]interface{}{} + for _, parametersItem := range model.Parameters { + parametersItemMap, err := dataSourceIbmSccReportControlsParameterInfoToMap(¶metersItem) + if err != nil { + return modelMap, err + } + parameters = append(parameters, parametersItemMap) + } + modelMap["parameters"] = parameters + } + return modelMap, nil +} + +func dataSourceIbmSccReportControlsParameterInfoToMap(model *securityandcompliancecenterapiv3.ParameterInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ParameterName != nil { + modelMap["parameter_name"] = model.ParameterName + } + if model.ParameterDisplayName != nil { + modelMap["parameter_display_name"] = model.ParameterDisplayName + } + if model.ParameterType != nil { + modelMap["parameter_type"] = model.ParameterType + } + if model.ParameterValue != nil { + modelMap["parameter_value"] = model.ParameterValue + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_controls_test.go b/ibm/service/scc/data_source_ibm_scc_report_controls_test.go new file mode 100644 index 0000000000..adec094fab --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_controls_test.go @@ -0,0 +1,39 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccReportControlsDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccReportControlsDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_report_controls.scc_report_controls_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report_controls.scc_report_controls_instance", "report_id"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccReportControlsDataSourceConfigBasic() string { + report_id := os.Getenv("IBMCLOUD_SCC_REPORT_ID") + return fmt.Sprintf(` + data "ibm_scc_report_controls" "scc_report_controls_instance" { + report_id = "%s" + } + `, report_id) +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_evaluations.go b/ibm/service/scc/data_source_ibm_scc_report_evaluations.go new file mode 100644 index 0000000000..24fc6f6100 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_evaluations.go @@ -0,0 +1,481 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +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/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccReportEvaluations() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccReportEvaluationsRead, + + Schema: map[string]*schema.Schema{ + "report_id": { + Type: schema.TypeString, + Required: true, + Description: "The ID of the scan that is associated with a report.", + }, + "assessment_id": { + Type: schema.TypeString, + Optional: true, + Description: "The ID of the assessment.", + }, + "component_id": { + Type: schema.TypeString, + Optional: true, + Description: "The ID of component.", + }, + "target_id": { + Type: schema.TypeString, + Optional: true, + Description: "The ID of the evaluation target.", + }, + "target_name": { + Type: schema.TypeString, + Optional: true, + Description: "The name of the evaluation target.", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "The evaluation status value.", + }, + "first": { + Type: schema.TypeList, + Computed: true, + Description: "The page reference.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "href": { + Type: schema.TypeString, + Computed: true, + Description: "The URL for the first and next page.", + }, + }, + }, + }, + "home_account_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of the home account.", + }, + "evaluations": { + Type: schema.TypeList, + Computed: true, + Description: "The list of evaluations that are on the page.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "home_account_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of the home account.", + }, + "report_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of the report that is associated to the evaluation.", + }, + "control_id": { + Type: schema.TypeString, + Computed: true, + Description: "The control ID.", + }, + "component_id": { + Type: schema.TypeString, + Computed: true, + Description: "The component ID.", + }, + "assessment": { + Type: schema.TypeList, + Computed: true, + Description: "The control specification assessment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "assessment_id": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment ID.", + }, + "assessment_type": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment type.", + }, + "assessment_method": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment method.", + }, + "assessment_description": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment description.", + }, + "parameter_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of parameters of this assessment.", + }, + "parameters": { + Type: schema.TypeList, + Computed: true, + Description: "The list of parameters of this assessment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "parameter_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter name.", + }, + "parameter_display_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter display name.", + }, + "parameter_type": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter type.", + }, + "parameter_value": { + Type: schema.TypeString, + Computed: true, + Description: "The property value.", + }, + }, + }, + }, + }, + }, + }, + "evaluate_time": { + Type: schema.TypeString, + Computed: true, + Description: "The time when the evaluation was made.", + }, + "target": { + Type: schema.TypeList, + Computed: true, + Description: "The evaluation target.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + Description: "The target ID.", + }, + "account_id": { + Type: schema.TypeString, + Computed: true, + Description: "The target account ID.", + }, + "resource_crn": { + Type: schema.TypeString, + Computed: true, + Description: "The target resource CRN.", + }, + "resource_name": { + Type: schema.TypeString, + Computed: true, + Description: "The target resource name.", + }, + "service_name": { + Type: schema.TypeString, + Computed: true, + Description: "The target service name.", + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an evaluation status.", + }, + "reason": { + Type: schema.TypeString, + Computed: true, + Description: "The reason for the evaluation failure.", + }, + "details": { + Type: schema.TypeList, + Computed: true, + Description: "The evaluation details.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "properties": { + Type: schema.TypeList, + Computed: true, + Description: "The evaluation properties.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "property": { + Type: schema.TypeString, + Computed: true, + Description: "The property name.", + }, + "property_description": { + Type: schema.TypeString, + Computed: true, + Description: "The property description.", + }, + "operator": { + Type: schema.TypeString, + Computed: true, + Description: "The property operator.", + }, + "expected_value": { + Type: schema.TypeString, + Computed: true, + Description: "The property value.", + }, + "found_value": { + Type: schema.TypeString, + Computed: true, + Description: "The property value.", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccReportEvaluationsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + resultsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + listReportEvaluationsOptions := &securityandcompliancecenterapiv3.ListReportEvaluationsOptions{} + + listReportEvaluationsOptions.SetReportID(d.Get("report_id").(string)) + if _, ok := d.GetOk("assessment_id"); ok { + listReportEvaluationsOptions.SetAssessmentID(d.Get("assessment_id").(string)) + } + if _, ok := d.GetOk("component_id"); ok { + listReportEvaluationsOptions.SetComponentID(d.Get("component_id").(string)) + } + if _, ok := d.GetOk("target_id"); ok { + listReportEvaluationsOptions.SetTargetID(d.Get("target_id").(string)) + } + if _, ok := d.GetOk("target_name"); ok { + listReportEvaluationsOptions.SetTargetName(d.Get("target_name").(string)) + } + if _, ok := d.GetOk("status"); ok { + listReportEvaluationsOptions.SetStatus(d.Get("status").(string)) + } + + var pager *securityandcompliancecenterapiv3.ReportEvaluationsPager + pager, err = resultsClient.NewReportEvaluationsPager(listReportEvaluationsOptions) + if err != nil { + return diag.FromErr(err) + } + + log.Printf("[DEBUG] ReportEvaluationsPager %v:\n%s", pager, err) + allItems, err := pager.GetAll() + if err != nil { + log.Printf("[DEBUG] ReportEvaluationsPager.GetAll() failed %s", err) + return diag.FromErr(fmt.Errorf("ReportEvaluationsPager.GetAll() failed %s", err)) + } + + d.SetId(dataSourceIbmSccReportEvaluationsID(d)) + + mapSlice := []map[string]interface{}{} + for _, modelItem := range allItems { + modelMap, err := dataSourceIbmSccReportEvaluationsEvaluationToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + mapSlice = append(mapSlice, modelMap) + } + + if err = d.Set("evaluations", mapSlice); err != nil { + return diag.FromErr(fmt.Errorf("Error setting evaluations %s", err)) + } + + return nil +} + +// dataSourceIbmSccReportEvaluationsID returns a reasonable ID for the list. +func dataSourceIbmSccReportEvaluationsID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func dataSourceIbmSccReportEvaluationsPageHRefToMap(model *securityandcompliancecenterapiv3.PageHRef) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["href"] = model.Href + return modelMap, nil +} + +func dataSourceIbmSccReportEvaluationsEvaluationToMap(model *securityandcompliancecenterapiv3.Evaluation) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.HomeAccountID != nil { + modelMap["home_account_id"] = model.HomeAccountID + } + if model.ReportID != nil { + modelMap["report_id"] = model.ReportID + } + if model.ControlID != nil { + modelMap["control_id"] = model.ControlID + } + if model.ComponentID != nil { + modelMap["component_id"] = model.ComponentID + } + if model.Assessment != nil { + assessmentMap, err := dataSourceIbmSccReportEvaluationsAssessmentToMap(model.Assessment) + if err != nil { + return modelMap, err + } + modelMap["assessment"] = []map[string]interface{}{assessmentMap} + } + if model.EvaluateTime != nil { + modelMap["evaluate_time"] = model.EvaluateTime + } + if model.Target != nil { + targetMap, err := dataSourceIbmSccReportEvaluationsTargetInfoToMap(model.Target) + if err != nil { + return modelMap, err + } + modelMap["target"] = []map[string]interface{}{targetMap} + } + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.Reason != nil { + modelMap["reason"] = model.Reason + } + if model.Details != nil { + detailsMap, err := dataSourceIbmSccReportEvaluationsEvalDetailsToMap(model.Details) + if err != nil { + return modelMap, err + } + modelMap["details"] = []map[string]interface{}{detailsMap} + } + return modelMap, nil +} + +func dataSourceIbmSccReportEvaluationsAssessmentToMap(model *securityandcompliancecenterapiv3.Assessment) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AssessmentID != nil { + modelMap["assessment_id"] = model.AssessmentID + } + if model.AssessmentType != nil { + modelMap["assessment_type"] = model.AssessmentType + } + if model.AssessmentMethod != nil { + modelMap["assessment_method"] = model.AssessmentMethod + } + if model.AssessmentDescription != nil { + modelMap["assessment_description"] = model.AssessmentDescription + } + if model.ParameterCount != nil { + modelMap["parameter_count"] = flex.IntValue(model.ParameterCount) + } + if model.Parameters != nil { + parameters := []map[string]interface{}{} + for _, parametersItem := range model.Parameters { + parametersItemMap, err := dataSourceIbmSccReportEvaluationsParameterInfoToMap(¶metersItem) + if err != nil { + return modelMap, err + } + parameters = append(parameters, parametersItemMap) + } + modelMap["parameters"] = parameters + } + return modelMap, nil +} + +func dataSourceIbmSccReportEvaluationsParameterInfoToMap(model *securityandcompliancecenterapiv3.ParameterInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ParameterName != nil { + modelMap["parameter_name"] = model.ParameterName + } + if model.ParameterDisplayName != nil { + modelMap["parameter_display_name"] = model.ParameterDisplayName + } + if model.ParameterType != nil { + modelMap["parameter_type"] = model.ParameterType + } + if model.ParameterValue != nil { + modelMap["parameter_value"] = model.ParameterValue + } + return modelMap, nil +} + +func dataSourceIbmSccReportEvaluationsTargetInfoToMap(model *securityandcompliancecenterapiv3.TargetInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.AccountID != nil { + modelMap["account_id"] = model.AccountID + } + if model.ResourceCrn != nil { + modelMap["resource_crn"] = model.ResourceCrn + } + if model.ResourceName != nil { + modelMap["resource_name"] = model.ResourceName + } + if model.ServiceName != nil { + modelMap["service_name"] = model.ServiceName + } + return modelMap, nil +} + +func dataSourceIbmSccReportEvaluationsEvalDetailsToMap(model *securityandcompliancecenterapiv3.EvalDetails) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Properties != nil { + properties := []map[string]interface{}{} + for _, propertiesItem := range model.Properties { + propertiesItemMap, err := dataSourceIbmSccReportEvaluationsPropertyToMap(&propertiesItem) + if err != nil { + return modelMap, err + } + properties = append(properties, propertiesItemMap) + } + modelMap["properties"] = properties + } + return modelMap, nil +} + +func dataSourceIbmSccReportEvaluationsPropertyToMap(model *securityandcompliancecenterapiv3.Property) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Property != nil { + modelMap["property"] = model.Property + } + if model.PropertyDescription != nil { + modelMap["property_description"] = model.PropertyDescription + } + if model.Operator != nil { + modelMap["operator"] = model.Operator + } + if model.ExpectedValue != nil { + modelMap["expected_value"] = model.ExpectedValue + } + if model.FoundValue != nil { + // modelMap["found_value"] = model.FoundValue + fValIntf := model.FoundValue + log.Printf("The Found value is = %v", fValIntf) + modelMap["found_value"] = fmt.Sprintf("%v", fValIntf) + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_evaluations_test.go b/ibm/service/scc/data_source_ibm_scc_report_evaluations_test.go new file mode 100644 index 0000000000..bab407752a --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_evaluations_test.go @@ -0,0 +1,40 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccReportEvaluationsDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccReportEvaluationsDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_report_evaluations.scc_report_evaluations_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report_evaluations.scc_report_evaluations_instance", "report_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report_evaluations.scc_report_evaluations_instance", "evaluations.#"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccReportEvaluationsDataSourceConfigBasic() string { + report_id := os.Getenv("IBMCLOUD_SCC_REPORT_ID") + return fmt.Sprintf(` + data "ibm_scc_report_evaluations" "scc_report_evaluations_instance" { + report_id = "%s" + } + `, report_id) +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_resources.go b/ibm/service/scc/data_source_ibm_scc_report_resources.go new file mode 100644 index 0000000000..d040497f29 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_resources.go @@ -0,0 +1,297 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +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/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccReportResources() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccReportResourcesRead, + + Schema: map[string]*schema.Schema{ + "report_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The ID of the scan that is associated with a report.", + }, + "id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The ID of the resource.", + }, + "resource_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The name of the resource.", + }, + "account_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The ID of the account owning a resource.", + }, + "component_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The ID of component.", + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The compliance status value.", + }, + "sort": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "This field sorts resources by using a valid sort field. To learn more, see [Sorting](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-sorting).", + }, + "first": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The page reference.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "href": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The URL for the first and next page.", + }, + }, + }, + }, + "home_account_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the home account.", + }, + "resources": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of resource evaluation summaries that are on the page.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "report_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the report.", + }, + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The resource CRN.", + }, + "resource_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The resource name.", + }, + "component_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the component.", + }, + "environment": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The environment.", + }, + "account": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The account that is associated with a report.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account ID.", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account name.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account type.", + }, + }, + }, + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an aggregated status for controls, specifications, assessments, and resources.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of evaluations.", + }, + "pass_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of passed evaluations.", + }, + "failure_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of failed evaluations.", + }, + "error_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of evaluations that started, but did not finish, and ended with errors.", + }, + "completed_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of completed evaluations.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccReportResourcesRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + resultsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + listReportResourcesOptions := &securityandcompliancecenterapiv3.ListReportResourcesOptions{} + + listReportResourcesOptions.SetReportID(d.Get("report_id").(string)) + if _, ok := d.GetOk("id"); ok { + listReportResourcesOptions.SetID(d.Get("id").(string)) + } + if _, ok := d.GetOk("resource_name"); ok { + listReportResourcesOptions.SetResourceName(d.Get("resource_name").(string)) + } + if _, ok := d.GetOk("account_id"); ok { + listReportResourcesOptions.SetAccountID(d.Get("account_id").(string)) + } + if _, ok := d.GetOk("component_id"); ok { + listReportResourcesOptions.SetComponentID(d.Get("component_id").(string)) + } + if _, ok := d.GetOk("status"); ok { + listReportResourcesOptions.SetStatus(d.Get("status").(string)) + } + if _, ok := d.GetOk("sort"); ok { + listReportResourcesOptions.SetSort(d.Get("sort").(string)) + } + + var pager *securityandcompliancecenterapiv3.ReportResourcesPager + pager, err = resultsClient.NewReportResourcesPager(listReportResourcesOptions) + if err != nil { + return diag.FromErr(err) + } + + allItems, err := pager.GetAll() + if err != nil { + log.Printf("[DEBUG] ReportResourcesPager.GetAll() failed %s", err) + return diag.FromErr(fmt.Errorf("ReportResourcesPager.GetAll() failed %s", err)) + } + + d.SetId(dataSourceIbmSccReportResourcesID(d)) + + mapSlice := []map[string]interface{}{} + for _, modelItem := range allItems { + modelMap, err := dataSourceIbmSccReportResourcesResourceToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + mapSlice = append(mapSlice, modelMap) + } + + if err = d.Set("resources", mapSlice); err != nil { + return diag.FromErr(fmt.Errorf("Error setting resources %s", err)) + } + + return nil +} + +// dataSourceIbmSccReportResourcesID returns a reasonable ID for the list. +func dataSourceIbmSccReportResourcesID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func dataSourceIbmSccReportResourcesPageHRefToMap(model *securityandcompliancecenterapiv3.PageHRef) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["href"] = model.Href + return modelMap, nil +} + +func dataSourceIbmSccReportResourcesResourceToMap(model *securityandcompliancecenterapiv3.Resource) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ReportID != nil { + modelMap["report_id"] = model.ReportID + } + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.ResourceName != nil { + modelMap["resource_name"] = model.ResourceName + } + if model.ComponentID != nil { + modelMap["component_id"] = model.ComponentID + } + if model.Environment != nil { + modelMap["environment"] = model.Environment + } + if model.Account != nil { + accountMap, err := dataSourceIbmSccReportResourcesAccountToMap(model.Account) + if err != nil { + return modelMap, err + } + modelMap["account"] = []map[string]interface{}{accountMap} + } + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.PassCount != nil { + modelMap["pass_count"] = flex.IntValue(model.PassCount) + } + if model.FailureCount != nil { + modelMap["failure_count"] = flex.IntValue(model.FailureCount) + } + if model.ErrorCount != nil { + modelMap["error_count"] = flex.IntValue(model.ErrorCount) + } + if model.CompletedCount != nil { + modelMap["completed_count"] = flex.IntValue(model.CompletedCount) + } + return modelMap, nil +} + +func dataSourceIbmSccReportResourcesAccountToMap(model *securityandcompliancecenterapiv3.Account) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Type != nil { + modelMap["type"] = model.Type + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_resources_test.go b/ibm/service/scc/data_source_ibm_scc_report_resources_test.go new file mode 100644 index 0000000000..352bc33432 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_resources_test.go @@ -0,0 +1,40 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccReportResourcesDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccReportResourcesDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_report_resources.scc_report_resources_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report_resources.scc_report_resources_instance", "report_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report_resources.scc_report_resources_instance", "resources.#"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccReportResourcesDataSourceConfigBasic() string { + report_id := os.Getenv("IBMCLOUD_SCC_REPORT_ID") + return fmt.Sprintf(` + data "ibm_scc_report_resources" "scc_report_resources_instance" { + report_id = "%s" + } + `, report_id) +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_rule.go b/ibm/service/scc/data_source_ibm_scc_report_rule.go new file mode 100644 index 0000000000..ce5e218bc9 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_rule.go @@ -0,0 +1,146 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccReportRule() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccReportRuleRead, + + Schema: map[string]*schema.Schema{ + "report_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The ID of the scan that is associated with a report.", + }, + "rule_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The ID of a rule in a report.", + }, + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The rule ID.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The rule type.", + }, + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The rule description.", + }, + "version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The rule version.", + }, + "account_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The rule account ID.", + }, + "created_on": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the rule was created.", + }, + "created_by": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the user who created the rule.", + }, + "updated_on": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the rule was updated.", + }, + "updated_by": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the user who updated the rule.", + }, + "labels": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The rule labels.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + } +} + +func dataSourceIbmSccReportRuleRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + resultsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getReportRuleOptions := &securityandcompliancecenterapiv3.GetReportRuleOptions{} + + getReportRuleOptions.SetReportID(d.Get("report_id").(string)) + getReportRuleOptions.SetRuleID(d.Get("rule_id").(string)) + + ruleInfo, response, err := resultsClient.GetReportRuleWithContext(context, getReportRuleOptions) + if err != nil { + log.Printf("[DEBUG] GetReportRuleWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetReportRuleWithContext failed %s\n%s", err, response)) + } + + d.SetId(*ruleInfo.ID) + + if err = d.Set("id", ruleInfo.ID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting id: %s", err)) + } + + if err = d.Set("type", ruleInfo.Type); err != nil { + return diag.FromErr(fmt.Errorf("Error setting type: %s", err)) + } + + if err = d.Set("description", ruleInfo.Description); err != nil { + return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + } + + if err = d.Set("version", ruleInfo.Version); err != nil { + return diag.FromErr(fmt.Errorf("Error setting version: %s", err)) + } + + if err = d.Set("account_id", ruleInfo.AccountID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) + } + + if err = d.Set("created_on", ruleInfo.CreatedOn); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_on: %s", err)) + } + + if err = d.Set("created_by", ruleInfo.CreatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + } + + if err = d.Set("updated_on", ruleInfo.UpdatedOn); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_on: %s", err)) + } + + if err = d.Set("updated_by", ruleInfo.UpdatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_by: %s", err)) + } + + return nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_rule_test.go b/ibm/service/scc/data_source_ibm_scc_report_rule_test.go new file mode 100644 index 0000000000..649c1fcd03 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_rule_test.go @@ -0,0 +1,41 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccReportRuleDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccReportRuleDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_report_rule.scc_report_rule_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report_rule.scc_report_rule_instance", "report_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report_rule.scc_report_rule_instance", "rule_id"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccReportRuleDataSourceConfigBasic() string { + report_id := os.Getenv("IBMCLOUD_SCC_REPORT_ID") + return fmt.Sprintf(` + data "ibm_scc_report_rule" "scc_report_rule_instance" { + report_id = "%s" + rule_id = "rule-f8722625-1968-4d7a-93cb-4b0f8da726da" + } + `, report_id) +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_summary.go b/ibm/service/scc/data_source_ibm_scc_report_summary.go new file mode 100644 index 0000000000..086838f0f2 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_summary.go @@ -0,0 +1,548 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +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/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccReportSummary() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccReportSummaryRead, + + Schema: map[string]*schema.Schema{ + "report_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The ID of the scan that is associated with a report.", + }, + "isntance_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Instance ID.", + }, + "account": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The account that is associated with a report.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account ID.", + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account name.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account type.", + }, + }, + }, + }, + "score": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The compliance score.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "passed": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of successful evaluations.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of evaluations.", + }, + "percent": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The percentage of successful evaluations.", + }, + }, + }, + }, + "controls": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The compliance stats.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an aggregated status for controls, specifications, assessments, and resources.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of checks.", + }, + "compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of compliant checks.", + }, + "not_compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are not compliant.", + }, + "unable_to_perform_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are unable to perform.", + }, + "user_evaluation_required_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that require a user evaluation.", + }, + }, + }, + }, + "evaluations": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The evaluation stats.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an aggregated status for controls, specifications, assessments, and resources.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of evaluations.", + }, + "pass_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of passed evaluations.", + }, + "failure_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of failed evaluations.", + }, + "error_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of evaluations that started, but did not finish, and ended with errors.", + }, + "completed_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of completed evaluations.", + }, + }, + }, + }, + "resources": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The resource summary.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an aggregated status for controls, specifications, assessments, and resources.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of checks.", + }, + "compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of compliant checks.", + }, + "not_compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are not compliant.", + }, + "unable_to_perform_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are unable to perform.", + }, + "user_evaluation_required_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that require a user evaluation.", + }, + "top_failed": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The top 10 resources that have the most failures.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The resource name.", + }, + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The resource ID.", + }, + "service": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The service that is managing the resource.", + }, + "tags": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The collection of different types of tags.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "user": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The collection of user tags.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "access": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The collection of access tags.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "service": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The collection of service tags.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + "account": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account that owns the resource.", + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an aggregated status for controls, specifications, assessments, and resources.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of evaluations.", + }, + "pass_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of passed evaluations.", + }, + "failure_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of failed evaluations.", + }, + "error_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of evaluations that started, but did not finish, and ended with errors.", + }, + "completed_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of completed evaluations.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccReportSummaryRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + resultsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getReportSummaryOptions := &securityandcompliancecenterapiv3.GetReportSummaryOptions{} + + getReportSummaryOptions.SetReportID(d.Get("report_id").(string)) + + reportSummary, response, err := resultsClient.GetReportSummaryWithContext(context, getReportSummaryOptions) + if err != nil { + log.Printf("[DEBUG] GetReportSummaryWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetReportSummaryWithContext failed %s\n%s", err, response)) + } + + d.SetId(dataSourceIbmSccReportSummaryID(d)) + + if err = d.Set("isntance_id", reportSummary.IsntanceID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting isntance_id: %s", err)) + } + + account := []map[string]interface{}{} + if reportSummary.Account != nil { + modelMap, err := dataSourceIbmSccReportSummaryAccountToMap(reportSummary.Account) + if err != nil { + return diag.FromErr(err) + } + account = append(account, modelMap) + } + if err = d.Set("account", account); err != nil { + return diag.FromErr(fmt.Errorf("Error setting account %s", err)) + } + + score := []map[string]interface{}{} + if reportSummary.Score != nil { + modelMap, err := dataSourceIbmSccReportSummaryComplianceScoreToMap(reportSummary.Score) + if err != nil { + return diag.FromErr(err) + } + score = append(score, modelMap) + } + if err = d.Set("score", score); err != nil { + return diag.FromErr(fmt.Errorf("Error setting score %s", err)) + } + + controls := []map[string]interface{}{} + if reportSummary.Controls != nil { + modelMap, err := dataSourceIbmSccReportSummaryComplianceStatsToMap(reportSummary.Controls) + if err != nil { + return diag.FromErr(err) + } + controls = append(controls, modelMap) + } + if err = d.Set("controls", controls); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls %s", err)) + } + + evaluations := []map[string]interface{}{} + if reportSummary.Evaluations != nil { + modelMap, err := dataSourceIbmSccReportSummaryEvalStatsToMap(reportSummary.Evaluations) + if err != nil { + return diag.FromErr(err) + } + evaluations = append(evaluations, modelMap) + } + if err = d.Set("evaluations", evaluations); err != nil { + return diag.FromErr(fmt.Errorf("Error setting evaluations %s", err)) + } + + resources := []map[string]interface{}{} + if reportSummary.Resources != nil { + modelMap, err := dataSourceIbmSccReportSummaryResourceSummaryToMap(reportSummary.Resources) + if err != nil { + return diag.FromErr(err) + } + resources = append(resources, modelMap) + } + if err = d.Set("resources", resources); err != nil { + return diag.FromErr(fmt.Errorf("Error setting resources %s", err)) + } + + return nil +} + +// dataSourceIbmSccReportSummaryID returns a reasonable ID for the list. +func dataSourceIbmSccReportSummaryID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func dataSourceIbmSccReportSummaryAccountToMap(model *securityandcompliancecenterapiv3.Account) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Type != nil { + modelMap["type"] = model.Type + } + return modelMap, nil +} + +func dataSourceIbmSccReportSummaryComplianceScoreToMap(model *securityandcompliancecenterapiv3.ComplianceScore) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Passed != nil { + modelMap["passed"] = flex.IntValue(model.Passed) + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.Percent != nil { + modelMap["percent"] = flex.IntValue(model.Percent) + } + return modelMap, nil +} + +func dataSourceIbmSccReportSummaryComplianceStatsToMap(model *securityandcompliancecenterapiv3.ComplianceStats) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.CompliantCount != nil { + modelMap["compliant_count"] = flex.IntValue(model.CompliantCount) + } + if model.NotCompliantCount != nil { + modelMap["not_compliant_count"] = flex.IntValue(model.NotCompliantCount) + } + if model.UnableToPerformCount != nil { + modelMap["unable_to_perform_count"] = flex.IntValue(model.UnableToPerformCount) + } + if model.UserEvaluationRequiredCount != nil { + modelMap["user_evaluation_required_count"] = flex.IntValue(model.UserEvaluationRequiredCount) + } + return modelMap, nil +} + +func dataSourceIbmSccReportSummaryEvalStatsToMap(model *securityandcompliancecenterapiv3.EvalStats) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.PassCount != nil { + modelMap["pass_count"] = flex.IntValue(model.PassCount) + } + if model.FailureCount != nil { + modelMap["failure_count"] = flex.IntValue(model.FailureCount) + } + if model.ErrorCount != nil { + modelMap["error_count"] = flex.IntValue(model.ErrorCount) + } + if model.CompletedCount != nil { + modelMap["completed_count"] = flex.IntValue(model.CompletedCount) + } + return modelMap, nil +} + +func dataSourceIbmSccReportSummaryResourceSummaryToMap(model *securityandcompliancecenterapiv3.ResourceSummary) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.CompliantCount != nil { + modelMap["compliant_count"] = flex.IntValue(model.CompliantCount) + } + if model.NotCompliantCount != nil { + modelMap["not_compliant_count"] = flex.IntValue(model.NotCompliantCount) + } + if model.UnableToPerformCount != nil { + modelMap["unable_to_perform_count"] = flex.IntValue(model.UnableToPerformCount) + } + if model.UserEvaluationRequiredCount != nil { + modelMap["user_evaluation_required_count"] = flex.IntValue(model.UserEvaluationRequiredCount) + } + if model.TopFailed != nil { + topFailed := []map[string]interface{}{} + for _, topFailedItem := range model.TopFailed { + topFailedItemMap, err := dataSourceIbmSccReportSummaryResourceSummaryItemToMap(&topFailedItem) + if err != nil { + return modelMap, err + } + topFailed = append(topFailed, topFailedItemMap) + } + modelMap["top_failed"] = topFailed + } + return modelMap, nil +} + +func dataSourceIbmSccReportSummaryResourceSummaryItemToMap(model *securityandcompliancecenterapiv3.ResourceSummaryItem) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Service != nil { + modelMap["service"] = model.Service + } + if model.Tags != nil { + tagsMap, err := dataSourceIbmSccReportSummaryTagsToMap(model.Tags) + if err != nil { + return modelMap, err + } + modelMap["tags"] = []map[string]interface{}{tagsMap} + } + if model.Account != nil { + modelMap["account"] = model.Account + } + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.PassCount != nil { + modelMap["pass_count"] = flex.IntValue(model.PassCount) + } + if model.FailureCount != nil { + modelMap["failure_count"] = flex.IntValue(model.FailureCount) + } + if model.ErrorCount != nil { + modelMap["error_count"] = flex.IntValue(model.ErrorCount) + } + if model.CompletedCount != nil { + modelMap["completed_count"] = flex.IntValue(model.CompletedCount) + } + return modelMap, nil +} + +func dataSourceIbmSccReportSummaryTagsToMap(model *securityandcompliancecenterapiv3.Tags) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.User != nil { + modelMap["user"] = model.User + } + if model.Access != nil { + modelMap["access"] = model.Access + } + if model.Service != nil { + modelMap["service"] = model.Service + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_summary_test.go b/ibm/service/scc/data_source_ibm_scc_report_summary_test.go new file mode 100644 index 0000000000..e28d55ec2b --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_summary_test.go @@ -0,0 +1,39 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccReportSummaryDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccReportSummaryDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_report_summary.scc_report_summary_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report_summary.scc_report_summary_instance", "report_id"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccReportSummaryDataSourceConfigBasic() string { + report_id := os.Getenv("IBMCLOUD_SCC_REPORT_ID") + return fmt.Sprintf(` + data "ibm_scc_report_summary" "scc_report_summary_instance" { + report_id = "%s" + } + `, report_id) +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_tags.go b/ibm/service/scc/data_source_ibm_scc_report_tags.go new file mode 100644 index 0000000000..ad46601842 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_tags.go @@ -0,0 +1,116 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +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/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccReportTags() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccReportTagsRead, + + Schema: map[string]*schema.Schema{ + "report_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The ID of the scan that is associated with a report.", + }, + "tags": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The collection of different types of tags.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "user": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The collection of user tags.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "access": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The collection of access tags.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "service": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The collection of service tags.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccReportTagsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + resultsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getReportTagsOptions := &securityandcompliancecenterapiv3.GetReportTagsOptions{} + + getReportTagsOptions.SetReportID(d.Get("report_id").(string)) + + reportTags, response, err := resultsClient.GetReportTagsWithContext(context, getReportTagsOptions) + if err != nil { + log.Printf("[DEBUG] GetReportTagsWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetReportTagsWithContext failed %s\n%s", err, response)) + } + + d.SetId(dataSourceIbmSccReportTagsID(d)) + + tags := []map[string]interface{}{} + if reportTags.Tags != nil { + modelMap, err := dataSourceIbmSccReportTagsTagsToMap(reportTags.Tags) + if err != nil { + return diag.FromErr(err) + } + tags = append(tags, modelMap) + } + if err = d.Set("tags", tags); err != nil { + return diag.FromErr(fmt.Errorf("Error setting tags %s", err)) + } + + return nil +} + +// dataSourceIbmSccReportTagsID returns a reasonable ID for the list. +func dataSourceIbmSccReportTagsID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func dataSourceIbmSccReportTagsTagsToMap(model *securityandcompliancecenterapiv3.Tags) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.User != nil { + modelMap["user"] = model.User + } + if model.Access != nil { + modelMap["access"] = model.Access + } + if model.Service != nil { + modelMap["service"] = model.Service + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_tags_test.go b/ibm/service/scc/data_source_ibm_scc_report_tags_test.go new file mode 100644 index 0000000000..8319f6a27c --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_tags_test.go @@ -0,0 +1,39 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccReportTagsDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccReportTagsDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_report_tags.scc_report_tags_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report_tags.scc_report_tags_instance", "report_id"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccReportTagsDataSourceConfigBasic() string { + report_id := os.Getenv("IBMCLOUD_SCC_REPORT_ID") + return fmt.Sprintf(` + data "ibm_scc_report_tags" "scc_report_tags_instance" { + report_id = "%s" + } + `, report_id) +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_test.go b/ibm/service/scc/data_source_ibm_scc_report_test.go new file mode 100644 index 0000000000..19feffc1b5 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_test.go @@ -0,0 +1,39 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccReportDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccReportDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_report.scc_report_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report.scc_report_instance", "report_id"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccReportDataSourceConfigBasic() string { + report_id := os.Getenv("IBMCLOUD_SCC_REPORT_ID") + return fmt.Sprintf(` + data "ibm_scc_report" "scc_report_instance" { + report_id = "%s" + } + `, report_id) +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_violation_drift.go b/ibm/service/scc/data_source_ibm_scc_report_violation_drift.go new file mode 100644 index 0000000000..39ba6b307d --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_violation_drift.go @@ -0,0 +1,197 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +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/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccReportViolationDrift() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccReportViolationDriftRead, + + Schema: map[string]*schema.Schema{ + "report_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The ID of the scan that is associated with a report.", + }, + "scan_time_duration": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Default: 0, + Description: "The duration of the `scan_time` timestamp in number of days.", + }, + "home_account_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the home account.", + }, + "data_points": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of report violations data points.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "report_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The ID of the report.", + }, + "report_group_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The group ID that is associated with the report. The group ID combines profile, scope, and attachment IDs.", + }, + "scan_time": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the scan was run.", + }, + "controls": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The compliance stats.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The allowed values of an aggregated status for controls, specifications, assessments, and resources.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The total number of checks.", + }, + "compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of compliant checks.", + }, + "not_compliant_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are not compliant.", + }, + "unable_to_perform_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that are unable to perform.", + }, + "user_evaluation_required_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "The number of checks that require a user evaluation.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmSccReportViolationDriftRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + resultsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getReportViolationsDriftOptions := &securityandcompliancecenterapiv3.GetReportViolationsDriftOptions{} + + getReportViolationsDriftOptions.SetReportID(d.Get("report_id").(string)) + if _, ok := d.GetOk("scan_time_duration"); ok { + getReportViolationsDriftOptions.SetScanTimeDuration(int64(d.Get("scan_time_duration").(int))) + } + + reportViolationsDrift, response, err := resultsClient.GetReportViolationsDriftWithContext(context, getReportViolationsDriftOptions) + if err != nil { + log.Printf("[DEBUG] GetReportViolationsDriftWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetReportViolationsDriftWithContext failed %s\n%s", err, response)) + } + + d.SetId(dataSourceIbmSccReportViolationDriftID(d)) + + if err = d.Set("home_account_id", reportViolationsDrift.HomeAccountID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting home_account_id: %s", err)) + } + + dataPoints := []map[string]interface{}{} + if reportViolationsDrift.DataPoints != nil { + for _, modelItem := range reportViolationsDrift.DataPoints { + modelMap, err := dataSourceIbmSccReportViolationDriftReportViolationDataPointToMap(&modelItem) + if err != nil { + return diag.FromErr(err) + } + dataPoints = append(dataPoints, modelMap) + } + } + if err = d.Set("data_points", dataPoints); err != nil { + return diag.FromErr(fmt.Errorf("Error setting data_points %s", err)) + } + + return nil +} + +// dataSourceIbmSccReportViolationDriftID returns a reasonable ID for the list. +func dataSourceIbmSccReportViolationDriftID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func dataSourceIbmSccReportViolationDriftReportViolationDataPointToMap(model *securityandcompliancecenterapiv3.ReportViolationDataPoint) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ReportID != nil { + modelMap["report_id"] = model.ReportID + } + if model.ReportGroupID != nil { + modelMap["report_group_id"] = model.ReportGroupID + } + if model.ScanTime != nil { + modelMap["scan_time"] = model.ScanTime + } + if model.Controls != nil { + controlsMap, err := dataSourceIbmSccReportViolationDriftComplianceStatsToMap(model.Controls) + if err != nil { + return modelMap, err + } + modelMap["controls"] = []map[string]interface{}{controlsMap} + } + return modelMap, nil +} + +func dataSourceIbmSccReportViolationDriftComplianceStatsToMap(model *securityandcompliancecenterapiv3.ComplianceStats) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.CompliantCount != nil { + modelMap["compliant_count"] = flex.IntValue(model.CompliantCount) + } + if model.NotCompliantCount != nil { + modelMap["not_compliant_count"] = flex.IntValue(model.NotCompliantCount) + } + if model.UnableToPerformCount != nil { + modelMap["unable_to_perform_count"] = flex.IntValue(model.UnableToPerformCount) + } + if model.UserEvaluationRequiredCount != nil { + modelMap["user_evaluation_required_count"] = flex.IntValue(model.UserEvaluationRequiredCount) + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_report_violation_drift_test.go b/ibm/service/scc/data_source_ibm_scc_report_violation_drift_test.go new file mode 100644 index 0000000000..829942fc77 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_report_violation_drift_test.go @@ -0,0 +1,39 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccReportViolationDriftDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccReportViolationDriftDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_report_violation_drift.scc_report_violation_drift_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_report_violation_drift.scc_report_violation_drift_instance", "report_id"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccReportViolationDriftDataSourceConfigBasic() string { + report_id := os.Getenv("IBMCLOUD_SCC_REPORT_ID") + return fmt.Sprintf(` + data "ibm_scc_report_violation_drift" "scc_report_violation_drift_instance" { + report_id = "%s" + } + `, report_id) +} diff --git a/ibm/service/scc/data_source_ibm_scc_rule.go b/ibm/service/scc/data_source_ibm_scc_rule.go new file mode 100644 index 0000000000..84eea610e9 --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_rule.go @@ -0,0 +1,758 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +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/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func DataSourceIbmSccRule() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmSccRuleRead, + Timeouts: &schema.ResourceTimeout{ + Read: schema.DefaultTimeout(40 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "rule_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "The ID of the corresponding rule.", + }, + "created_on": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the rule was created.", + }, + "created_by": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The user who created the rule.", + }, + "updated_on": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The date when the rule was modified.", + }, + "updated_by": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The user who modified the rule.", + }, + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The rule ID.", + }, + "account_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account ID.", + }, + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The details of a rule's response.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The rule type (allowable values are `user_defined` or `system_defined`).", + }, + "version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The version number of a rule.", + }, + "import": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The collection of import parameters.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "parameters": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of import parameters.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The import parameter name.", + }, + "display_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The display name of the property.", + }, + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The propery description.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property type.", + }, + }, + }, + }, + }, + }, + }, + "target": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The rule target.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "service_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The target service name.", + }, + "service_display_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The display name of the target service.", + }, + "resource_kind": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The target resource kind.", + }, + "additional_target_attributes": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of targets supported properties.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The additional target attribute name.", + }, + "operator": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The operator.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The value.", + }, + }, + }, + }, + }, + }, + }, + "required_config": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The required config description.", + }, + "and": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The `AND` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The required config description.", + }, + "or": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The `OR` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The required config description.", + }, + "property": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property.", + }, + "operator": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The operator.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "and": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The `AND` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The required config description.", + }, + "property": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property.", + }, + "operator": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The operator.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "property": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property.", + }, + "operator": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The operator.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "or": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The `OR` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The required config description.", + }, + "or": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The `OR` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The required config description.", + }, + "property": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property.", + }, + "operator": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The operator.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "and": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The `AND` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The required config description.", + }, + "property": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property.", + }, + "operator": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The operator.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "property": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property.", + }, + "operator": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The operator.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "property": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The property.", + }, + "operator": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The operator.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "labels": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The list of labels.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + } +} + +func dataSourceIbmSccRuleRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + configManagerClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getRuleOptions := &securityandcompliancecenterapiv3.GetRuleOptions{} + + getRuleOptions.SetRuleID(d.Get("rule_id").(string)) + + rule, response, err := configManagerClient.GetRuleWithContext(context, getRuleOptions) + if err != nil { + log.Printf("[DEBUG] GetRuleWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetRuleWithContext failed %s\n%s", err, response)) + } + + d.SetId(fmt.Sprintf("%s", *getRuleOptions.RuleID)) + + if err = d.Set("created_on", flex.DateTimeToString(rule.CreatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_on: %s", err)) + } + + if err = d.Set("created_by", rule.CreatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + } + + if err = d.Set("updated_on", flex.DateTimeToString(rule.UpdatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_on: %s", err)) + } + + if err = d.Set("updated_by", rule.UpdatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_by: %s", err)) + } + + if err = d.Set("id", rule.ID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting id: %s", err)) + } + + if err = d.Set("account_id", rule.AccountID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) + } + + if err = d.Set("description", rule.Description); err != nil { + return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + } + + if err = d.Set("type", rule.Type); err != nil { + return diag.FromErr(fmt.Errorf("Error setting type: %s", err)) + } + + if err = d.Set("version", rule.Version); err != nil { + return diag.FromErr(fmt.Errorf("Error setting version: %s", err)) + } + + importVar := []map[string]interface{}{} + if rule.Import != nil { + modelMap, err := dataSourceIbmSccRuleImportToMap(rule.Import) + if err != nil { + return diag.FromErr(err) + } + importVar = append(importVar, modelMap) + } + if err = d.Set("import", importVar); err != nil { + return diag.FromErr(fmt.Errorf("Error setting import %s", err)) + } + + target := []map[string]interface{}{} + if rule.Target != nil { + modelMap, err := dataSourceIbmSccRuleTargetToMap(rule.Target) + if err != nil { + return diag.FromErr(err) + } + target = append(target, modelMap) + } + + if err = d.Set("target", target); err != nil { + return diag.FromErr(fmt.Errorf("Error setting target %s", err)) + } + + if err = d.Set("labels", rule.Labels); err != nil { + return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + } + + requiredConfig := []map[string]interface{}{} + if rule.RequiredConfig != nil { + modelMap, err := dataSourceIbmSccRuleRequiredConfigToMap(rule.RequiredConfig) + if err != nil { + return diag.FromErr(err) + } + requiredConfig = append(requiredConfig, modelMap) + } + if err = d.Set("required_config", requiredConfig); err != nil { + return diag.FromErr(fmt.Errorf("Error setting required_config %s", err)) + } + + return nil +} + +func dataSourceIbmSccRuleImportToMap(model *securityandcompliancecenterapiv3.Import) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Parameters != nil { + parameters := []map[string]interface{}{} + for _, parametersItem := range model.Parameters { + parametersItemMap, err := dataSourceIbmSccRuleParameterToMap(¶metersItem) + if err != nil { + return modelMap, err + } + parameters = append(parameters, parametersItemMap) + } + modelMap["parameters"] = parameters + } + return modelMap, nil +} + +func dataSourceIbmSccRuleParameterToMap(model *securityandcompliancecenterapiv3.Parameter) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.DisplayName != nil { + modelMap["display_name"] = model.DisplayName + } + if model.Description != nil { + modelMap["description"] = model.Description + } + if model.Type != nil { + modelMap["type"] = model.Type + } + return modelMap, nil +} + +func dataSourceIbmSccRuleTargetToMap(model *securityandcompliancecenterapiv3.Target) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["service_name"] = model.ServiceName + if model.ServiceDisplayName != nil { + modelMap["service_display_name"] = model.ServiceDisplayName + } + modelMap["resource_kind"] = model.ResourceKind + if model.AdditionalTargetAttributes != nil { + additionalTargetAttributes := []map[string]interface{}{} + for _, additionalTargetAttributesItem := range model.AdditionalTargetAttributes { + additionalTargetAttributesItemMap, err := dataSourceIbmSccRuleAdditionalTargetAttributeToMap(&additionalTargetAttributesItem) + if err != nil { + return modelMap, err + } + additionalTargetAttributes = append(additionalTargetAttributes, additionalTargetAttributesItemMap) + } + modelMap["additional_target_attributes"] = additionalTargetAttributes + } + return modelMap, nil +} + +func dataSourceIbmSccRuleAdditionalTargetAttributeToMap(model *securityandcompliancecenterapiv3.AdditionalTargetAttribute) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Operator != nil { + modelMap["operator"] = model.Operator + } + if model.Value != nil { + modelMap["value"] = model.Value + } + return modelMap, nil +} + +func dataSourceIbmSccRuleRequiredConfigToMap(model securityandcompliancecenterapiv3.RequiredConfigIntf) (map[string]interface{}, error) { + if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigAnd); ok { + return dataSourceIbmSccRuleRequiredConfigAndToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigAnd)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigOr); ok { + return dataSourceIbmSccRuleRequiredConfigOrToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigOr)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase); ok { + return dataSourceIbmSccRuleRequiredConfigRequiredConfigBaseToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfig); ok { + modelMap := make(map[string]interface{}) + model := model.(*securityandcompliancecenterapiv3.RequiredConfig) + if model.Description != nil { + modelMap["description"] = model.Description + } + if model.And != nil { + and := []map[string]interface{}{} + for _, andItem := range model.And { + andItemMap, err := dataSourceIbmSccRuleRequiredConfigItemsToMap(andItem) + if err != nil { + return modelMap, err + } + and = append(and, andItemMap) + } + modelMap["and"] = and + } + if model.Or != nil { + or := []map[string]interface{}{} + for _, orItem := range model.Or { + orItemMap, err := dataSourceIbmSccRuleRequiredConfigItemsToMap(orItem) + if err != nil { + return modelMap, err + } + or = append(or, orItemMap) + } + modelMap["or"] = or + } + if model.Property != nil { + modelMap["property"] = model.Property + } + if model.Operator != nil { + modelMap["operator"] = model.Operator + } + if model.Value != nil { + modelMap["value"] = model.Value + } + return modelMap, nil + } else { + return nil, fmt.Errorf("Unrecognized securityandcompliancecenterapiv3.RequiredConfigIntf subtype encountered") + } +} + +func dataSourceIbmSccRuleRequiredConfigItemsToMap(model securityandcompliancecenterapiv3.RequiredConfigItemsIntf) (map[string]interface{}, error) { + if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigOr); ok { + return dataSourceIbmSccRuleRequiredConfigItemsRequiredConfigOrToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigOr)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigAnd); ok { + return dataSourceIbmSccRuleRequiredConfigItemsRequiredConfigAndToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigAnd)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigBase); ok { + return dataSourceIbmSccRuleRequiredConfigItemsRequiredConfigBaseToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigBase)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigItems); ok { + modelMap := make(map[string]interface{}) + model := model.(*securityandcompliancecenterapiv3.RequiredConfigItems) + if model.Description != nil { + modelMap["description"] = model.Description + } + if model.Or != nil { + or := []map[string]interface{}{} + for _, orItem := range model.Or { + orItemMap, err := dataSourceIbmSccRuleRequiredConfigItemsToMap(orItem) + if err != nil { + return modelMap, err + } + or = append(or, orItemMap) + } + modelMap["or"] = or + } + if model.And != nil { + and := []map[string]interface{}{} + for _, andItem := range model.And { + andItemMap, err := dataSourceIbmSccRuleRequiredConfigItemsToMap(andItem) + if err != nil { + return modelMap, err + } + and = append(and, andItemMap) + } + modelMap["and"] = and + } + if model.Property != nil { + modelMap["property"] = model.Property + } + if model.Operator != nil { + modelMap["operator"] = model.Operator + } + if model.Value != nil { + modelMap["value"] = model.Value + } + return modelMap, nil + } else { + return nil, fmt.Errorf("Unrecognized securityandcompliancecenterapiv3.RequiredConfigItemsIntf subtype encountered") + } +} + +func dataSourceIbmSccRuleRequiredConfigBaseToMap(model *securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Description != nil { + modelMap["description"] = model.Description + } + modelMap["property"] = model.Property + modelMap["operator"] = model.Operator + if model.Value != nil { + modelMap["value"] = model.Value + } + return modelMap, nil +} + +func dataSourceIbmSccRuleRequiredConfigItemsRequiredConfigOrToMap(model *securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigOr) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Description != nil { + modelMap["description"] = model.Description + } + if model.Or != nil { + or := []map[string]interface{}{} + for _, orItem := range model.Or { + orItemMap, err := dataSourceIbmSccRuleRequiredConfigItemsToMap(orItem.(*securityandcompliancecenterapiv3.RequiredConfigItems)) + if err != nil { + return modelMap, err + } + or = append(or, orItemMap) + } + modelMap["or"] = or + } + return modelMap, nil +} + +func dataSourceIbmSccRuleRequiredConfigItemsRequiredConfigAndToMap(model *securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigAnd) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Description != nil { + modelMap["description"] = model.Description + } + if model.And != nil { + and := []map[string]interface{}{} + for _, andItem := range model.And { + andItemMap, err := dataSourceIbmSccRuleRequiredConfigItemsToMap(andItem.(*securityandcompliancecenterapiv3.RequiredConfigItems)) + if err != nil { + return modelMap, err + } + and = append(and, andItemMap) + } + modelMap["and"] = and + } + return modelMap, nil +} + +func dataSourceIbmSccRuleRequiredConfigItemsRequiredConfigBaseToMap(model *securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigBase) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Description != nil { + modelMap["description"] = model.Description + } + modelMap["property"] = model.Property + modelMap["operator"] = model.Operator + if model.Value != nil { + modelMap["value"] = model.Value + } + return modelMap, nil +} + +func dataSourceIbmSccRuleRequiredConfigAndToMap(model *securityandcompliancecenterapiv3.RequiredConfigRequiredConfigAnd) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Description != nil { + modelMap["description"] = model.Description + } + if model.And != nil { + and := []map[string]interface{}{} + for _, andItem := range model.And { + andItemMap, err := dataSourceIbmSccRuleRequiredConfigItemsToMap(andItem) + if err != nil { + return modelMap, err + } + and = append(and, andItemMap) + } + modelMap["and"] = and + } + return modelMap, nil +} + +func dataSourceIbmSccRuleRequiredConfigOrToMap(model *securityandcompliancecenterapiv3.RequiredConfigRequiredConfigOr) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Description != nil { + modelMap["description"] = model.Description + } + if model.Or != nil { + or := []map[string]interface{}{} + for _, orItem := range model.Or { + orItemMap, err := dataSourceIbmSccRuleRequiredConfigItemsToMap(orItem) + if err != nil { + return modelMap, err + } + or = append(or, orItemMap) + } + modelMap["or"] = or + } + return modelMap, nil +} + +func dataSourceIbmSccRuleRequiredConfigRequiredConfigBaseToMap(model *securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Description != nil { + modelMap["description"] = model.Description + } + modelMap["property"] = model.Property + modelMap["operator"] = model.Operator + if model.Value != nil { + modelMap["value"] = model.Value + } + return modelMap, nil +} diff --git a/ibm/service/scc/data_source_ibm_scc_rule_test.go b/ibm/service/scc/data_source_ibm_scc_rule_test.go new file mode 100644 index 0000000000..92cbeef72a --- /dev/null +++ b/ibm/service/scc/data_source_ibm_scc_rule_test.go @@ -0,0 +1,130 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmSccRuleDataSourceBasic(t *testing.T) { + ruleDescription := fmt.Sprintf("tf_description_%d", acctest.RandIntRange(10, 100)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccRuleDataSourceConfigBasic(ruleDescription), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "rule_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "created_on"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "created_by"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "updated_on"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "updated_by"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "account_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "description"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "type"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "version"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "target.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "required_config.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "labels.#"), + ), + }, + }, + }) +} + +func TestAccIbmSccRuleDataSourceAllArgs(t *testing.T) { + ruleDescription := fmt.Sprintf("tf_description_%d", acctest.RandIntRange(10, 100)) + ruleVersion := "0.0.1" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccRuleDataSourceConfig(ruleDescription, ruleVersion), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "rule_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "created_on"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "created_by"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "updated_on"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "updated_by"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "account_id"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "description"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "type"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "version"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "import.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "target.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "required_config.#"), + resource.TestCheckResourceAttrSet("data.ibm_scc_rule.scc_rule_instance", "labels.#"), + ), + }, + }, + }) +} + +func testAccCheckIbmSccRuleDataSourceConfigBasic(ruleDescription string) string { + return fmt.Sprintf(` + resource "ibm_scc_rule" "scc_rule_instance" { + description = "%s" + target { + service_name = "cloud-object-storage" + resource_kind = "bucket" + } + labels = ["FIX_ME"] + required_config { + description = "required_config_description" + and { + description = "description" + property = "storage_class" + operator = "string_equals" + value = "smart" + } + } + version = "0.0.1" + } + + data "ibm_scc_rule" "scc_rule_instance" { + rule_id = ibm_scc_rule.scc_rule_instance.id + } + `, ruleDescription) +} + +func testAccCheckIbmSccRuleDataSourceConfig(ruleDescription string, ruleVersion string) string { + return fmt.Sprintf(` + resource "ibm_scc_rule" "scc_rule_instance" { + description = "%s" + target { + service_name = "cloud-object-storage" + resource_kind = "bucket" + } + labels = ["FIX_ME"] + required_config { + description = "required_config_description" + and { + description = "description" + property = "storage_class" + operator = "string_equals" + value = "smart" + } + } + version = "%s" + } + + data "ibm_scc_rule" "scc_rule_instance" { + rule_id = ibm_scc_rule.scc_rule_instance.id + } + `, ruleDescription, ruleVersion) +} diff --git a/ibm/service/scc/resource_ibm_scc_account_settings.go b/ibm/service/scc/resource_ibm_scc_account_settings.go index 57fea8f673..05ce32e8cf 100644 --- a/ibm/service/scc/resource_ibm_scc_account_settings.go +++ b/ibm/service/scc/resource_ibm_scc_account_settings.go @@ -5,343 +5,21 @@ package scc import ( "context" - "fmt" - "log" - "time" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/IBM/go-sdk-core/v5/core" - "github.com/IBM/scc-go-sdk/v3/adminserviceapiv1" ) func ResourceIBMSccAccountSettings() *schema.Resource { return &schema.Resource{ - CreateContext: resourceIbmSccAccountSettingsCreate, - ReadContext: resourceIbmSccAccountSettingsRead, - UpdateContext: resourceIbmSccAccountSettingsUpdate, - DeleteContext: resourceIbmSccAccountSettingsDelete, - Importer: &schema.ResourceImporter{}, - - Schema: map[string]*schema.Schema{ - "location_id": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_scc_account_settings", "location_id"), - Description: "The programatic ID of the location that you want to work in.", - Deprecated: "The attribute location_id will soon be deprecated. Please use location instead. See https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/resources/scc_account_settings for details", - }, - "location": &schema.Schema{ - Type: schema.TypeList, - MaxItems: 1, - Optional: true, // Made this Required to avoid drift - ConflictsWith: []string{"location_id"}, - Description: "Location Settings.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "location_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The programatic ID of the location that you want to work in.", - ValidateFunc: validate.InvokeValidator("ibm_scc_account_settings", "location_id"), - }, - }, - }, - }, - "event_notifications": &schema.Schema{ - Type: schema.TypeList, - MaxItems: 1, - Optional: true, - Description: "The Event Notification settings to register.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "instance_crn": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Default: "", - Description: "The Cloud Resource Name (CRN) of the Event Notifications instance that you want to connect.", - }, - }, - }, - // Made a custom DiffSuppressFunc in order to prevent resource drift due to it being Optional - DiffSuppressFunc: func(_, oldValue, newValue string, d *schema.ResourceData) bool { - if _, ok := d.GetOk("event_notifications"); ok { - // oldValue being 1 vs newValue being 0 means the schema field is now missing the *.tf files - if oldValue == "1" && newValue == "0" { - return true - } else { - return oldValue == newValue - } - } else { - return false - } - }, - }, + CreateContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_account_settings has been deprecated") + }, + ReadContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_account_settings has been deprecated") + }, + DeleteContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_account_settings has been deprecated") }, } } - -func resourceIbmSccAccountSettingsCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - log.Printf("[DEBUG] Starting resourceIbmSccAccountSettings%s \n", "Create") - adminServiceApiClient, err := meta.(conns.ClientSession).AdminServiceApiV1() - if err != nil { - return diag.FromErr(err) - } - - // Get the available body that you can put from the SDK - patchAccountSettingsOptions := &adminserviceapiv1.PatchAccountSettingsOptions{} - - userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() - if err != nil { - return diag.FromErr(err) - } - - // Set the patchSettings to use userAccount tied to the API_KEY - patchAccountSettingsOptions.SetAccountID(userDetails.UserAccount) - - getSettingsOptions := &adminserviceapiv1.GetSettingsOptions{} - getSettingsOptions.SetAccountID(userDetails.UserAccount) - - // Check with GetSettings what the current setting is - accountSettings, response, err := adminServiceApiClient.GetSettingsWithContext(context, getSettingsOptions) - - hasChange := false - - // Handle the backwards compatibility - if _, ok := d.GetOk("location_id"); ok { - location_id, exists := d.Get("location_id").(string) - if !exists { - return diag.FromErr(fmt.Errorf("SCC Admin: Failed to insert location_id into CREATE payload")) - } - // if GetSettings is different than the terrafrom config file, prepare a PATCH call - if location_id != *accountSettings.Location.ID { - patchAccountSettingsOptions.SetLocation(&adminserviceapiv1.LocationID{ - ID: core.StringPtr(location_id), - }) - hasChange = true - } - } else if _, ok := d.GetOk("location"); ok { - // check from the local tf file is location is defined - location, err := resourceIbmSccAccountSettingsMapToLocationID(d.Get("location.0").(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - // if GetSettings is different than the terrafrom config file, prepare a PATCH call - if location.ID != accountSettings.Location.ID { - patchAccountSettingsOptions.SetLocation(location) - hasChange = true - } - } - - // check from the local tf file if event_notifications is defined - event_obj := d.Get("event_notifications.0").(map[string]interface{}) - if _, ok := d.GetOk("event_notifications"); ok && event_obj["instance_crn"] != nil { - eventNotifications, err := resourceIbmSccAccountSettingsMapToNotificationsRegistration(d.Get("event_notifications.0").(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - // if GetSettings is different than the terrafrom config file, prepare a PATCH call - if eventNotifications.InstanceCrn != event_obj["instance_crn"] { - patchAccountSettingsOptions.SetEventNotifications(eventNotifications) - hasChange = true - } - } - - // use scc-go-sdk to send the PATCH request if there is a change - if hasChange { - _, response, err = adminServiceApiClient.PatchAccountSettingsWithContext(context, patchAccountSettingsOptions) - if err != nil { - log.Printf("[DEBUG] PatchAccountSettingsWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("PatchAccountSettingsWithContext failed %s\n%s", err, response)) - } - } - // Set the ID of the Terraform object - d.SetId("scc_admin_account_settings") - - return resourceIbmSccAccountSettingsRead(context, d, meta) -} - -func resourceIbmSccAccountSettingID(d *schema.ResourceData) string { - // make a unique ID according to the timestamp - return time.Now().UTC().String() -} - -func resourceIbmSccAccountSettingsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - log.Printf("[DEBUG] Starting resourceIbmSccAccountSettings%s \n", "Read") - adminServiceApiClient, err := meta.(conns.ClientSession).AdminServiceApiV1() - if err != nil { - return diag.FromErr(err) - } - - // Get the Settings to call GetSettings - getSettingsOptions := &adminserviceapiv1.GetSettingsOptions{} - - userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() - if err != nil { - return diag.FromErr(err) - } - - getSettingsOptions.SetAccountID(userDetails.UserAccount) - - // Return back the current Settings according to GetSettings - accountSettings, response, err := adminServiceApiClient.GetSettingsWithContext(context, getSettingsOptions) - if err != nil { - if response != nil && response.StatusCode == 404 { - d.SetId("") - return nil - } - log.Printf("[DEBUG] GetSettingsWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSettingsWithContext failed %s\n%s", err, response)) - } - - if accountSettings.Location != nil { - locationMap, err := resourceIbmSccAccountSettingsLocationIDToMap(accountSettings.Location) - if err != nil { - return diag.FromErr(err) - } - // Handle backwards compatiability - if _, ok := d.GetOk("location_id"); ok { - log.Printf("[DEBUG] Found location_id for Operation %s \n", "Read") - if err = d.Set("location_id", locationMap["location_id"]); err != nil { - return diag.FromErr(fmt.Errorf("Error setting location_id: %s", err)) - } - } else { - if err = d.Set("location", []map[string]interface{}{locationMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting location: %s", err)) - } - } - } - if accountSettings.EventNotifications != nil { - eventNotificationsMap, err := resourceIbmSccAccountSettingsNotificationsRegistrationToMap(accountSettings.EventNotifications) - if err != nil { - return diag.FromErr(err) - } - // if _, ok := d.GetOk("event_notifications"); ok { - log.Println("[DEBUG] event_notifications was found from the resource") - if err = d.Set("event_notifications", []map[string]interface{}{eventNotificationsMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting event_notifications during the read: %s", err)) - } - // } - } - - return nil -} - -func resourceIbmSccAccountSettingsUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - log.Printf("[DEBUG] Starting resourceIbmSccAccountSettings%s \n", "Update") - adminServiceApiClient, err := meta.(conns.ClientSession).AdminServiceApiV1() - if err != nil { - return diag.FromErr(err) - } - - // Use the same logic as resourceIbmSccAccountSettingsCreate - patchAccountSettingsOptions := &adminserviceapiv1.PatchAccountSettingsOptions{} - - userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() - if err != nil { - return diag.FromErr(err) - } - patchAccountSettingsOptions.SetAccountID(userDetails.UserAccount) - - // Flag to see if anything has been changed from the Update(terraform apply) - hasChange := false - - // handle the backwards compatibility - if _, ok := d.GetOk("location_id"); ok && d.HasChange("location_id") { - location_id, exists := d.Get("location_id").(string) - if !exists { - return diag.FromErr(fmt.Errorf("SCC Admin: Failed to insert location_id into Update payload")) - } - // if location is different than the terrafrom config file, prepare a PATCH call - patchAccountSettingsOptions.SetLocation(&adminserviceapiv1.LocationID{ - ID: core.StringPtr(location_id), - }) - hasChange = true - } else if d.HasChange("location") { - location, err := resourceIbmSccAccountSettingsMapToLocationID(d.Get("location.0").(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - patchAccountSettingsOptions.SetLocation(location) - hasChange = true - } - - if d.HasChange("event_notifications") { - eventNotifications, err := resourceIbmSccAccountSettingsMapToNotificationsRegistration(d.Get("event_notifications.0").(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - patchAccountSettingsOptions.SetEventNotifications(eventNotifications) - // if eventNotifications.InstanceCrn != nil && len(*eventNotifications.InstanceCrn) != 0 { - // hasChange = true - // } - hasChange = true - } - - if hasChange { - _, response, err := adminServiceApiClient.PatchAccountSettingsWithContext(context, patchAccountSettingsOptions) - if err != nil { - log.Printf("[DEBUG] PatchAccountSettingsWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("PatchAccountSettingsWithContext failed %s\n%s", err, response)) - } - } - - return resourceIbmSccAccountSettingsRead(context, d, meta) -} - -func resourceIbmSccAccountSettingsDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - // Use GetSettings since there is no API to delete the configuration of the AccountSettings and avoid compiler warnings - adminServiceApiClient, err := meta.(conns.ClientSession).AdminServiceApiV1() - if err != nil { - return diag.FromErr(err) - } - - getSettingsOptions := &adminserviceapiv1.GetSettingsOptions{} - - userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() - if err != nil { - return diag.FromErr(err) - } - - getSettingsOptions.SetAccountID(userDetails.UserAccount) - - _, response, err := adminServiceApiClient.GetSettingsWithContext(context, getSettingsOptions) - if err != nil { - log.Printf("[DEBUG] PatchAccountSettingsWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("PatchAccountSettingsWithContext failed %s\n%s", err, response)) - } - // Set the object to a empty string so Terraform deletes the object - d.SetId("") - - return nil -} - -func resourceIbmSccAccountSettingsMapToLocationID(modelMap map[string]interface{}) (*adminserviceapiv1.LocationID, error) { - model := &adminserviceapiv1.LocationID{} - model.ID = core.StringPtr(modelMap["location_id"].(string)) - return model, nil -} - -func resourceIbmSccAccountSettingsMapToNotificationsRegistration(modelMap map[string]interface{}) (*adminserviceapiv1.NotificationsRegistration, error) { - model := &adminserviceapiv1.NotificationsRegistration{} - model.InstanceCrn = core.StringPtr(modelMap["instance_crn"].(string)) - return model, nil -} - -func resourceIbmSccAccountSettingsLocationIDToMap(model *adminserviceapiv1.LocationID) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - modelMap["location_id"] = model.ID - return modelMap, nil -} - -func resourceIbmSccAccountSettingsNotificationsRegistrationToMap(model *adminserviceapiv1.NotificationsRegistration) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - - // if len(*model.InstanceCrn) > 0 { - modelMap["instance_crn"] = model.InstanceCrn - // } - return modelMap, nil -} diff --git a/ibm/service/scc/resource_ibm_scc_account_settings_test.go b/ibm/service/scc/resource_ibm_scc_account_settings_test.go deleted file mode 100644 index 4d092f7bdc..0000000000 --- a/ibm/service/scc/resource_ibm_scc_account_settings_test.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc_test - -import ( - "fmt" - "testing" - - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" - - "github.com/IBM/scc-go-sdk/v3/adminserviceapiv1" -) - -func TestAccIbmSccAccountSettingsBasic(t *testing.T) { - var conf adminserviceapiv1.AccountSettings - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - CheckDestroy: testAccCheckIbmSccAccountSettingsDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckIbmSccAccountSettingsConfigBasic(), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckIbmSccAccountSettingsExists("ibm_scc_account_settings.scc_account_settings", conf), - resource.TestCheckResourceAttr( - "ibm_scc_account_settings.scc_account_settings", - "location.0.location_id", - "us", - ), - resource.TestCheckResourceAttr( - "ibm_scc_account_settings.scc_account_settings", - "event_notifications.#", - "1", - ), - ), - // ExpectNonEmptyPlan: true, - }, - resource.TestStep{ - ResourceName: "ibm_scc_account_settings.scc_account_settings", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func testAccCheckIbmSccAccountSettingsConfigBasic() string { - return fmt.Sprintf(` - resource "ibm_scc_account_settings" "scc_account_settings" { - location { - location_id = "us" - } - event_notifications { - } - } - `) -} - -func testAccCheckIbmSccAccountSettingsExists(n string, obj adminserviceapiv1.AccountSettings) resource.TestCheckFunc { - - return func(s *terraform.State) error { - // rs, ok := s.RootModule().Resources[n] - _, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - adminServiceApiClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).AdminServiceApiV1() - if err != nil { - return err - } - - getSettingsOptions := &adminserviceapiv1.GetSettingsOptions{} - - userDetails, err := acc.TestAccProvider.Meta().(conns.ClientSession).BluemixUserDetails() - if err != nil { - return err - } - - getSettingsOptions.SetAccountID(userDetails.UserAccount) - - accountSettings, _, err := adminServiceApiClient.GetSettings(getSettingsOptions) - if err != nil { - return err - } - - obj = *accountSettings - return nil - } -} - -func testAccCheckIbmSccAccountSettingsDestroy(s *terraform.State) error { - adminServiceApiClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).AdminServiceApiV1() - if err != nil { - return err - } - for _, rs := range s.RootModule().Resources { - if rs.Type != "ibm_scc_account_settings" { - continue - } - - getSettingsOptions := &adminserviceapiv1.GetSettingsOptions{} - - userDetails, err := acc.TestAccProvider.Meta().(conns.ClientSession).BluemixUserDetails() - if err != nil { - return err - } - getSettingsOptions.SetAccountID(userDetails.UserAccount) - - // Try to find the key - _, response, err := adminServiceApiClient.GetSettings(getSettingsOptions) - if response.StatusCode == 404 { - return fmt.Errorf("Error checking for scc_account_settings (%s) has been destroyed: %s", rs.Primary.ID, err) - } - - } - - return nil -} diff --git a/ibm/service/scc/resource_ibm_scc_account_settings_validator.go b/ibm/service/scc/resource_ibm_scc_account_settings_validator.go deleted file mode 100644 index e907259a38..0000000000 --- a/ibm/service/scc/resource_ibm_scc_account_settings_validator.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc - -import ( - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" -) - -func ResourceIBMSccAccountSettingsValidator() *validate.ResourceValidator { - validateSchema := make([]validate.ValidateSchema, 2) - validateSchema = append(validateSchema, - validate.ValidateSchema{ - Identifier: "location_id", - ValidateFunctionIdentifier: validate.ValidateAllowedStringValue, - Type: validate.TypeString, - Required: true, - AllowedValues: "us, eu, uk", - }, - ) - - resourceValidator := validate.ResourceValidator{ResourceName: "ibm_scc_account_settings", Schema: validateSchema} - return &resourceValidator -} diff --git a/ibm/service/scc/resource_ibm_scc_control_library.go b/ibm/service/scc/resource_ibm_scc_control_library.go new file mode 100644 index 0000000000..f89d21acda --- /dev/null +++ b/ibm/service/scc/resource_ibm_scc_control_library.go @@ -0,0 +1,944 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" + "github.com/IBM/go-sdk-core/v5/core" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func ResourceIbmSccControlLibrary() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIbmSccControlLibraryCreate, + ReadContext: resourceIbmSccControlLibraryRead, + UpdateContext: resourceIbmSccControlLibraryUpdate, + DeleteContext: resourceIbmSccControlLibraryDelete, + Importer: &schema.ResourceImporter{}, + + Schema: map[string]*schema.Schema{ + "control_library_name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_control_library", "control_library_name"), + Description: "The control library name.", + }, + "control_library_description": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_control_library", "control_library_description"), + Description: "The control library description.", + }, + "control_library_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_control_library", "control_library_type"), + Description: "The control library type.", + }, + "version_group_label": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_control_library", "version_group_label"), + Description: "The version group label.", + }, + "control_library_version": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: func() (any, error) { return "0.0.0", nil }, + ValidateFunc: validate.InvokeValidator("ibm_scc_control_library", "control_library_version"), + Description: "The control library version.", + }, + "latest": { + Type: schema.TypeBool, + Optional: true, + Description: "The latest version of the control library.", + }, + "controls_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of controls.", + }, + "controls": { + Type: schema.TypeList, + Required: true, + Description: "The list of controls in a control library.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_name": { + Type: schema.TypeString, + Optional: true, + Description: "The control name.", + }, + "control_id": { + Type: schema.TypeString, + Optional: true, + Description: "The ID of the control library that contains the profile.", + }, + "control_description": { + Type: schema.TypeString, + Optional: true, + Description: "The control description.", + }, + "control_category": { + Type: schema.TypeString, + Optional: true, + Description: "The control category.", + }, + "control_parent": { + Type: schema.TypeString, + Optional: true, + Description: "The parent control.", + }, + "control_tags": { + Type: schema.TypeList, + Optional: true, + Description: "The control tags.", + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "control_specifications": { + Type: schema.TypeList, + Optional: true, + Description: "The control specifications.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_specification_id": { + Type: schema.TypeString, + Optional: true, + Description: "The control specification ID.", + }, + "responsibility": { + Type: schema.TypeString, + Optional: true, + Description: "The responsibility for managing the control.", + }, + "component_id": { + Type: schema.TypeString, + Optional: true, + Description: "The component ID.", + }, + "component_name": { + Type: schema.TypeString, + Optional: true, + Description: "The component name.", + }, + "environment": { + Type: schema.TypeString, + Optional: true, + Description: "The control specifications environment.", + }, + "control_specification_description": { + Type: schema.TypeString, + Optional: true, + Description: "The control specifications description.", + }, + "assessments_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of assessments.", + }, + "assessments": { + Type: schema.TypeList, + Optional: true, + Description: "The assessments.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "assessment_id": { + Type: schema.TypeString, + Optional: true, + Description: "The assessment ID.", + }, + "assessment_method": { + Type: schema.TypeString, + Optional: true, + Description: "The assessment method.", + }, + "assessment_type": { + Type: schema.TypeString, + Optional: true, + Description: "The assessment type.", + }, + "assessment_description": { + Type: schema.TypeString, + Optional: true, + Description: "The assessment description.", + }, + "parameter_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The parameter count.", + }, + "parameters": { + Type: schema.TypeList, + Optional: true, + Description: "The parameters.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "parameter_name": { + Type: schema.TypeString, + Optional: true, + Description: "The parameter name.", + }, + "parameter_display_name": { + Type: schema.TypeString, + Optional: true, + Description: "The parameter display name.", + }, + "parameter_type": { + Type: schema.TypeString, + Optional: true, + Description: "The parameter type.", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + "control_docs": { + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + Description: "The control documentation.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_docs_id": { + Type: schema.TypeString, + Optional: true, + Description: "The ID of the control documentation.", + }, + "control_docs_type": { + Type: schema.TypeString, + Optional: true, + Description: "The type of control documentation.", + }, + }, + }, + }, + "control_requirement": { + Type: schema.TypeBool, + Optional: true, + Description: "Is this a control that can be automated or manually evaluated.", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "The control status.", + }, + }, + }, + }, + "account_id": { + Type: schema.TypeString, + Computed: true, + Description: "The account ID.", + }, + "created_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the control library was created.", + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who created the control library.", + }, + "updated_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the control library was updated.", + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who updated the control library.", + }, + "hierarchy_enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "The indication of whether hierarchy is enabled for the control library.", + }, + "control_parents_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of parent controls in the control library.", + }, + }, + } +} + +func ResourceIbmSccControlLibraryValidator() *validate.ResourceValidator { + validateSchema := make([]validate.ValidateSchema, 0) + validateSchema = append(validateSchema, + validate.ValidateSchema{ + Identifier: "control_library_name", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^[a-zA-Z0-9_\s\-]*$`, + MinValueLength: 2, + MaxValueLength: 64, + }, + validate.ValidateSchema{ + Identifier: "control_library_description", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `[A-Za-z0-9]+`, + MinValueLength: 2, + MaxValueLength: 256, + }, + validate.ValidateSchema{ + Identifier: "control_library_type", + ValidateFunctionIdentifier: validate.ValidateAllowedStringValue, + Type: validate.TypeString, + Required: true, + AllowedValues: "custom, predefined", + }, + validate.ValidateSchema{ + Identifier: "version_group_label", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Optional: true, + Regexp: `^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`, + MinValueLength: 36, + MaxValueLength: 36, + }, + validate.ValidateSchema{ + Identifier: "control_library_version", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Optional: true, + Regexp: `^[a-zA-Z0-9_\-.]*$`, + MinValueLength: 5, + MaxValueLength: 64, + }, + ) + + resourceValidator := validate.ResourceValidator{ResourceName: "ibm_scc_control_library", Schema: validateSchema} + return &resourceValidator +} + +func resourceIbmSccControlLibraryCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + bodyModelMap := map[string]interface{}{} + createCustomControlLibraryOptions := &securityandcompliancecenterapiv3.CreateCustomControlLibraryOptions{} + + bodyModelMap["control_library_name"] = d.Get("control_library_name") + bodyModelMap["control_library_description"] = d.Get("control_library_description") + bodyModelMap["control_library_type"] = d.Get("control_library_type") + if _, ok := d.GetOk("version_group_label"); ok { + bodyModelMap["version_group_label"] = d.Get("version_group_label") + } + if _, ok := d.GetOk("control_library_version"); ok { + bodyModelMap["control_library_version"] = d.Get("control_library_version") + } + if _, ok := d.GetOk("latest"); ok { + bodyModelMap["latest"] = d.Get("latest") + } + if _, ok := d.GetOk("controls_count"); ok { + bodyModelMap["controls_count"] = d.Get("controls_count") + } + bodyModelMap["controls"] = d.Get("controls") + + convertedModel, err := resourceIbmSccControlLibraryMapToControlLibraryPrototype(bodyModelMap) + if err != nil { + log.Printf("[DEBUG] CreateCustomControlLibraryWithContext failed %s\n", err) + return diag.FromErr(fmt.Errorf("CreateCustomControlLibraryWithContext failed %s\n", err)) + } + createCustomControlLibraryOptions = convertedModel + controlLibrary, response, err := securityandcompliancecenterapiClient.CreateCustomControlLibraryWithContext(context, createCustomControlLibraryOptions) + if err != nil { + log.Printf("[DEBUG] CreateCustomControlLibraryWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("CreateCustomControlLibraryWithContext failed %s\n%s", err, response)) + } + + d.SetId(*controlLibrary.ID) + + return resourceIbmSccControlLibraryRead(context, d, meta) +} + +func resourceIbmSccControlLibraryRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getControlLibraryOptions := &securityandcompliancecenterapiv3.GetControlLibraryOptions{} + + getControlLibraryOptions.SetControlLibrariesID(d.Id()) + + controlLibrary, response, err := securityandcompliancecenterapiClient.GetControlLibraryWithContext(context, getControlLibraryOptions) + if err != nil { + if response != nil && response.StatusCode == 404 { + d.SetId("") + return nil + } + log.Printf("[DEBUG] GetControlLibraryWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetControlLibraryWithContext failed %s\n%s", err, response)) + } + + if err = d.Set("control_library_name", controlLibrary.ControlLibraryName); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_library_name: %s", err)) + } + if err = d.Set("control_library_description", controlLibrary.ControlLibraryDescription); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_library_description: %s", err)) + } + if err = d.Set("control_library_type", controlLibrary.ControlLibraryType); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_library_type: %s", err)) + } + if !core.IsNil(controlLibrary.VersionGroupLabel) { + if err = d.Set("version_group_label", controlLibrary.VersionGroupLabel); err != nil { + return diag.FromErr(fmt.Errorf("Error setting version_group_label: %s", err)) + } + } + if !core.IsNil(controlLibrary.ControlLibraryVersion) { + if err = d.Set("control_library_version", controlLibrary.ControlLibraryVersion); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_library_version: %s", err)) + } + } + if !core.IsNil(controlLibrary.Latest) { + if err = d.Set("latest", controlLibrary.Latest); err != nil { + return diag.FromErr(fmt.Errorf("Error setting latest: %s", err)) + } + } + if !core.IsNil(controlLibrary.ControlsCount) { + if err = d.Set("controls_count", flex.IntValue(controlLibrary.ControlsCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls_count: %s", err)) + } + } + controls := []map[string]interface{}{} + for _, controlsItem := range controlLibrary.Controls { + controlsItemMap, err := resourceIbmSccControlLibraryControlsInControlLibToMap(&controlsItem) + if err != nil { + return diag.FromErr(err) + } + controls = append(controls, controlsItemMap) + } + if err = d.Set("controls", controls); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls: %s", err)) + } + if !core.IsNil(controlLibrary.AccountID) { + if err = d.Set("account_id", controlLibrary.AccountID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) + } + } + if !core.IsNil(controlLibrary.CreatedOn) { + if err = d.Set("created_on", flex.DateTimeToString(controlLibrary.CreatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_on: %s", err)) + } + } + if !core.IsNil(controlLibrary.CreatedBy) { + if err = d.Set("created_by", controlLibrary.CreatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + } + } + if !core.IsNil(controlLibrary.UpdatedOn) { + if err = d.Set("updated_on", flex.DateTimeToString(controlLibrary.UpdatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_on: %s", err)) + } + } + if !core.IsNil(controlLibrary.UpdatedBy) { + if err = d.Set("updated_by", controlLibrary.UpdatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_by: %s", err)) + } + } + if !core.IsNil(controlLibrary.HierarchyEnabled) { + if err = d.Set("hierarchy_enabled", controlLibrary.HierarchyEnabled); err != nil { + return diag.FromErr(fmt.Errorf("Error setting hierarchy_enabled: %s", err)) + } + } + if !core.IsNil(controlLibrary.ControlParentsCount) { + if err = d.Set("control_parents_count", flex.IntValue(controlLibrary.ControlParentsCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_parents_count: %s", err)) + } + } + + return nil +} + +func resourceIbmSccControlLibraryUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + replaceCustomControlLibraryOptions := &securityandcompliancecenterapiv3.ReplaceCustomControlLibraryOptions{} + + replaceCustomControlLibraryOptions.SetControlLibrariesID(d.Id()) + + hasChange := false + + if d.HasChange("control_library") { + controlLibrary, err := resourceIbmSccControlLibraryMapToControlLibrary(d.Get("control_library.0").(map[string]interface{})) + if err != nil { + return diag.FromErr(err) + } + replaceCustomControlLibraryOptions.SetControlLibrariesID(*controlLibrary.ID) + hasChange = true + } + + if d.HasChange("controls") { + for _, controlsItem := range d.Get("controls").([]interface{}) { + controlsItemModel, err := resourceIbmSccControlLibraryMapToControlsInControlLib(controlsItem.(map[string]interface{})) + if err != nil { + return diag.FromErr(fmt.Errorf("ReplaceCustomControlLibraryWithContext failed %s\n", err)) + } + replaceCustomControlLibraryOptions.Controls = append(replaceCustomControlLibraryOptions.Controls, *controlsItemModel) + } + hasChange = true + } + if d.HasChange("control_library_version") { + replaceCustomControlLibraryOptions.SetControlLibraryVersion(d.Get("control_library_version").(string)) + hasChange = true + } + + if hasChange { + if replaceCustomControlLibraryOptions.ControlLibraryName == nil { + replaceCustomControlLibraryOptions.SetControlLibraryName(d.Get("control_library_name").(string)) + } + if replaceCustomControlLibraryOptions.ControlLibraryDescription == nil { + replaceCustomControlLibraryOptions.SetControlLibraryDescription(d.Get("control_library_description").(string)) + } + if replaceCustomControlLibraryOptions.ControlLibraryVersion == nil { + replaceCustomControlLibraryOptions.SetControlLibraryDescription(d.Get("control_library_version").(string)) + } + if len(replaceCustomControlLibraryOptions.Controls) == 0 { + for _, controlsItem := range d.Get("controls").([]interface{}) { + controlsItemModel, err := resourceIbmSccControlLibraryMapToControlsInControlLib(controlsItem.(map[string]interface{})) + if err != nil { + return diag.FromErr(fmt.Errorf("ReplaceCustomControlLibraryWithContext failed %s\n", err)) + } + replaceCustomControlLibraryOptions.Controls = append(replaceCustomControlLibraryOptions.Controls, *controlsItemModel) + } + } + _, response, err := securityandcompliancecenterapiClient.ReplaceCustomControlLibraryWithContext(context, replaceCustomControlLibraryOptions) + if err != nil { + log.Printf("[DEBUG] ReplaceCustomControlLibraryWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("ReplaceCustomControlLibraryWithContext failed %s\n%s", err, response)) + } + } + + return resourceIbmSccControlLibraryRead(context, d, meta) +} + +func resourceIbmSccControlLibraryDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + deleteCustomControlLibraryOptions := &securityandcompliancecenterapiv3.DeleteCustomControlLibraryOptions{} + + deleteCustomControlLibraryOptions.SetControlLibrariesID(d.Id()) + + _, response, err := securityandcompliancecenterapiClient.DeleteCustomControlLibraryWithContext(context, deleteCustomControlLibraryOptions) + if err != nil { + log.Printf("[DEBUG] DeleteCustomControlLibraryWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("DeleteCustomControlLibraryWithContext failed %s\n%s", err, response)) + } + + d.SetId("") + + return nil +} + +func resourceIbmSccControlLibraryMapToControlsInControlLib(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.ControlsInControlLib, error) { + model := &securityandcompliancecenterapiv3.ControlsInControlLib{} + if modelMap["control_name"] != nil && modelMap["control_name"].(string) != "" { + model.ControlName = core.StringPtr(modelMap["control_name"].(string)) + } + if modelMap["control_id"] != nil && modelMap["control_id"].(string) != "" { + model.ControlID = core.StringPtr(modelMap["control_id"].(string)) + } + if modelMap["control_description"] != nil && modelMap["control_description"].(string) != "" { + model.ControlDescription = core.StringPtr(modelMap["control_description"].(string)) + } + if modelMap["control_category"] != nil && modelMap["control_category"].(string) != "" { + model.ControlCategory = core.StringPtr(modelMap["control_category"].(string)) + } + if modelMap["control_parent"] != nil && modelMap["control_parent"].(string) != "" { + model.ControlParent = core.StringPtr(modelMap["control_parent"].(string)) + } + if modelMap["control_tags"] != nil { + controlTags := []string{} + for _, controlTagsItem := range modelMap["control_tags"].([]interface{}) { + controlTags = append(controlTags, controlTagsItem.(string)) + } + model.ControlTags = controlTags + } + if modelMap["control_specifications"] != nil { + controlSpecifications := []securityandcompliancecenterapiv3.ControlSpecifications{} + for _, controlSpecificationsItem := range modelMap["control_specifications"].([]interface{}) { + controlSpecificationsItemModel, err := resourceIbmSccControlLibraryMapToControlSpecifications(controlSpecificationsItem.(map[string]interface{})) + if err != nil { + return model, err + } + controlSpecifications = append(controlSpecifications, *controlSpecificationsItemModel) + } + model.ControlSpecifications = controlSpecifications + } + if modelMap["control_docs"].([]interface{})[0] != nil && len(modelMap["control_docs"].([]interface{})[0].(map[string]interface{})) > 0 { + ControlDocsModel, err := resourceIbmSccControlLibraryMapToControlDocs(modelMap["control_docs"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.ControlDocs = ControlDocsModel + } + if modelMap["control_requirement"] != nil { + model.ControlRequirement = core.BoolPtr(modelMap["control_requirement"].(bool)) + } + if modelMap["status"] != nil && modelMap["status"].(string) != "" { + model.Status = core.StringPtr(modelMap["status"].(string)) + } + return model, nil +} + +func resourceIbmSccControlLibraryMapToControlSpecifications(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.ControlSpecifications, error) { + model := &securityandcompliancecenterapiv3.ControlSpecifications{} + if modelMap["control_specification_id"] != nil && modelMap["control_specification_id"].(string) != "" { + model.ControlSpecificationID = core.StringPtr(modelMap["control_specification_id"].(string)) + } + if modelMap["responsibility"] != nil && modelMap["responsibility"].(string) != "" { + model.Responsibility = core.StringPtr(modelMap["responsibility"].(string)) + } + if modelMap["component_id"] != nil && modelMap["component_id"].(string) != "" { + model.ComponentID = core.StringPtr(modelMap["component_id"].(string)) + } + if modelMap["component_name"] != nil && modelMap["component_name"].(string) != "" { + model.ComponentName = core.StringPtr(modelMap["component_name"].(string)) + } + if modelMap["environment"] != nil && modelMap["environment"].(string) != "" { + model.Environment = core.StringPtr(modelMap["environment"].(string)) + } + if modelMap["control_specification_description"] != nil && modelMap["control_specification_description"].(string) != "" { + model.ControlSpecificationDescription = core.StringPtr(modelMap["control_specification_description"].(string)) + } + if modelMap["assessments_count"] != nil { + model.AssessmentsCount = core.Int64Ptr(int64(modelMap["assessments_count"].(int))) + } + if modelMap["assessments"] != nil { + assessments := []securityandcompliancecenterapiv3.Implementation{} + for _, assessmentsItem := range modelMap["assessments"].([]interface{}) { + assessmentsItemModel, err := resourceIbmSccControlLibraryMapToImplementation(assessmentsItem.(map[string]interface{})) + if err != nil { + return model, err + } + assessments = append(assessments, *assessmentsItemModel) + } + model.Assessments = assessments + } + return model, nil +} + +func resourceIbmSccControlLibraryMapToImplementation(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.Implementation, error) { + model := &securityandcompliancecenterapiv3.Implementation{} + if modelMap["assessment_id"] != nil && modelMap["assessment_id"].(string) != "" { + model.AssessmentID = core.StringPtr(modelMap["assessment_id"].(string)) + } + if modelMap["assessment_method"] != nil && modelMap["assessment_method"].(string) != "" { + model.AssessmentMethod = core.StringPtr(modelMap["assessment_method"].(string)) + } + if modelMap["assessment_type"] != nil && modelMap["assessment_type"].(string) != "" { + model.AssessmentType = core.StringPtr(modelMap["assessment_type"].(string)) + } + if modelMap["assessment_description"] != nil && modelMap["assessment_description"].(string) != "" { + model.AssessmentDescription = core.StringPtr(modelMap["assessment_description"].(string)) + } + if modelMap["parameter_count"] != nil { + model.ParameterCount = core.Int64Ptr(int64(modelMap["parameter_count"].(int))) + } + if modelMap["parameters"] != nil { + parameters := []securityandcompliancecenterapiv3.ParameterInfo{} + for _, parametersItem := range modelMap["parameters"].([]interface{}) { + if parametersItem != nil { + parametersItemModel, err := resourceIbmSccControlLibraryMapToParameterInfo(parametersItem.(map[string]interface{})) + if err != nil { + return model, err + } + parameters = append(parameters, *parametersItemModel) + } + } + model.Parameters = parameters + } + return model, nil +} + +func resourceIbmSccControlLibraryMapToParameterInfo(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.ParameterInfo, error) { + model := &securityandcompliancecenterapiv3.ParameterInfo{} + if modelMap["parameter_name"] != nil && modelMap["parameter_name"].(string) != "" { + model.ParameterName = core.StringPtr(modelMap["parameter_name"].(string)) + } + if modelMap["parameter_display_name"] != nil && modelMap["parameter_display_name"].(string) != "" { + model.ParameterDisplayName = core.StringPtr(modelMap["parameter_display_name"].(string)) + } + if modelMap["parameter_type"] != nil && modelMap["parameter_type"].(string) != "" { + model.ParameterType = core.StringPtr(modelMap["parameter_type"].(string)) + } + return model, nil +} + +func resourceIbmSccControlLibraryMapToControlDocs(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.ControlDocs, error) { + model := &securityandcompliancecenterapiv3.ControlDocs{} + if modelMap["control_docs_id"] != nil && modelMap["control_docs_id"].(string) != "" { + model.ControlDocsID = core.StringPtr(modelMap["control_docs_id"].(string)) + } + if modelMap["control_docs_type"] != nil && modelMap["control_docs_type"].(string) != "" { + model.ControlDocsType = core.StringPtr(modelMap["control_docs_type"].(string)) + } + return model, nil +} + +func resourceIbmSccControlLibraryMapToControlLibrary(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.ControlLibrary, error) { + model := &securityandcompliancecenterapiv3.ControlLibrary{} + if modelMap["id"] != nil && modelMap["id"].(string) != "" { + model.ID = core.StringPtr(modelMap["id"].(string)) + } + if modelMap["account_id"] != nil && modelMap["account_id"].(string) != "" { + model.AccountID = core.StringPtr(modelMap["account_id"].(string)) + } + if modelMap["control_library_name"] != nil && modelMap["control_library_name"].(string) != "" { + model.ControlLibraryName = core.StringPtr(modelMap["control_library_name"].(string)) + } + if modelMap["control_library_description"] != nil && modelMap["control_library_description"].(string) != "" { + model.ControlLibraryDescription = core.StringPtr(modelMap["control_library_description"].(string)) + } + if modelMap["control_library_type"] != nil && modelMap["control_library_type"].(string) != "" { + model.ControlLibraryType = core.StringPtr(modelMap["control_library_type"].(string)) + } + if modelMap["version_group_label"] != nil && modelMap["version_group_label"].(string) != "" { + model.VersionGroupLabel = core.StringPtr(modelMap["version_group_label"].(string)) + } + if modelMap["control_library_version"] != nil && modelMap["control_library_version"].(string) != "" { + model.ControlLibraryVersion = core.StringPtr(modelMap["control_library_version"].(string)) + } + if modelMap["created_on"] != nil { + dateTime, err := core.ParseDateTime(modelMap["created_on"].(string)) + if err != nil { + return model, err + } + model.CreatedOn = &dateTime + } + if modelMap["created_by"] != nil && modelMap["created_by"].(string) != "" { + model.CreatedBy = core.StringPtr(modelMap["created_by"].(string)) + } + if modelMap["updated_on"] != nil { + dateTime, err := core.ParseDateTime(modelMap["updated_on"].(string)) + if err != nil { + return model, err + } + model.UpdatedOn = &dateTime + } + if modelMap["updated_by"] != nil && modelMap["updated_by"].(string) != "" { + model.UpdatedBy = core.StringPtr(modelMap["updated_by"].(string)) + } + if modelMap["latest"] != nil { + model.Latest = core.BoolPtr(modelMap["latest"].(bool)) + } + if modelMap["hierarchy_enabled"] != nil { + model.HierarchyEnabled = core.BoolPtr(modelMap["hierarchy_enabled"].(bool)) + } + if modelMap["controls_count"] != nil { + model.ControlsCount = core.Int64Ptr(int64(modelMap["controls_count"].(int))) + } + if modelMap["control_parents_count"] != nil { + model.ControlParentsCount = core.Int64Ptr(int64(modelMap["control_parents_count"].(int))) + } + if modelMap["controls"] != nil { + controls := []securityandcompliancecenterapiv3.ControlsInControlLib{} + for _, controlsItem := range modelMap["controls"].([]interface{}) { + controlsItemModel, err := resourceIbmSccControlLibraryMapToControlsInControlLib(controlsItem.(map[string]interface{})) + if err != nil { + return model, err + } + controls = append(controls, *controlsItemModel) + } + model.Controls = controls + } + return model, nil +} + +func resourceIbmSccControlLibraryMapToControlLibraryPrototype(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.CreateCustomControlLibraryOptions, error) { + model := &securityandcompliancecenterapiv3.CreateCustomControlLibraryOptions{} + model.ControlLibraryName = core.StringPtr(modelMap["control_library_name"].(string)) + model.ControlLibraryDescription = core.StringPtr(modelMap["control_library_description"].(string)) + model.ControlLibraryType = core.StringPtr(modelMap["control_library_type"].(string)) + if modelMap["version_group_label"] != nil && modelMap["version_group_label"].(string) != "" { + model.VersionGroupLabel = core.StringPtr(modelMap["version_group_label"].(string)) + } + if modelMap["control_library_version"] != nil && modelMap["control_library_version"].(string) != "" { + model.ControlLibraryVersion = core.StringPtr(modelMap["control_library_version"].(string)) + } + if modelMap["latest"] != nil { + model.Latest = core.BoolPtr(modelMap["latest"].(bool)) + } + if modelMap["controls_count"] != nil { + model.ControlsCount = core.Int64Ptr(int64(modelMap["controls_count"].(int))) + } + controls := []securityandcompliancecenterapiv3.ControlsInControlLib{} + for _, controlsItem := range modelMap["controls"].([]interface{}) { + controlsItemModel, err := resourceIbmSccControlLibraryMapToControlsInControlLib(controlsItem.(map[string]interface{})) + if err != nil { + return model, err + } + controls = append(controls, *controlsItemModel) + } + model.Controls = controls + return model, nil +} + +func resourceIbmSccControlLibraryControlsInControlLibToMap(model *securityandcompliancecenterapiv3.ControlsInControlLib) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlName != nil { + modelMap["control_name"] = model.ControlName + } + if model.ControlID != nil { + modelMap["control_id"] = model.ControlID + } + if model.ControlDescription != nil { + modelMap["control_description"] = model.ControlDescription + } + if model.ControlCategory != nil { + modelMap["control_category"] = model.ControlCategory + } + if model.ControlParent != nil { + modelMap["control_parent"] = model.ControlParent + } + if model.ControlTags != nil { + modelMap["control_tags"] = model.ControlTags + } + if model.ControlSpecifications != nil { + controlSpecifications := []map[string]interface{}{} + for _, controlSpecificationsItem := range model.ControlSpecifications { + controlSpecificationsItemMap, err := resourceIbmSccControlLibraryControlSpecificationsToMap(&controlSpecificationsItem) + if err != nil { + return modelMap, err + } + controlSpecifications = append(controlSpecifications, controlSpecificationsItemMap) + } + modelMap["control_specifications"] = controlSpecifications + } + if model.ControlDocs != nil { + controlDocsMap, err := resourceIbmSccControlLibraryControlDocsToMap(model.ControlDocs) + if err != nil { + return modelMap, err + } + modelMap["control_docs"] = []map[string]interface{}{controlDocsMap} + } + if model.ControlRequirement != nil { + modelMap["control_requirement"] = model.ControlRequirement + } + if model.Status != nil { + modelMap["status"] = model.Status + } + return modelMap, nil +} + +func resourceIbmSccControlLibraryControlSpecificationsToMap(model *securityandcompliancecenterapiv3.ControlSpecifications) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlSpecificationID != nil { + modelMap["control_specification_id"] = model.ControlSpecificationID + } + if model.Responsibility != nil { + modelMap["responsibility"] = model.Responsibility + } + if model.ComponentID != nil { + modelMap["component_id"] = model.ComponentID + } + if model.ComponentName != nil { + modelMap["component_name"] = model.ComponentName + } + if model.Environment != nil { + modelMap["environment"] = model.Environment + } + if model.ControlSpecificationDescription != nil { + modelMap["control_specification_description"] = model.ControlSpecificationDescription + } + if model.AssessmentsCount != nil { + modelMap["assessments_count"] = flex.IntValue(model.AssessmentsCount) + } + if model.Assessments != nil { + assessments := []map[string]interface{}{} + for _, assessmentsItem := range model.Assessments { + assessmentsItemMap, err := resourceIbmSccControlLibraryImplementationToMap(&assessmentsItem) + if err != nil { + return modelMap, err + } + assessments = append(assessments, assessmentsItemMap) + } + modelMap["assessments"] = assessments + } + return modelMap, nil +} + +func resourceIbmSccControlLibraryImplementationToMap(model *securityandcompliancecenterapiv3.Implementation) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AssessmentID != nil { + modelMap["assessment_id"] = model.AssessmentID + } + if model.AssessmentMethod != nil { + modelMap["assessment_method"] = model.AssessmentMethod + } + if model.AssessmentType != nil { + modelMap["assessment_type"] = model.AssessmentType + } + if model.AssessmentDescription != nil { + modelMap["assessment_description"] = model.AssessmentDescription + } + if model.ParameterCount != nil { + modelMap["parameter_count"] = flex.IntValue(model.ParameterCount) + } + if model.Parameters != nil { + parameters := []map[string]interface{}{} + for _, parametersItem := range model.Parameters { + parametersItemMap, err := resourceIbmSccControlLibraryParameterInfoToMap(¶metersItem) + if err != nil { + return modelMap, err + } + parameters = append(parameters, parametersItemMap) + } + modelMap["parameters"] = parameters + } + return modelMap, nil +} + +func resourceIbmSccControlLibraryParameterInfoToMap(model *securityandcompliancecenterapiv3.ParameterInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ParameterName != nil { + modelMap["parameter_name"] = model.ParameterName + } + if model.ParameterDisplayName != nil { + modelMap["parameter_display_name"] = model.ParameterDisplayName + } + if model.ParameterType != nil { + modelMap["parameter_type"] = model.ParameterType + } + return modelMap, nil +} + +func resourceIbmSccControlLibraryControlDocsToMap(model *securityandcompliancecenterapiv3.ControlDocs) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlDocsID != nil { + modelMap["control_docs_id"] = model.ControlDocsID + } + if model.ControlDocsType != nil { + modelMap["control_docs_type"] = model.ControlDocsType + } + return modelMap, nil +} diff --git a/ibm/service/scc/resource_ibm_scc_control_library_test.go b/ibm/service/scc/resource_ibm_scc_control_library_test.go new file mode 100644 index 0000000000..ecc8a35da2 --- /dev/null +++ b/ibm/service/scc/resource_ibm_scc_control_library_test.go @@ -0,0 +1,252 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func TestAccIbmSccControlLibraryBasic(t *testing.T) { + var conf securityandcompliancecenterapiv3.ControlLibrary + controlLibraryName := fmt.Sprintf("tf_control_library_name_%d", acctest.RandIntRange(10, 100)) + controlLibraryDescription := fmt.Sprintf("tf_control_library_description_%d", acctest.RandIntRange(10, 100)) + controlLibraryType := "custom" + controlLibraryNameUpdate := controlLibraryName + controlLibraryDescriptionUpdate := controlLibraryDescription + controlLibraryTypeUpdate := controlLibraryType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmSccControlLibraryDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccControlLibraryConfigBasic(controlLibraryName, controlLibraryDescription, controlLibraryType), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmSccControlLibraryExists("ibm_scc_control_library.scc_control_library_instance", conf), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_name", controlLibraryName), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_description", controlLibraryDescription), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_type", controlLibraryType), + ), + }, + resource.TestStep{ + Config: testAccCheckIbmSccControlLibraryConfigBasic(controlLibraryNameUpdate, controlLibraryDescriptionUpdate, controlLibraryTypeUpdate), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_name", controlLibraryNameUpdate), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_description", controlLibraryDescriptionUpdate), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_type", controlLibraryTypeUpdate), + ), + }, + }, + }) +} + +func TestAccIbmSccControlLibraryAllArgs(t *testing.T) { + var conf securityandcompliancecenterapiv3.ControlLibrary + controlLibraryName := fmt.Sprintf("tf_control_library_name_%d", acctest.RandIntRange(10, 100)) + controlLibraryDescription := fmt.Sprintf("tf_control_library_description_%d", acctest.RandIntRange(10, 100)) + controlLibraryType := "custom" + versionGroupLabel := "11111111-2222-3333-4444-555555555555" + controlLibraryVersion := "0.0.1" + latest := "true" + controlsCount := "1" + + controlLibraryNameUpdate := controlLibraryName + controlLibraryDescriptionUpdate := controlLibraryDescription + controlLibraryTypeUpdate := "custom" + versionGroupLabelUpdate := versionGroupLabel + controlLibraryVersionUpdate := "0.0.2" + latestUpdate := "true" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmSccControlLibraryDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccControlLibraryConfig(controlLibraryName, controlLibraryDescription, controlLibraryType, versionGroupLabel, controlLibraryVersion, latest), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmSccControlLibraryExists("ibm_scc_control_library.scc_control_library_instance", conf), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_name", controlLibraryName), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_description", controlLibraryDescription), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_type", controlLibraryType), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "version_group_label", versionGroupLabel), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_version", controlLibraryVersion), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "latest", latest), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "controls_count", controlsCount), + ), + }, + resource.TestStep{ + Config: testAccCheckIbmSccControlLibraryConfig(controlLibraryNameUpdate, controlLibraryDescriptionUpdate, controlLibraryTypeUpdate, versionGroupLabelUpdate, controlLibraryVersionUpdate, latestUpdate), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_name", controlLibraryNameUpdate), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_description", controlLibraryDescriptionUpdate), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_type", controlLibraryTypeUpdate), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "version_group_label", versionGroupLabelUpdate), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "control_library_version", controlLibraryVersionUpdate), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "latest", latestUpdate), + resource.TestCheckResourceAttr("ibm_scc_control_library.scc_control_library_instance", "controls_count", controlsCount), + ), + }, + resource.TestStep{ + ResourceName: "ibm_scc_control_library.scc_control_library_instance", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckIbmSccControlLibraryConfigBasic(controlLibraryName string, controlLibraryDescription string, controlLibraryType string) string { + return fmt.Sprintf(` + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "%s" + control_library_description = "%s" + control_library_type = "%s" + version_group_label = "03354ab4-03be-41c0-a469-826fc0262e78" + latest = true + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + `, controlLibraryName, controlLibraryDescription, controlLibraryType) +} + +func testAccCheckIbmSccControlLibraryConfig(controlLibraryName string, controlLibraryDescription string, controlLibraryType string, versionGroupLabel string, controlLibraryVersion string, latest string) string { + return fmt.Sprintf(` + + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "%s" + control_library_description = "%s" + control_library_type = "%s" + version_group_label = "%s" + control_library_version = "%s" + latest = %s + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + `, controlLibraryName, controlLibraryDescription, controlLibraryType, versionGroupLabel, controlLibraryVersion, latest) +} + +func testAccCheckIbmSccControlLibraryExists(n string, obj securityandcompliancecenterapiv3.ControlLibrary) resource.TestCheckFunc { + + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + securityandcompliancecenterapiClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return err + } + + getControlLibraryOptions := &securityandcompliancecenterapiv3.GetControlLibraryOptions{} + + getControlLibraryOptions.SetControlLibrariesID(rs.Primary.ID) + + controlLibrary, _, err := securityandcompliancecenterapiClient.GetControlLibrary(getControlLibraryOptions) + if err != nil { + return err + } + + obj = *controlLibrary + return nil + } +} + +func testAccCheckIbmSccControlLibraryDestroy(s *terraform.State) error { + securityandcompliancecenterapiClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return err + } + for _, rs := range s.RootModule().Resources { + if rs.Type != "ibm_scc_control_library" { + continue + } + + getControlLibraryOptions := &securityandcompliancecenterapiv3.GetControlLibraryOptions{} + + getControlLibraryOptions.SetControlLibrariesID(rs.Primary.ID) + + // Try to find the key + _, response, err := securityandcompliancecenterapiClient.GetControlLibrary(getControlLibraryOptions) + + if err == nil { + return fmt.Errorf("scc_control_library still exists: %s", rs.Primary.ID) + } else if response.StatusCode != 404 { + return fmt.Errorf("Error checking for scc_control_library (%s) has been destroyed: %s", rs.Primary.ID, err) + } + } + + return nil +} diff --git a/ibm/service/scc/resource_ibm_scc_profile.go b/ibm/service/scc/resource_ibm_scc_profile.go new file mode 100644 index 0000000000..d70e2bf221 --- /dev/null +++ b/ibm/service/scc/resource_ibm_scc_profile.go @@ -0,0 +1,838 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" + "github.com/IBM/go-sdk-core/v5/core" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func ResourceIbmSccProfile() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIbmSccProfileCreate, + ReadContext: resourceIbmSccProfileRead, + UpdateContext: resourceIbmSccProfileUpdate, + DeleteContext: resourceIbmSccProfileDelete, + Importer: &schema.ResourceImporter{}, + + Schema: map[string]*schema.Schema{ + "profile_name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_profile", "profile_name"), + Description: "The profile name.", + }, + "profile_description": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_profile", "profile_description"), + Description: "The profile description.", + }, + "profile_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_profile", "profile_type"), + Description: "The profile type, such as custom or predefined.", + }, + "controls": { + Type: schema.TypeList, + Required: true, + Description: "The array of controls that are used to create the profile.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_library_id": { + Type: schema.TypeString, + Optional: true, + Description: "The ID of the control library that contains the profile.", + }, + "control_id": { + Type: schema.TypeString, + Optional: true, + Description: "The unique ID of the control inside the control library.", + }, + "control_library_version": { + Type: schema.TypeString, + Computed: true, + Description: "The most recent version of the control library.", + }, + "control_name": { + Type: schema.TypeString, + Computed: true, + Description: "The control name.", + }, + "control_description": { + Type: schema.TypeString, + Computed: true, + Description: "The control description.", + }, + "control_category": { + Type: schema.TypeString, + Computed: true, + Description: "The control category.", + }, + "control_parent": { + Type: schema.TypeString, + Computed: true, + Description: "The parent control.", + }, + "control_requirement": { + Type: schema.TypeBool, + Computed: true, + Description: "Is this a control that can be automated or manually evaluated.", + }, + "control_docs": { + Type: schema.TypeList, + Computed: true, + Description: "The control documentation.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_docs_id": { + Type: schema.TypeString, + Optional: true, + Description: "The ID of the control documentation.", + }, + "control_docs_type": { + Type: schema.TypeString, + Optional: true, + Description: "The type of control documentation.", + }, + }, + }, + }, + "control_specifications_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of control specifications.", + }, + "control_specifications": { + Type: schema.TypeList, + Computed: true, + Description: "The control specifications.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "control_specification_id": { + Type: schema.TypeString, + Computed: true, + Description: "The control specification ID.", + }, + "responsibility": { + Type: schema.TypeString, + Computed: true, + Description: "The responsibility for managing the control.", + }, + "component_id": { + Type: schema.TypeString, + Computed: true, + Description: "The component ID.", + }, + "component_name": { + Type: schema.TypeString, + Computed: true, + Description: "The component name.", + }, + "environment": { + Type: schema.TypeString, + Computed: true, + Description: "The control specifications environment.", + }, + "control_specification_description": { + Type: schema.TypeString, + Computed: true, + Description: "The control specifications description.", + }, + "assessments_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of assessments.", + }, + "assessments": { + Type: schema.TypeList, + Computed: true, + Description: "The assessments.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "assessment_id": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment ID.", + }, + "assessment_method": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment method.", + }, + "assessment_type": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment type.", + }, + "assessment_description": { + Type: schema.TypeString, + Computed: true, + Description: "The assessment description.", + }, + "parameter_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The parameter count.", + }, + "parameters": { + Type: schema.TypeList, + Computed: true, + Description: "The parameters.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "parameter_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter name.", + }, + "parameter_display_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter display name.", + }, + "parameter_type": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter type.", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + "default_parameters": { + Type: schema.TypeList, + Optional: true, + Description: "The default parameters of the profile.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "assessment_type": { + Type: schema.TypeString, + Optional: true, + Description: "The type of the implementation.", + }, + "assessment_id": { + Type: schema.TypeString, + Optional: true, + Description: "The implementation ID of the parameter.", + }, + "parameter_name": { + Type: schema.TypeString, + Optional: true, + Description: "The parameter name.", + }, + "parameter_default_value": { + Type: schema.TypeString, + Optional: true, + Description: "The default value of the parameter.", + }, + "parameter_display_name": { + Type: schema.TypeString, + Optional: true, + Description: "The parameter display name.", + }, + "parameter_type": { + Type: schema.TypeString, + Optional: true, + Description: "The parameter type.", + }, + }, + }, + }, + "profile_version": { + Type: schema.TypeString, + Computed: true, + Description: "The version status of the profile.", + }, + "version_group_label": { + Type: schema.TypeString, + Computed: true, + Description: "The version group label of the profile.", + }, + "instance_id": { + Type: schema.TypeString, + Computed: true, + Description: "The instance ID.", + }, + "latest": { + Type: schema.TypeBool, + Computed: true, + Description: "The latest version of the profile.", + }, + "hierarchy_enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "The indication of whether hierarchy is enabled for the profile.", + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who created the profile.", + }, + "created_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the profile was created.", + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who updated the profile.", + }, + "updated_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the profile was updated.", + }, + "controls_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of controls for the profile.", + }, + "control_parents_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of parent controls for the profile.", + }, + "attachments_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of attachments related to this profile.", + }, + }, + } +} + +func ResourceIbmSccProfileValidator() *validate.ResourceValidator { + validateSchema := make([]validate.ValidateSchema, 0) + validateSchema = append(validateSchema, + validate.ValidateSchema{ + Identifier: "profile_name", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^[a-zA-Z0-9_\s\-]*$`, + MinValueLength: 2, + MaxValueLength: 64, + }, + validate.ValidateSchema{ + Identifier: "profile_description", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^[a-zA-Z0-9_,'"\s\-\[\]]+$`, + MinValueLength: 2, + MaxValueLength: 256, + }, + ) + + resourceValidator := validate.ResourceValidator{ResourceName: "ibm_scc_profile", Schema: validateSchema} + return &resourceValidator +} + +func resourceIbmSccProfileCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + log.Print("[DEBUG] Starting resourceIbmSccProfileCreate") + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + bodyModelMap := map[string]interface{}{} + createProfileOptions := &securityandcompliancecenterapiv3.CreateProfileOptions{} + + bodyModelMap["profile_name"] = d.Get("profile_name") + bodyModelMap["profile_description"] = d.Get("profile_description") + bodyModelMap["profile_type"] = "custom" + if _, ok := d.GetOk("controls"); ok { + bodyModelMap["controls"] = d.Get("controls") + } + if _, ok := d.GetOk("default_parameters"); ok { + bodyModelMap["default_parameters"] = d.Get("default_parameters") + } else { + bodyModelMap["default_parameters"] = []interface{}{} + } + convertedModel, err := resourceIbmSccProfileMapToProfilePrototype(bodyModelMap) + if err != nil { + return diag.FromErr(err) + } + createProfileOptions = convertedModel + + profile, response, err := securityandcompliancecenterapiClient.CreateProfileWithContext(context, createProfileOptions) + if err != nil { + log.Printf("[DEBUG] CreateProfileWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("CreateProfileWithContext failed %s\n%s", err, response)) + } + + d.SetId(*profile.ID) + + return resourceIbmSccProfileRead(context, d, meta) +} + +func resourceIbmSccProfileRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + log.Print("[DEBUG] Starting resourceIbmSccProfileRead") + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getProfileOptions := &securityandcompliancecenterapiv3.GetProfileOptions{} + + getProfileOptions.SetProfileID(d.Id()) + + profile, response, err := securityandcompliancecenterapiClient.GetProfileWithContext(context, getProfileOptions) + if err != nil { + if response != nil && response.StatusCode == 404 { + d.SetId("") + return nil + } + log.Printf("[DEBUG] GetProfileWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetProfileWithContext failed %s\n%s", err, response)) + } + + if err = d.Set("profile_name", profile.ProfileName); err != nil { + return diag.FromErr(fmt.Errorf("Error setting profile_name: %s", err)) + } + if err = d.Set("profile_description", profile.ProfileDescription); err != nil { + return diag.FromErr(fmt.Errorf("Error setting profile_description: %s", err)) + } + if err = d.Set("profile_type", profile.ProfileType); err != nil { + return diag.FromErr(fmt.Errorf("Error setting profile_type: %s", err)) + } + controls := []map[string]interface{}{} + for _, controlsItem := range profile.Controls { + controlsItemMap, err := resourceIbmSccProfileProfileControlsToMap(&controlsItem) + if err != nil { + return diag.FromErr(err) + } + controls = append(controls, controlsItemMap) + } + if err = d.Set("controls", controls); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls: %s", err)) + } + if len(profile.DefaultParameters) > 0 { + defaultParameters := []map[string]interface{}{} + for _, defaultParametersItem := range profile.DefaultParameters { + defaultParametersItemMap, err := resourceIbmSccProfileDefaultParametersPrototypeToMap(&defaultParametersItem) + if err != nil { + return diag.FromErr(err) + } + defaultParameters = append(defaultParameters, defaultParametersItemMap) + } + if err = d.Set("default_parameters", defaultParameters); err != nil { + return diag.FromErr(fmt.Errorf("Error setting default_parameters: %s", err)) + } + } + if !core.IsNil(profile.ProfileVersion) { + if err = d.Set("profile_version", profile.ProfileVersion); err != nil { + return diag.FromErr(fmt.Errorf("Error setting profile_version: %s", err)) + } + } + if !core.IsNil(profile.VersionGroupLabel) { + if err = d.Set("version_group_label", profile.VersionGroupLabel); err != nil { + return diag.FromErr(fmt.Errorf("Error setting version_group_label: %s", err)) + } + } + if !core.IsNil(profile.InstanceID) { + if err = d.Set("instance_id", profile.InstanceID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + } + } + if !core.IsNil(profile.Latest) { + if err = d.Set("latest", profile.Latest); err != nil { + return diag.FromErr(fmt.Errorf("Error setting latest: %s", err)) + } + } + if !core.IsNil(profile.HierarchyEnabled) { + if err = d.Set("hierarchy_enabled", profile.HierarchyEnabled); err != nil { + return diag.FromErr(fmt.Errorf("Error setting hierarchy_enabled: %s", err)) + } + } + if !core.IsNil(profile.CreatedBy) { + if err = d.Set("created_by", profile.CreatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + } + } + if !core.IsNil(profile.CreatedOn) { + if err = d.Set("created_on", flex.DateTimeToString(profile.CreatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_on: %s", err)) + } + } + if !core.IsNil(profile.UpdatedBy) { + if err = d.Set("updated_by", profile.UpdatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_by: %s", err)) + } + } + if !core.IsNil(profile.UpdatedOn) { + if err = d.Set("updated_on", flex.DateTimeToString(profile.UpdatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_on: %s", err)) + } + } + if !core.IsNil(profile.ControlsCount) { + if err = d.Set("controls_count", flex.IntValue(profile.ControlsCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting controls_count: %s", err)) + } + } + if !core.IsNil(profile.ControlParentsCount) { + if err = d.Set("control_parents_count", flex.IntValue(profile.ControlParentsCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting control_parents_count: %s", err)) + } + } + if !core.IsNil(profile.AttachmentsCount) { + if err = d.Set("attachments_count", flex.IntValue(profile.AttachmentsCount)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting attachments_count: %s", err)) + } + } + + return nil +} + +func resourceIbmSccProfileUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + replaceProfileOptions := &securityandcompliancecenterapiv3.ReplaceProfileOptions{} + hasChange := false + bodyModelMap := map[string]interface{}{} + + if d.HasChange("controls") { + hasChange = true + } + if d.HasChange("default_parameters") { + hasChange = true + } + if d.HasChange("profile_name") { + hasChange = true + } + if d.HasChange("profile_description") { + hasChange = true + } + + if hasChange { + if _, ok := d.GetOk("controls"); ok { + bodyModelMap["controls"] = d.Get("controls") + } + if _, ok := d.GetOk("default_parameters"); ok { + bodyModelMap["default_parameters"] = d.Get("default_parameters") + } + if _, ok := d.GetOk("profile_name"); ok { + bodyModelMap["profile_name"] = d.Get("profile_name") + } + if _, ok := d.GetOk("profile_description"); ok { + bodyModelMap["profile_description"] = d.Get("profile_description") + } + + convertedModel, err := resourceIbmSccProfileMapToReplaceProfileOptions(bodyModelMap) + if err != nil { + return diag.FromErr(err) + } + + replaceProfileOptions = convertedModel + replaceProfileOptions.SetProfileID(d.Id()) + _, response, err := securityandcompliancecenterapiClient.ReplaceProfileWithContext(context, replaceProfileOptions) + if err != nil { + log.Printf("[DEBUG] ReplaceProfileWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("ReplaceProfileWithContext failed %s\n%s", err, response)) + } + } + + return resourceIbmSccProfileRead(context, d, meta) +} + +func resourceIbmSccProfileDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + deleteCustomProfileOptions := &securityandcompliancecenterapiv3.DeleteCustomProfileOptions{} + + deleteCustomProfileOptions.SetProfileID(d.Id()) + + _, response, err := securityandcompliancecenterapiClient.DeleteCustomProfileWithContext(context, deleteCustomProfileOptions) + if err != nil { + log.Printf("[DEBUG] DeleteCustomProfileWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("DeleteCustomProfileWithContext failed %s\n%s", err, response)) + } + + d.SetId("") + + return nil +} + +func resourceIbmSccProfileMapToProfileControlsPrototype(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.ProfileControlsPrototype, error) { + model := &securityandcompliancecenterapiv3.ProfileControlsPrototype{} + if modelMap["control_library_id"] != nil && modelMap["control_library_id"].(string) != "" { + model.ControlLibraryID = core.StringPtr(modelMap["control_library_id"].(string)) + } + if modelMap["control_id"] != nil && modelMap["control_id"].(string) != "" { + model.ControlID = core.StringPtr(modelMap["control_id"].(string)) + } + return model, nil +} + +func resourceIbmSccProfileMapToDefaultParametersPrototype(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.DefaultParametersPrototype, error) { + model := &securityandcompliancecenterapiv3.DefaultParametersPrototype{} + if modelMap["assessment_type"] != nil && modelMap["assessment_type"].(string) != "" { + model.AssessmentType = core.StringPtr(modelMap["assessment_type"].(string)) + } + if modelMap["assessment_id"] != nil && modelMap["assessment_id"].(string) != "" { + model.AssessmentID = core.StringPtr(modelMap["assessment_id"].(string)) + } + if modelMap["parameter_name"] != nil && modelMap["parameter_name"].(string) != "" { + model.ParameterName = core.StringPtr(modelMap["parameter_name"].(string)) + } + if modelMap["parameter_default_value"] != nil && modelMap["parameter_default_value"].(string) != "" { + model.ParameterDefaultValue = core.StringPtr(modelMap["parameter_default_value"].(string)) + } + if modelMap["parameter_display_name"] != nil && modelMap["parameter_display_name"].(string) != "" { + model.ParameterDisplayName = core.StringPtr(modelMap["parameter_display_name"].(string)) + } + if modelMap["parameter_type"] != nil && modelMap["parameter_type"].(string) != "" { + model.ParameterType = core.StringPtr(modelMap["parameter_type"].(string)) + } + return model, nil +} + +func resourceIbmSccProfileMapToProfilePrototype(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.CreateProfileOptions, error) { + model := &securityandcompliancecenterapiv3.CreateProfileOptions{} + model.ProfileName = core.StringPtr(modelMap["profile_name"].(string)) + model.ProfileDescription = core.StringPtr(modelMap["profile_description"].(string)) + model.ProfileType = core.StringPtr(modelMap["profile_type"].(string)) + controls := []securityandcompliancecenterapiv3.ProfileControlsPrototype{} + for _, controlsItem := range modelMap["controls"].([]interface{}) { + controlsItemModel, err := resourceIbmSccProfileMapToProfileControlsPrototype(controlsItem.(map[string]interface{})) + if err != nil { + return model, err + } + controls = append(controls, *controlsItemModel) + } + model.Controls = controls + defaultParameters := []securityandcompliancecenterapiv3.DefaultParametersPrototype{} + for _, defaultParametersItem := range modelMap["default_parameters"].([]interface{}) { + if defaultParametersItem != nil { + defaultParametersItemModel, err := resourceIbmSccProfileMapToDefaultParametersPrototype(defaultParametersItem.(map[string]interface{})) + if err != nil { + return model, err + } + defaultParameters = append(defaultParameters, *defaultParametersItemModel) + } + } + model.DefaultParameters = defaultParameters + return model, nil +} + +func resourceIbmSccProfileMapToReplaceProfileOptions(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.ReplaceProfileOptions, error) { + model := &securityandcompliancecenterapiv3.ReplaceProfileOptions{} + model.ProfileName = core.StringPtr(modelMap["profile_name"].(string)) + model.ProfileDescription = core.StringPtr(modelMap["profile_description"].(string)) + model.ProfileType = core.StringPtr(modelMap["profile_type"].(string)) + controls := []securityandcompliancecenterapiv3.ProfileControlsPrototype{} + for _, controlsItem := range modelMap["controls"].([]interface{}) { + controlsItemModel, err := resourceIbmSccProfileMapToProfileControlsPrototype(controlsItem.(map[string]interface{})) + if err != nil { + return model, err + } + controls = append(controls, *controlsItemModel) + } + model.Controls = controls + defaultParameters := []securityandcompliancecenterapiv3.DefaultParametersPrototype{} + for _, defaultParametersItem := range modelMap["default_parameters"].([]interface{}) { + if defaultParametersItem != nil { + defaultParametersItemModel, err := resourceIbmSccProfileMapToDefaultParametersPrototype(defaultParametersItem.(map[string]interface{})) + if err != nil { + return model, err + } + defaultParameters = append(defaultParameters, *defaultParametersItemModel) + } + } + model.DefaultParameters = defaultParameters + return model, nil +} + +func resourceIbmSccProfileProfileControlsToMap(model *securityandcompliancecenterapiv3.ProfileControls) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlLibraryID != nil { + modelMap["control_library_id"] = model.ControlLibraryID + } + if model.ControlID != nil { + modelMap["control_id"] = model.ControlID + } + if model.ControlLibraryVersion != nil { + modelMap["control_library_version"] = model.ControlLibraryVersion + } + if model.ControlName != nil { + modelMap["control_name"] = model.ControlName + } + if model.ControlDescription != nil { + modelMap["control_description"] = model.ControlDescription + } + if model.ControlCategory != nil { + modelMap["control_category"] = model.ControlCategory + } + if model.ControlParent != nil { + modelMap["control_parent"] = model.ControlParent + } + if model.ControlRequirement != nil { + modelMap["control_requirement"] = model.ControlRequirement + } + if model.ControlDocs != nil { + controlDocsMap, err := resourceIbmSccProfileControlDocsToMap(model.ControlDocs) + if err != nil { + return modelMap, err + } + modelMap["control_docs"] = []map[string]interface{}{controlDocsMap} + } + if model.ControlSpecificationsCount != nil { + modelMap["control_specifications_count"] = flex.IntValue(model.ControlSpecificationsCount) + } + if model.ControlSpecifications != nil { + controlSpecifications := []map[string]interface{}{} + for _, controlSpecificationsItem := range model.ControlSpecifications { + controlSpecificationsItemMap, err := resourceIbmSccProfileControlSpecificationsToMap(&controlSpecificationsItem) + if err != nil { + return modelMap, err + } + controlSpecifications = append(controlSpecifications, controlSpecificationsItemMap) + } + modelMap["control_specifications"] = controlSpecifications + } + return modelMap, nil +} + +func resourceIbmSccProfileControlDocsToMap(model *securityandcompliancecenterapiv3.ControlDocs) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlDocsID != nil { + modelMap["control_docs_id"] = model.ControlDocsID + } + if model.ControlDocsType != nil { + modelMap["control_docs_type"] = model.ControlDocsType + } + return modelMap, nil +} + +func resourceIbmSccProfileControlSpecificationsToMap(model *securityandcompliancecenterapiv3.ControlSpecifications) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ControlSpecificationID != nil { + modelMap["control_specification_id"] = model.ControlSpecificationID + } + if model.Responsibility != nil { + modelMap["responsibility"] = model.Responsibility + } + if model.ComponentID != nil { + modelMap["component_id"] = model.ComponentID + } + if model.ComponentName != nil { + modelMap["component_name"] = model.ComponentName + } + if model.Environment != nil { + modelMap["environment"] = model.Environment + } + if model.ControlSpecificationDescription != nil { + modelMap["control_specification_description"] = model.ControlSpecificationDescription + } + if model.AssessmentsCount != nil { + modelMap["assessments_count"] = flex.IntValue(model.AssessmentsCount) + } + if model.Assessments != nil { + assessments := []map[string]interface{}{} + for _, assessmentsItem := range model.Assessments { + assessmentsItemMap, err := resourceIbmSccProfileImplementationToMap(&assessmentsItem) + if err != nil { + return modelMap, err + } + assessments = append(assessments, assessmentsItemMap) + } + modelMap["assessments"] = assessments + } + return modelMap, nil +} + +func resourceIbmSccProfileImplementationToMap(model *securityandcompliancecenterapiv3.Implementation) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AssessmentID != nil { + modelMap["assessment_id"] = model.AssessmentID + } + if model.AssessmentMethod != nil { + modelMap["assessment_method"] = model.AssessmentMethod + } + if model.AssessmentType != nil { + modelMap["assessment_type"] = model.AssessmentType + } + if model.AssessmentDescription != nil { + modelMap["assessment_description"] = model.AssessmentDescription + } + if model.ParameterCount != nil { + modelMap["parameter_count"] = flex.IntValue(model.ParameterCount) + } + if model.Parameters != nil { + parameters := []map[string]interface{}{} + for _, parametersItem := range model.Parameters { + parametersItemMap, err := resourceIbmSccProfileParameterInfoToMap(¶metersItem) + if err != nil { + return modelMap, err + } + parameters = append(parameters, parametersItemMap) + } + modelMap["parameters"] = parameters + } + return modelMap, nil +} + +func resourceIbmSccProfileParameterInfoToMap(model *securityandcompliancecenterapiv3.ParameterInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ParameterName != nil { + modelMap["parameter_name"] = model.ParameterName + } + if model.ParameterDisplayName != nil { + modelMap["parameter_display_name"] = model.ParameterDisplayName + } + if model.ParameterType != nil { + modelMap["parameter_type"] = model.ParameterType + } + return modelMap, nil +} + +func resourceIbmSccProfileDefaultParametersPrototypeToMap(model *securityandcompliancecenterapiv3.DefaultParametersPrototype) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AssessmentType != nil { + modelMap["assessment_type"] = model.AssessmentType + } + if model.AssessmentID != nil { + modelMap["assessment_id"] = model.AssessmentID + } + if model.ParameterName != nil { + modelMap["parameter_name"] = model.ParameterName + } + if model.ParameterDefaultValue != nil { + modelMap["parameter_default_value"] = model.ParameterDefaultValue + } + if model.ParameterDisplayName != nil { + modelMap["parameter_display_name"] = model.ParameterDisplayName + } + if model.ParameterType != nil { + modelMap["parameter_type"] = model.ParameterType + } + return modelMap, nil +} diff --git a/ibm/service/scc/resource_ibm_scc_profile_attachment.go b/ibm/service/scc/resource_ibm_scc_profile_attachment.go new file mode 100644 index 0000000000..456bc1fd40 --- /dev/null +++ b/ibm/service/scc/resource_ibm_scc_profile_attachment.go @@ -0,0 +1,905 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" + "github.com/IBM/go-sdk-core/v5/core" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func ResourceIbmSccProfileAttachment() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIbmSccProfileAttachmentCreate, + ReadContext: resourceIbmSccProfileAttachmentRead, + UpdateContext: resourceIbmSccProfileAttachmentUpdate, + DeleteContext: resourceIbmSccProfileAttachmentDelete, + Importer: &schema.ResourceImporter{}, + + Schema: map[string]*schema.Schema{ + "profile_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_profile_attachment", "profile_id"), + Description: "The ID of the profile that is specified in the attachment.", + }, + "account_id": { + Type: schema.TypeString, + Computed: true, + Description: "The account ID that is associated to the attachment.", + }, + "instance_id": { + Type: schema.TypeString, + Computed: true, + Description: "The instance ID of the account that is associated to the attachment.", + }, + "scope": { + Type: schema.TypeList, + Required: true, + Description: "The scope payload for the multi cloud feature.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "environment": { + Type: schema.TypeString, + Required: true, + Description: "The environment that relates to this scope.", + }, + "properties": { + Type: schema.TypeList, + Required: true, + Description: "The properties supported for scoping by this environment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "The name of the property.", + }, + "value": { + Type: schema.TypeString, + Optional: true, + Description: "The value of the property.", + }, + }, + }, + }, + }, + }, + }, + "created_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the attachment was created.", + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who created the attachment.", + }, + "updated_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the attachment was updated.", + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who updated the attachment.", + }, + "status": { + Type: schema.TypeString, + Required: true, + Description: "The status of an attachment evaluation.", + }, + "schedule": { + Type: schema.TypeString, + Required: true, + Description: "The schedule of an attachment evaluation.", + }, + "notifications": { + Type: schema.TypeList, + Required: true, + Description: "The request payload of the attachment notifications.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Optional: true, + Description: "enabled notifications.", + DefaultFunc: func() (any, error) { + return false, nil + }, + }, + "controls": { + Type: schema.TypeList, + MinItems: 1, + MaxItems: 1, + Optional: true, + Description: "The failed controls.", + DefaultFunc: func() (any, error) { + return []map[string]interface{}{ + { + "threshold_limit": 15, + "failed_control_ids": []string{}, + }, + }, nil + }, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "threshold_limit": { + Type: schema.TypeInt, + Optional: true, + Description: "The threshold limit.", + DefaultFunc: func() (any, error) { + return 15, nil + }, + }, + "failed_control_ids": { + Type: schema.TypeList, + Optional: true, + Description: "The failed control IDs.", + Elem: &schema.Schema{Type: schema.TypeString}, + DefaultFunc: func() (any, error) { + return []string{}, nil + }, + }, + }, + }, + }, + }, + }, + }, + "attachment_parameters": { + Type: schema.TypeList, + Optional: true, + Description: "The profile parameters for the attachment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "assessment_type": { + Type: schema.TypeString, + Optional: true, + Description: "The type of the implementation.", + }, + "assessment_id": { + Type: schema.TypeString, + Optional: true, + Description: "The implementation ID of the parameter.", + }, + "parameter_name": { + Type: schema.TypeString, + Optional: true, + Description: "The parameter name.", + }, + "parameter_value": { + Type: schema.TypeString, + Optional: true, + Description: "The value of the parameter.", + }, + "parameter_display_name": { + Type: schema.TypeString, + Optional: true, + Description: "The parameter display name.", + }, + "parameter_type": { + Type: schema.TypeString, + Optional: true, + Description: "The parameter type.", + }, + }, + }, + }, + "last_scan": { + Type: schema.TypeList, + Computed: true, + Description: "The details of the last scan of an attachment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Optional: true, + Description: "The ID of the last scan of an attachment.", + }, + "status": { + Type: schema.TypeString, + Optional: true, + Description: "The status of the last scan of an attachment.", + }, + "time": { + Type: schema.TypeString, + Optional: true, + Description: "The time when the last scan started.", + }, + }, + }, + }, + "next_scan_time": { + Type: schema.TypeString, + Computed: true, + Description: "The start time of the next scan.", + }, + "name": { + Type: schema.TypeString, + Required: true, + Description: "The name of the attachment.", + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: "The description for the attachment.", + }, + "attachment_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of the attachment.", + }, + }, + } +} + +func ResourceIbmSccProfileAttachmentValidator() *validate.ResourceValidator { + validateSchema := make([]validate.ValidateSchema, 0) + validateSchema = append(validateSchema, + validate.ValidateSchema{ + Identifier: "profile_id", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`, + MinValueLength: 36, + MaxValueLength: 36, + }, + ) + + resourceValidator := validate.ResourceValidator{ResourceName: "ibm_scc_profile_attachment", Schema: validateSchema} + return &resourceValidator +} + +func resourceIbmSccProfileAttachmentCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + bodyModelMap := map[string]interface{}{} + createAttachmentOptions := &securityandcompliancecenterapiv3.CreateAttachmentOptions{} + + if _, ok := d.GetOk("profile_id"); ok { + bodyModelMap["profile_id"] = d.Get("profile_id") + } + if _, ok := d.GetOk("description"); ok { + bodyModelMap["description"] = d.Get("description") + } + if _, ok := d.GetOk("scope"); ok { + bodyModelMap["scope"] = d.Get("scope") + } + // manual chang + if _, ok := d.GetOk("attachment_parameters"); ok { + bodyModelMap["attachment_parameters"] = d.Get("attachment_parameters") + } else { + bodyModelMap["attachment_parameters"] = []interface{}{} + } + if _, ok := d.GetOk("notifications"); ok { + bodyModelMap["notifications"] = d.Get("notifications") + } + // end manual change + if _, ok := d.GetOk("status"); ok { + bodyModelMap["status"] = d.Get("status") + } + if _, ok := d.GetOk("schedule"); ok { + bodyModelMap["schedule"] = d.Get("schedule") + } + if _, ok := d.GetOk("name"); ok { + bodyModelMap["name"] = d.Get("name") + } + convertedModel, err := resourceIbmSccProfileAttachmentMapToAttachmentPrototype(bodyModelMap) + if err != nil { + return diag.FromErr(err) + } + createAttachmentOptions = convertedModel + + attachmentPrototype, response, err := securityandcompliancecenterapiClient.CreateAttachmentWithContext(context, createAttachmentOptions) + if err != nil { + log.Printf("[DEBUG] CreateAttachmentWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("CreateAttachmentWithContext failed %s\n%s", err, response)) + } + + d.SetId(fmt.Sprintf("%s/%s", *createAttachmentOptions.ProfileID, *attachmentPrototype.Attachments[0].ID)) + + return resourceIbmSccProfileAttachmentRead(context, d, meta) +} + +func resourceIbmSccProfileAttachmentRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getProfileAttachmentOptions := &securityandcompliancecenterapiv3.GetProfileAttachmentOptions{} + + parts, err := flex.SepIdParts(d.Id(), "/") + if err != nil { + return diag.FromErr(err) + } + + getProfileAttachmentOptions.SetProfileID(parts[0]) + getProfileAttachmentOptions.SetAttachmentID(parts[1]) + + attachmentItem, response, err := securityandcompliancecenterapiClient.GetProfileAttachmentWithContext(context, getProfileAttachmentOptions) + if err != nil { + if response != nil && response.StatusCode == 404 { + d.SetId("") + return nil + } + log.Printf("[DEBUG] GetProfileAttachmentWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetProfileAttachmentWithContext failed %s\n%s", err, response)) + } + + if !core.IsNil(attachmentItem.ProfileID) { + if err = d.Set("profile_id", attachmentItem.ProfileID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting profile_id: %s", err)) + } + } + if !core.IsNil(attachmentItem.AccountID) { + if err = d.Set("account_id", attachmentItem.AccountID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) + } + } + if !core.IsNil(attachmentItem.InstanceID) { + if err = d.Set("instance_id", attachmentItem.InstanceID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + } + } + if !core.IsNil(attachmentItem.Scope) { + scope := []map[string]interface{}{} + for _, scopeItem := range attachmentItem.Scope { + scopeItemMap, err := resourceIbmSccProfileAttachmentMultiCloudScopeToMap(&scopeItem) + if err != nil { + return diag.FromErr(err) + } + scope = append(scope, scopeItemMap) + } + if err = d.Set("scope", scope); err != nil { + return diag.FromErr(fmt.Errorf("Error setting scope: %s", err)) + } + } + if !core.IsNil(attachmentItem.CreatedOn) { + if err = d.Set("created_on", flex.DateTimeToString(attachmentItem.CreatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_on: %s", err)) + } + } + if !core.IsNil(attachmentItem.CreatedBy) { + if err = d.Set("created_by", attachmentItem.CreatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + } + } + if !core.IsNil(attachmentItem.UpdatedOn) { + if err = d.Set("updated_on", flex.DateTimeToString(attachmentItem.UpdatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_on: %s", err)) + } + } + if !core.IsNil(attachmentItem.UpdatedBy) { + if err = d.Set("updated_by", attachmentItem.UpdatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_by: %s", err)) + } + } + if !core.IsNil(attachmentItem.Status) { + if err = d.Set("status", attachmentItem.Status); err != nil { + return diag.FromErr(fmt.Errorf("Error setting status: %s", err)) + } + } + if !core.IsNil(attachmentItem.Schedule) { + if err = d.Set("schedule", attachmentItem.Schedule); err != nil { + return diag.FromErr(fmt.Errorf("Error setting schedule: %s", err)) + } + } + if !core.IsNil(attachmentItem.Notifications) { + notificationsMap, err := resourceIbmSccProfileAttachmentAttachmentsNotificationsPrototypeToMap(attachmentItem.Notifications) + if err != nil { + return diag.FromErr(err) + } + if err = d.Set("notifications", []map[string]interface{}{notificationsMap}); err != nil { + return diag.FromErr(fmt.Errorf("Error setting notifications: %s", err)) + } + } + if !core.IsNil(attachmentItem.AttachmentParameters) { + attachmentParameters := []map[string]interface{}{} + for _, attachmentParametersItem := range attachmentItem.AttachmentParameters { + attachmentParametersItemMap, err := resourceIbmSccProfileAttachmentAttachmentParameterPrototypeToMap(&attachmentParametersItem) + if err != nil { + return diag.FromErr(err) + } + attachmentParameters = append(attachmentParameters, attachmentParametersItemMap) + } + if err = d.Set("attachment_parameters", attachmentParameters); err != nil { + return diag.FromErr(fmt.Errorf("Error setting attachment_parameters: %s", err)) + } + } + if !core.IsNil(attachmentItem.LastScan) { + lastScanMap, err := resourceIbmSccProfileAttachmentLastScanToMap(attachmentItem.LastScan) + if err != nil { + return diag.FromErr(err) + } + if err = d.Set("last_scan", []map[string]interface{}{lastScanMap}); err != nil { + return diag.FromErr(fmt.Errorf("Error setting last_scan: %s", err)) + } + } + if !core.IsNil(attachmentItem.NextScanTime) { + if err = d.Set("next_scan_time", flex.DateTimeToString(attachmentItem.NextScanTime)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting next_scan_time: %s", err)) + } + } + if !core.IsNil(attachmentItem.Name) { + if err = d.Set("name", attachmentItem.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } + if !core.IsNil(attachmentItem.Description) { + if err = d.Set("description", attachmentItem.Description); err != nil { + return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + } + } + if !core.IsNil(attachmentItem.ID) { + if err = d.Set("attachment_id", attachmentItem.ID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting attachment_id: %s", err)) + } + } + + return nil +} + +func resourceIbmSccProfileAttachmentUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + replaceProfileAttachmentOptions := &securityandcompliancecenterapiv3.ReplaceProfileAttachmentOptions{} + + parts, err := flex.SepIdParts(d.Id(), "/") + if err != nil { + return diag.FromErr(err) + } + + replaceProfileAttachmentOptions.SetProfileID(parts[0]) + replaceProfileAttachmentOptions.SetAttachmentID(parts[1]) + + hasChange := false + + if d.HasChange("profile_id") { + return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ + " The resource must be re-created to update this property.", "profile_id")) + } + + if d.HasChange("schedule") { + replaceProfileAttachmentOptions.SetSchedule(d.Get("schedule").(string)) + hasChange = true + } + + if d.HasChange("name") { + replaceProfileAttachmentOptions.SetName(d.Get("name").(string)) + hasChange = true + } + + if d.HasChange("description") { + replaceProfileAttachmentOptions.SetDescription(d.Get("description").(string)) + hasChange = true + } + + if d.HasChange("attachment_item") { + attachmentItem, err := resourceIbmSccProfileAttachmentMapToAttachmentItem(d.Get("attachment_item.0").(map[string]interface{})) + if err != nil { + return diag.FromErr(err) + } + replaceProfileAttachmentOptions.SetAttachmentID(*attachmentItem.ID) + hasChange = true + } + + if d.HasChange("notifications") { + notificationsItem := d.Get("notifications.0").(map[string]interface{}) + updateNotifications, err := resourceIbmSccProfileAttachmentMapToAttachmentsNotificationsPrototype(notificationsItem) + if err != nil { + return diag.FromErr(err) + } + replaceProfileAttachmentOptions.SetNotifications(updateNotifications) + hasChange = true + } + + if hasChange { + if replaceProfileAttachmentOptions.Name == nil { + replaceProfileAttachmentOptions.SetName(d.Get("name").(string)) + } + if replaceProfileAttachmentOptions.Schedule == nil { + replaceProfileAttachmentOptions.SetSchedule(d.Get("schedule").(string)) + } + if replaceProfileAttachmentOptions.Notifications == nil { + notificationsItem := d.Get("notifications.0").(map[string]interface{}) + updateNotifications, err := resourceIbmSccProfileAttachmentMapToAttachmentsNotificationsPrototype(notificationsItem) + if err != nil { + return diag.FromErr(err) + } + replaceProfileAttachmentOptions.SetNotifications(updateNotifications) + } + if len(replaceProfileAttachmentOptions.Scope) == 0 { + scope := []securityandcompliancecenterapiv3.MultiCloudScope{} + for _, scopeItem := range d.Get("scope").([]interface{}) { + scopeItemModel, err := resourceIbmSccProfileAttachmentMapToMultiCloudScope(scopeItem.(map[string]interface{})) + if err != nil { + return diag.FromErr(err) + } + scope = append(scope, *scopeItemModel) + } + replaceProfileAttachmentOptions.SetScope(scope) + } + _, response, err := securityandcompliancecenterapiClient.ReplaceProfileAttachmentWithContext(context, replaceProfileAttachmentOptions) + if err != nil { + log.Printf("[DEBUG] ReplaceProfileAttachmentWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("ReplaceProfileAttachmentWithContext failed %s\n%s", err, response)) + } + } + + return resourceIbmSccProfileAttachmentRead(context, d, meta) +} + +func resourceIbmSccProfileAttachmentDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityandcompliancecenterapiClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + deleteProfileAttachmentOptions := &securityandcompliancecenterapiv3.DeleteProfileAttachmentOptions{} + + parts, err := flex.SepIdParts(d.Id(), "/") + if err != nil { + return diag.FromErr(err) + } + + deleteProfileAttachmentOptions.SetProfileID(parts[0]) + deleteProfileAttachmentOptions.SetAttachmentID(parts[1]) + + _, response, err := securityandcompliancecenterapiClient.DeleteProfileAttachmentWithContext(context, deleteProfileAttachmentOptions) + if err != nil { + log.Printf("[DEBUG] DeleteProfileAttachmentWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("DeleteProfileAttachmentWithContext failed %s\n%s", err, response)) + } + + d.SetId("") + + return nil +} + +func resourceIbmSccProfileAttachmentMapToAttachmentsPrototype(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.AttachmentsPrototype, error) { + model := &securityandcompliancecenterapiv3.AttachmentsPrototype{} + if modelMap["id"] != nil && modelMap["id"].(string) != "" { + model.ID = core.StringPtr(modelMap["id"].(string)) + } + model.Name = core.StringPtr(modelMap["name"].(string)) + if modelMap["description"] != nil && modelMap["description"].(string) != "" { + model.Description = core.StringPtr(modelMap["description"].(string)) + } + scope := []securityandcompliancecenterapiv3.MultiCloudScope{} + for _, scopeItem := range modelMap["scope"].([]interface{}) { + scopeItemModel, err := resourceIbmSccProfileAttachmentMapToMultiCloudScope(scopeItem.(map[string]interface{})) + if err != nil { + return model, err + } + scope = append(scope, *scopeItemModel) + } + model.Scope = scope + model.Status = core.StringPtr(modelMap["status"].(string)) + model.Schedule = core.StringPtr(modelMap["schedule"].(string)) + if modelMap["notifications"] != nil && len(modelMap["notifications"].([]interface{})) > 0 { + NotificationsModel, err := resourceIbmSccProfileAttachmentMapToAttachmentsNotificationsPrototype(modelMap["notifications"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.Notifications = NotificationsModel + } + attachmentParameters := []securityandcompliancecenterapiv3.AttachmentParameterPrototype{} + for _, attachmentParametersItem := range modelMap["attachment_parameters"].([]interface{}) { + if attachmentParametersItem != nil { + attachmentParametersItemModel, err := resourceIbmSccProfileAttachmentMapToAttachmentParameterPrototype(attachmentParametersItem.(map[string]interface{})) + if err != nil { + return model, err + } + attachmentParameters = append(attachmentParameters, *attachmentParametersItemModel) + } + } + model.AttachmentParameters = attachmentParameters + return model, nil +} + +func resourceIbmSccProfileAttachmentMapToMultiCloudScope(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.MultiCloudScope, error) { + model := &securityandcompliancecenterapiv3.MultiCloudScope{} + model.Environment = core.StringPtr(modelMap["environment"].(string)) + properties := []securityandcompliancecenterapiv3.PropertyItem{} + for _, propertiesItem := range modelMap["properties"].([]interface{}) { + propertiesItemModel, err := resourceIbmSccProfileAttachmentMapToPropertyItem(propertiesItem.(map[string]interface{})) + if err != nil { + return model, err + } + properties = append(properties, *propertiesItemModel) + } + model.Properties = properties + return model, nil +} + +func resourceIbmSccProfileAttachmentMapToPropertyItem(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.PropertyItem, error) { + model := &securityandcompliancecenterapiv3.PropertyItem{} + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) + } + if modelMap["value"] != nil && modelMap["value"].(string) != "" { + model.Value = core.StringPtr(modelMap["value"].(string)) + } + return model, nil +} + +func resourceIbmSccProfileAttachmentMapToAttachmentsNotificationsPrototype(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.AttachmentsNotificationsPrototype, error) { + model := &securityandcompliancecenterapiv3.AttachmentsNotificationsPrototype{} + model.Enabled = core.BoolPtr(modelMap["enabled"].(bool)) + ControlsModel, err := resourceIbmSccProfileAttachmentMapToFailedControls(modelMap["controls"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.Controls = ControlsModel + return model, nil +} + +func resourceIbmSccProfileAttachmentMapToFailedControls(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.FailedControls, error) { + model := &securityandcompliancecenterapiv3.FailedControls{} + if modelMap["threshold_limit"] != nil { + model.ThresholdLimit = core.Int64Ptr(int64(modelMap["threshold_limit"].(int))) + } + if modelMap["failed_control_ids"] != nil { + failedControlIds := []string{} + for _, failedControlIdsItem := range modelMap["failed_control_ids"].([]interface{}) { + failedControlIds = append(failedControlIds, failedControlIdsItem.(string)) + } + model.FailedControlIds = failedControlIds + } + return model, nil +} + +func resourceIbmSccProfileAttachmentMapToAttachmentParameterPrototype(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.AttachmentParameterPrototype, error) { + model := &securityandcompliancecenterapiv3.AttachmentParameterPrototype{} + if modelMap["assessment_type"] != nil && modelMap["assessment_type"].(string) != "" { + model.AssessmentType = core.StringPtr(modelMap["assessment_type"].(string)) + } + if modelMap["assessment_id"] != nil && modelMap["assessment_id"].(string) != "" { + model.AssessmentID = core.StringPtr(modelMap["assessment_id"].(string)) + } + if modelMap["parameter_name"] != nil && modelMap["parameter_name"].(string) != "" { + model.ParameterName = core.StringPtr(modelMap["parameter_name"].(string)) + } + if modelMap["parameter_value"] != nil && modelMap["parameter_value"].(string) != "" { + model.ParameterValue = core.StringPtr(modelMap["parameter_value"].(string)) + } + if modelMap["parameter_display_name"] != nil && modelMap["parameter_display_name"].(string) != "" { + model.ParameterDisplayName = core.StringPtr(modelMap["parameter_display_name"].(string)) + } + if modelMap["parameter_type"] != nil && modelMap["parameter_type"].(string) != "" { + model.ParameterType = core.StringPtr(modelMap["parameter_type"].(string)) + } + return model, nil +} + +func resourceIbmSccProfileAttachmentMapToAttachmentItem(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.AttachmentItem, error) { + model := &securityandcompliancecenterapiv3.AttachmentItem{} + if modelMap["id"] != nil && modelMap["id"].(string) != "" { + model.ID = core.StringPtr(modelMap["id"].(string)) + } + if modelMap["profile_id"] != nil && modelMap["profile_id"].(string) != "" { + model.ProfileID = core.StringPtr(modelMap["profile_id"].(string)) + } + if modelMap["account_id"] != nil && modelMap["account_id"].(string) != "" { + model.AccountID = core.StringPtr(modelMap["account_id"].(string)) + } + if modelMap["instance_id"] != nil && modelMap["instance_id"].(string) != "" { + model.InstanceID = core.StringPtr(modelMap["instance_id"].(string)) + } + if modelMap["scope"] != nil { + scope := []securityandcompliancecenterapiv3.MultiCloudScope{} + for _, scopeItem := range modelMap["scope"].([]interface{}) { + scopeItemModel, err := resourceIbmSccProfileAttachmentMapToMultiCloudScope(scopeItem.(map[string]interface{})) + if err != nil { + return model, err + } + scope = append(scope, *scopeItemModel) + } + model.Scope = scope + } + if modelMap["created_on"] != nil { + dateTime, err := core.ParseDateTime(modelMap["created_on"].(string)) + if err != nil { + return model, err + } + model.CreatedOn = &dateTime + } + if modelMap["created_by"] != nil && modelMap["created_by"].(string) != "" { + model.CreatedBy = core.StringPtr(modelMap["created_by"].(string)) + } + if modelMap["updated_on"] != nil { + dateTime, err := core.ParseDateTime(modelMap["updated_on"].(string)) + if err != nil { + return model, err + } + model.UpdatedOn = &dateTime + } + if modelMap["updated_by"] != nil && modelMap["updated_by"].(string) != "" { + model.UpdatedBy = core.StringPtr(modelMap["updated_by"].(string)) + } + if modelMap["status"] != nil && modelMap["status"].(string) != "" { + model.Status = core.StringPtr(modelMap["status"].(string)) + } + if modelMap["schedule"] != nil && modelMap["schedule"].(string) != "" { + model.Schedule = core.StringPtr(modelMap["schedule"].(string)) + } + if modelMap["notifications"] != nil && len(modelMap["notifications"].([]interface{})) > 0 { + NotificationsModel, err := resourceIbmSccProfileAttachmentMapToAttachmentsNotificationsPrototype(modelMap["notifications"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.Notifications = NotificationsModel + } + if modelMap["attachment_parameters"] != nil { + attachmentParameters := []securityandcompliancecenterapiv3.AttachmentParameterPrototype{} + for _, attachmentParametersItem := range modelMap["attachment_parameters"].([]interface{}) { + attachmentParametersItemModel, err := resourceIbmSccProfileAttachmentMapToAttachmentParameterPrototype(attachmentParametersItem.(map[string]interface{})) + if err != nil { + return model, err + } + attachmentParameters = append(attachmentParameters, *attachmentParametersItemModel) + } + model.AttachmentParameters = attachmentParameters + } + if modelMap["last_scan"] != nil && len(modelMap["last_scan"].([]interface{})) > 0 { + LastScanModel, err := resourceIbmSccProfileAttachmentMapToLastScan(modelMap["last_scan"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.LastScan = LastScanModel + } + if modelMap["next_scan_time"] != nil { + dateTime, err := core.ParseDateTime(modelMap["next_scan_time"].(string)) + if err != nil { + return model, err + } + model.NextScanTime = &dateTime + } + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) + } + if modelMap["description"] != nil && modelMap["description"].(string) != "" { + model.Description = core.StringPtr(modelMap["description"].(string)) + } + return model, nil +} + +func resourceIbmSccProfileAttachmentMapToLastScan(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.LastScan, error) { + model := &securityandcompliancecenterapiv3.LastScan{} + if modelMap["id"] != nil && modelMap["id"].(string) != "" { + model.ID = core.StringPtr(modelMap["id"].(string)) + } + if modelMap["status"] != nil && modelMap["status"].(string) != "" { + model.Status = core.StringPtr(modelMap["status"].(string)) + } + if modelMap["time"] != nil { + dateTime, err := core.ParseDateTime(modelMap["time"].(string)) + if err != nil { + return model, err + } + model.Time = &dateTime + } + return model, nil +} + +func resourceIbmSccProfileAttachmentMapToAttachmentPrototype(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.CreateAttachmentOptions, error) { + model := &securityandcompliancecenterapiv3.CreateAttachmentOptions{} + if modelMap["profile_id"] != nil && modelMap["profile_id"].(string) != "" { + model.ProfileID = core.StringPtr(modelMap["profile_id"].(string)) + } + attachments := []securityandcompliancecenterapiv3.AttachmentsPrototype{} + attachmentsItemModel, err := resourceIbmSccProfileAttachmentMapToAttachmentsPrototype(modelMap) + if err != nil { + return model, err + } + attachments = append(attachments, *attachmentsItemModel) + model.Attachments = attachments + return model, nil +} + +func resourceIbmSccProfileAttachmentMultiCloudScopeToMap(model *securityandcompliancecenterapiv3.MultiCloudScope) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["environment"] = model.Environment + properties := []map[string]interface{}{} + for _, propertiesItem := range model.Properties { + propertiesItemMap, err := resourceIbmSccProfileAttachmentPropertyItemToMap(&propertiesItem) + if err != nil { + return modelMap, err + } + properties = append(properties, propertiesItemMap) + } + modelMap["properties"] = properties + return modelMap, nil +} + +func resourceIbmSccProfileAttachmentPropertyItemToMap(model *securityandcompliancecenterapiv3.PropertyItem) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Value != nil { + modelMap["value"] = model.Value + } + return modelMap, nil +} + +func resourceIbmSccProfileAttachmentAttachmentsNotificationsPrototypeToMap(model *securityandcompliancecenterapiv3.AttachmentsNotificationsPrototype) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["enabled"] = model.Enabled + controlsMap, err := resourceIbmSccProfileAttachmentFailedControlsToMap(model.Controls) + if err != nil { + return modelMap, err + } + modelMap["controls"] = []map[string]interface{}{controlsMap} + return modelMap, nil +} + +func resourceIbmSccProfileAttachmentFailedControlsToMap(model *securityandcompliancecenterapiv3.FailedControls) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ThresholdLimit != nil { + modelMap["threshold_limit"] = flex.IntValue(model.ThresholdLimit) + } + if model.FailedControlIds != nil { + modelMap["failed_control_ids"] = model.FailedControlIds + } + return modelMap, nil +} + +func resourceIbmSccProfileAttachmentAttachmentParameterPrototypeToMap(model *securityandcompliancecenterapiv3.AttachmentParameterPrototype) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AssessmentType != nil { + modelMap["assessment_type"] = model.AssessmentType + } + if model.AssessmentID != nil { + modelMap["assessment_id"] = model.AssessmentID + } + if model.ParameterName != nil { + modelMap["parameter_name"] = model.ParameterName + } + if model.ParameterValue != nil { + modelMap["parameter_value"] = model.ParameterValue + } + if model.ParameterDisplayName != nil { + modelMap["parameter_display_name"] = model.ParameterDisplayName + } + if model.ParameterType != nil { + modelMap["parameter_type"] = model.ParameterType + } + return modelMap, nil +} + +func resourceIbmSccProfileAttachmentLastScanToMap(model *securityandcompliancecenterapiv3.LastScan) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = model.ID + } + if model.Status != nil { + modelMap["status"] = model.Status + } + if model.Time != nil { + modelMap["time"] = model.Time.String() + } + return modelMap, nil +} diff --git a/ibm/service/scc/resource_ibm_scc_profile_attachment_test.go b/ibm/service/scc/resource_ibm_scc_profile_attachment_test.go new file mode 100644 index 0000000000..3d751f1f12 --- /dev/null +++ b/ibm/service/scc/resource_ibm_scc_profile_attachment_test.go @@ -0,0 +1,293 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func TestAccIbmSccProfileAttachmentBasic(t *testing.T) { + var conf securityandcompliancecenterapiv3.AttachmentItem + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmSccProfileAttachmentDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccProfileAttachmentConfigBasic(), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmSccProfileAttachmentExists("ibm_scc_profile_attachment.scc_profile_attachment_instance", conf), + ), + }, + }, + }) +} + +func TestAccIbmSccProfileAttachmentAllArgs(t *testing.T) { + var conf securityandcompliancecenterapiv3.AttachmentItem + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmSccProfileAttachmentDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccProfileAttachmentConfig(), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmSccProfileAttachmentExists("ibm_scc_profile_attachment.scc_profile_attachment_instance", conf), + ), + }, + resource.TestStep{ + Config: testAccCheckIbmSccProfileAttachmentConfig(), + Check: resource.ComposeAggregateTestCheckFunc(), + }, + resource.TestStep{ + ResourceName: "ibm_scc_profile_attachment.scc_profile_attachment_instance", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckIbmSccProfileAttachmentConfigBasic() string { + return fmt.Sprintf(` + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "control_library_name" + control_library_description = "control_library_description" + control_library_type = "custom" + version_group_label = "03354ab4-03be-41c0-a469-826fc0262e78" + latest = true + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + + resource "ibm_scc_profile" "scc_profile_instance" { + profile_name = "profile_name" + profile_description = "profile_description" + profile_type = "custom" + controls { + control_library_id = resource.ibm_scc_control_library.scc_control_library_instance.id + control_id = resource.ibm_scc_control_library.scc_control_library_instance.controls[0].control_id + } + default_parameters { + } + } + + resource "ibm_scc_profile_attachment" "scc_profile_attachment_instance" { + profile_id = ibm_scc_profile.scc_profile_instance.id + name = "profile_attachment_name" + description = "scc_profile_attachment_description" + scope { + environment = "ibm-cloud" + properties { + name = "scope_id" + value = resource.ibm_scc_control_library.scc_control_library_instance.account_id + } + properties { + name = "scope_type" + value = "account" + } + } + schedule = "every_30_days" + status = "enabled" + notifications { + enabled = false + controls { + failed_control_ids = [] + threshold_limit = 14 + } + } + } + `) +} + +func testAccCheckIbmSccProfileAttachmentConfig() string { + return fmt.Sprint(` + + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "control_library_name" + control_library_description = "control_library_description" + control_library_type = "custom" + version_group_label = "03354ab4-03be-41c0-a469-826fc0262e78" + latest = true + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + + resource "ibm_scc_profile" "scc_profile_instance" { + profile_name = "profile_name" + profile_description = "profile_description" + profile_type = "custom" + controls { + control_library_id = resource.ibm_scc_control_library.scc_control_library_instance.id + control_id = resource.ibm_scc_control_library.scc_control_library_instance.controls[0].control_id + } + default_parameters { + } + } + + resource "ibm_scc_profile_attachment" "scc_profile_attachment_instance" { + profile_id = ibm_scc_profile.scc_profile_instance.id + name = "profile_attachment_name" + description = "scc_profile_attachment_description" + scope { + environment = "ibm-cloud" + properties { + name = "scope_id" + value = resource.ibm_scc_control_library.scc_control_library_instance.account_id + } + properties { + name = "scope_type" + value = "account" + } + } + schedule = "every_30_days" + status = "enabled" + notifications { + enabled = false + controls { + failed_control_ids = [] + threshold_limit = 14 + } + } + } + `) +} + +func testAccCheckIbmSccProfileAttachmentExists(n string, obj securityandcompliancecenterapiv3.AttachmentItem) resource.TestCheckFunc { + + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + securityandcompliancecenterapiClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return err + } + + getProfileAttachmentOptions := &securityandcompliancecenterapiv3.GetProfileAttachmentOptions{} + + parts, err := flex.SepIdParts(rs.Primary.ID, "/") + if err != nil { + return err + } + + getProfileAttachmentOptions.SetProfileID(parts[0]) + getProfileAttachmentOptions.SetAttachmentID(parts[1]) + + attachmentItem, _, err := securityandcompliancecenterapiClient.GetProfileAttachment(getProfileAttachmentOptions) + if err != nil { + return err + } + + obj = *attachmentItem + return nil + } +} + +func testAccCheckIbmSccProfileAttachmentDestroy(s *terraform.State) error { + securityandcompliancecenterapiClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return err + } + for _, rs := range s.RootModule().Resources { + if rs.Type != "ibm_scc_profile_attachment" { + continue + } + + getProfileAttachmentOptions := &securityandcompliancecenterapiv3.GetProfileAttachmentOptions{} + + parts, err := flex.SepIdParts(rs.Primary.ID, "/") + if err != nil { + return err + } + + getProfileAttachmentOptions.SetProfileID(parts[0]) + getProfileAttachmentOptions.SetAttachmentID(parts[1]) + + // Try to find the key + _, response, err := securityandcompliancecenterapiClient.GetProfileAttachment(getProfileAttachmentOptions) + + if err == nil { + return fmt.Errorf("scc_profile_attachment still exists: %s", rs.Primary.ID) + } else if response.StatusCode != 404 { + return fmt.Errorf("Error checking for scc_profile_attachment (%s) has been destroyed: %s", rs.Primary.ID, err) + } + } + + return nil +} diff --git a/ibm/service/scc/resource_ibm_scc_profile_test.go b/ibm/service/scc/resource_ibm_scc_profile_test.go new file mode 100644 index 0000000000..dd7a317d0a --- /dev/null +++ b/ibm/service/scc/resource_ibm_scc_profile_test.go @@ -0,0 +1,264 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func TestAccIbmSccProfileBasic(t *testing.T) { + var conf securityandcompliancecenterapiv3.Profile + profileName := fmt.Sprintf("tf_profile_name_%d", acctest.RandIntRange(10, 100)) + profileDescription := fmt.Sprintf("tf_profile_description_%d", acctest.RandIntRange(10, 100)) + profileType := "custom" + profileNameUpdate := profileName + profileDescriptionUpdate := profileDescription + profileTypeUpdate := profileType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmSccProfileDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccProfileConfigBasic(profileName, profileDescription, profileType), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmSccProfileExists("ibm_scc_profile.scc_profile_instance", conf), + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_name", profileName), + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_description", profileDescription), + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_type", profileType), + ), + }, + resource.TestStep{ + Config: testAccCheckIbmSccProfileConfigBasic(profileNameUpdate, profileDescriptionUpdate, profileTypeUpdate), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_name", profileNameUpdate), + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_description", profileDescriptionUpdate), + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_type", profileTypeUpdate), + ), + }, + }, + }) +} + +func TestAccIbmSccProfileAllArgs(t *testing.T) { + var conf securityandcompliancecenterapiv3.Profile + profileName := fmt.Sprintf("tf_profile_name_%d", acctest.RandIntRange(10, 100)) + profileDescription := fmt.Sprintf("tf_profile_description_%d", acctest.RandIntRange(10, 100)) + profileType := "custom" + profileNameUpdate := profileName + profileDescriptionUpdate := profileDescription + profileTypeUpdate := profileType + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmSccProfileDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmSccProfileConfig(profileName, profileDescription, profileType), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmSccProfileExists("ibm_scc_profile.scc_profile_instance", conf), + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_name", profileName), + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_description", profileDescription), + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_type", profileType), + ), + }, + resource.TestStep{ + Config: testAccCheckIbmSccProfileConfig(profileNameUpdate, profileDescriptionUpdate, profileTypeUpdate), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_name", profileNameUpdate), + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_description", profileDescriptionUpdate), + resource.TestCheckResourceAttr("ibm_scc_profile.scc_profile_instance", "profile_type", profileTypeUpdate), + ), + }, + resource.TestStep{ + ResourceName: "ibm_scc_profile.scc_profile_instance", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckIbmSccProfileConfigBasic(profileName string, profileDescription string, profileType string) string { + return fmt.Sprintf(` + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "control_library_name" + control_library_description = "control_library_description" + control_library_type = "custom" + version_group_label = "03354ab4-03be-41c0-a469-826fc0262e78" + latest = true + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + + resource "ibm_scc_profile" "scc_profile_instance" { + profile_name = "%s" + profile_description = "%s" + profile_type = "%s" + controls { + control_library_id = resource.ibm_scc_control_library.scc_control_library_instance.id + control_id = resource.ibm_scc_control_library.scc_control_library_instance.controls[0].control_id + } + } + + `, profileName, profileDescription, profileType) +} + +func testAccCheckIbmSccProfileConfig(profileName string, profileDescription string, profileType string) string { + return fmt.Sprintf(` + resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_name = "control_library_name" + control_library_description = "control_library_description" + control_library_type = "custom" + version_group_label = "03354ab4-03be-41c0-a469-826fc0262e78" + latest = true + controls { + control_name = "control-name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "f3517159-889e-4781-819a-89d89b747c85" + environment = "environment" + control_specification_description = "control_specification_description" + assessments { + assessment_id = "rule-a637949b-7e51-46c4-afd4-b96619001bf1" + assessment_method = "ibm-cloud-rule" + assessment_type = "automated" + assessment_description = "assessment_description" + parameters { + parameter_display_name = "Sign out due to inactivity in seconds" + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + } + + resource "ibm_scc_profile" "scc_profile_instance" { + profile_name = "%s" + profile_description = "%s" + profile_type = "%s" + controls { + control_library_id = resource.ibm_scc_control_library.scc_control_library_instance.id + control_id = resource.ibm_scc_control_library.scc_control_library_instance.controls[0].control_id + } + default_parameters { + assessment_type = "automated" + assessment_id = resource.ibm_scc_control_library.scc_control_library_instance.controls[0].control_specifications[0].assessments[0].assessment_id + parameter_name = "session_invalidation_in_seconds" + parameter_type = "numeric" + parameter_default_value = "9" + parameter_display_name = resource.ibm_scc_control_library.scc_control_library_instance.controls[0].control_specifications[0].assessments[0].parameters[0].parameter_display_name + } + } + + `, profileName, profileDescription, profileType) +} + +func testAccCheckIbmSccProfileExists(n string, obj securityandcompliancecenterapiv3.Profile) resource.TestCheckFunc { + + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + securityandcompliancecenterapiClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return err + } + + getProfileOptions := &securityandcompliancecenterapiv3.GetProfileOptions{} + + getProfileOptions.SetProfileID(rs.Primary.ID) + + profile, _, err := securityandcompliancecenterapiClient.GetProfile(getProfileOptions) + if err != nil { + return err + } + + obj = *profile + return nil + } +} + +func testAccCheckIbmSccProfileDestroy(s *terraform.State) error { + securityandcompliancecenterapiClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return err + } + for _, rs := range s.RootModule().Resources { + if rs.Type != "ibm_scc_profile" { + continue + } + + getProfileOptions := &securityandcompliancecenterapiv3.GetProfileOptions{} + + getProfileOptions.SetProfileID(rs.Primary.ID) + + // Try to find the key + _, response, err := securityandcompliancecenterapiClient.GetProfile(getProfileOptions) + + if err == nil { + return fmt.Errorf("scc_profile still exists: %s", rs.Primary.ID) + } else if response.StatusCode != 404 { + return fmt.Errorf("Error checking for scc_profile (%s) has been destroyed: %s", rs.Primary.ID, err) + } + } + + return nil +} diff --git a/ibm/service/scc/resource_ibm_scc_provider_type_instance.go b/ibm/service/scc/resource_ibm_scc_provider_type_instance.go new file mode 100644 index 0000000000..95d61448e5 --- /dev/null +++ b/ibm/service/scc/resource_ibm_scc_provider_type_instance.go @@ -0,0 +1,266 @@ +//ng Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" + "github.com/IBM/go-sdk-core/v5/core" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func ResourceIbmSccProviderTypeInstance() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIbmSccProviderTypeInstanceCreate, + ReadContext: resourceIbmSccProviderTypeInstanceRead, + UpdateContext: resourceIbmSccProviderTypeInstanceUpdate, + DeleteContext: resourceIbmSccProviderTypeInstanceDelete, + Importer: &schema.ResourceImporter{}, + + Schema: map[string]*schema.Schema{ + "provider_type_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_provider_type_instance", "provider_type_id"), + Description: "The provider type ID.", + }, + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_provider_type_instance", "name"), + Description: "The name of the provider type instance.", + }, + "attributes": { + Type: schema.TypeMap, + Optional: true, + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of the provider type.", + }, + "created_at": { + Type: schema.TypeString, + Computed: true, + Description: "Time at which resource was created.", + }, + "updated_at": { + Type: schema.TypeString, + Computed: true, + Description: "Time at which resource was updated.", + }, + "provider_type_instance_id": { + Type: schema.TypeString, + Computed: true, + Description: "The unique identifier of the provider type instance.", + }, + }, + } +} + +func ResourceIbmSccProviderTypeInstanceValidator() *validate.ResourceValidator { + validateSchema := make([]validate.ValidateSchema, 0) + validateSchema = append(validateSchema, + validate.ValidateSchema{ + Identifier: "provider_type_id", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^[a-zA-Z0-9 ,\-_]+$`, + MinValueLength: 32, + MaxValueLength: 36, + }, + validate.ValidateSchema{ + Identifier: "name", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `[A-Za-z0-9]+`, + MinValueLength: 1, + MaxValueLength: 64, + }, + ) + + resourceValidator := validate.ResourceValidator{ResourceName: "ibm_scc_provider_type_instance", Schema: validateSchema} + return &resourceValidator +} + +func resourceIbmSccProviderTypeInstanceCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityAndComplianceCenterApIsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + createProviderTypeInstanceOptions := &securityandcompliancecenterapiv3.CreateProviderTypeInstanceOptions{} + + createProviderTypeInstanceOptions.SetProviderTypeID(d.Get("provider_type_id").(string)) + createProviderTypeInstanceOptions.SetName(d.Get("name").(string)) + attributesModel, err := resourceIbmSccProviderTypeInstanceMapToProviderTypeInstanceAttributes(d.Get("attributes").(map[string]interface{})) + if err != nil { + return diag.FromErr(err) + } + createProviderTypeInstanceOptions.SetAttributes(attributesModel) + + providerTypeInstanceItem, response, err := securityAndComplianceCenterApIsClient.CreateProviderTypeInstanceWithContext(context, createProviderTypeInstanceOptions) + if err != nil { + log.Printf("[DEBUG] CreateProviderTypeInstanceWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("CreateProviderTypeInstanceWithContext failed %s\n%s", err, response)) + } + + d.SetId(fmt.Sprintf("%s/%s", *createProviderTypeInstanceOptions.ProviderTypeID, *providerTypeInstanceItem.ID)) + + return resourceIbmSccProviderTypeInstanceRead(context, d, meta) +} + +func resourceIbmSccProviderTypeInstanceRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityAndComplianceCenterApIsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + getProviderTypeInstanceOptions := &securityandcompliancecenterapiv3.GetProviderTypeInstanceOptions{} + + parts, err := flex.SepIdParts(d.Id(), "/") + if err != nil { + return diag.FromErr(err) + } + + getProviderTypeInstanceOptions.SetProviderTypeID(parts[0]) + getProviderTypeInstanceOptions.SetProviderTypeInstanceID(parts[1]) + + providerTypeInstanceItem, response, err := securityAndComplianceCenterApIsClient.GetProviderTypeInstanceWithContext(context, getProviderTypeInstanceOptions) + if err != nil { + if response != nil && response.StatusCode == 404 { + d.SetId("") + return nil + } + log.Printf("[DEBUG] GetProviderTypeInstanceWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("GetProviderTypeInstanceWithContext failed %s\n%s", err, response)) + } + + if err = d.Set("name", providerTypeInstanceItem.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + + attributesMap, err := resourceIbmSccProviderTypeInstanceProviderTypeInstanceAttributesToMap(providerTypeInstanceItem.Attributes) + if err != nil { + return diag.FromErr(err) + } + + if err = d.Set("attributes", attributesMap); err != nil { + return diag.FromErr(fmt.Errorf("Error setting attributes: %s", err)) + } + + if !core.IsNil(providerTypeInstanceItem.Type) { + if err = d.Set("type", providerTypeInstanceItem.Type); err != nil { + return diag.FromErr(fmt.Errorf("Error setting type: %s", err)) + } + } + if !core.IsNil(providerTypeInstanceItem.CreatedAt) { + if err = d.Set("created_at", flex.DateTimeToString(providerTypeInstanceItem.CreatedAt)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + } + } + if !core.IsNil(providerTypeInstanceItem.UpdatedAt) { + if err = d.Set("updated_at", flex.DateTimeToString(providerTypeInstanceItem.UpdatedAt)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + } + } + if !core.IsNil(providerTypeInstanceItem.ID) { + if err = d.Set("provider_type_instance_id", providerTypeInstanceItem.ID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting provider_type_instance_id: %s", err)) + } + } + if err = d.Set("provider_type_id", parts[0]); err != nil { + return diag.FromErr(fmt.Errorf("Error setting provider_type_id: %s", err)) + } + + return nil +} + +func resourceIbmSccProviderTypeInstanceUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityAndComplianceCenterApIsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + updateProviderTypeInstanceOptions := &securityandcompliancecenterapiv3.UpdateProviderTypeInstanceOptions{} + + parts, err := flex.SepIdParts(d.Id(), "/") + if err != nil { + return diag.FromErr(err) + } + + updateProviderTypeInstanceOptions.SetProviderTypeID(parts[0]) + updateProviderTypeInstanceOptions.SetProviderTypeInstanceID(parts[1]) + + hasChange := false + + if d.HasChange("provider_type_id") { + return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ + " The resource must be re-created to update this property.", "provider_type_id")) + } + if d.HasChange("attributes") { + updateProviderTypeInstanceOptions.SetAttributes(d.Get("attributes").(map[string]interface{})) + hasChange = true + } + if d.HasChange("name") { + updateProviderTypeInstanceOptions.SetName(d.Get("name").(string)) + hasChange = true + } + + if hasChange { + _, response, err := securityAndComplianceCenterApIsClient.UpdateProviderTypeInstanceWithContext(context, updateProviderTypeInstanceOptions) + if err != nil { + log.Printf("[DEBUG] UpdateProviderTypeInstanceWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("UpdateProviderTypeInstanceWithContext failed %s\n%s", err, response)) + } + } + + return resourceIbmSccProviderTypeInstanceRead(context, d, meta) +} + +func resourceIbmSccProviderTypeInstanceDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + securityAndComplianceCenterApIsClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return diag.FromErr(err) + } + + deleteProviderTypeInstanceOptions := &securityandcompliancecenterapiv3.DeleteProviderTypeInstanceOptions{} + + parts, err := flex.SepIdParts(d.Id(), "/") + if err != nil { + return diag.FromErr(err) + } + + deleteProviderTypeInstanceOptions.SetProviderTypeID(parts[0]) + deleteProviderTypeInstanceOptions.SetProviderTypeInstanceID(parts[1]) + + response, err := securityAndComplianceCenterApIsClient.DeleteProviderTypeInstanceWithContext(context, deleteProviderTypeInstanceOptions) + if err != nil { + log.Printf("[DEBUG] DeleteProviderTypeInstanceWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("DeleteProviderTypeInstanceWithContext failed %s\n%s", err, response)) + } + + d.SetId("") + + return nil +} + +func resourceIbmSccProviderTypeInstanceMapToProviderTypeInstanceAttributes(modelMap map[string]interface{}) (map[string]interface{}, error) { + return modelMap, nil +} + +func resourceIbmSccProviderTypeInstanceProviderTypeInstanceAttributesToMap(modelMap map[string]interface{}) (map[string]interface{}, error) { + return modelMap, nil +} diff --git a/ibm/service/scc/resource_ibm_scc_provider_type_instance_test.go b/ibm/service/scc/resource_ibm_scc_provider_type_instance_test.go new file mode 100644 index 0000000000..ad79dcf352 --- /dev/null +++ b/ibm/service/scc/resource_ibm_scc_provider_type_instance_test.go @@ -0,0 +1,165 @@ +// Copyright IBM Corp. 2023 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package scc_test + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" +) + +func TestAccIbmSccProviderTypeInstanceBasic(t *testing.T) { + var conf securityandcompliancecenterapiv3.ProviderTypeInstanceItem + providerTypeAttributes := os.Getenv("IBMCLOUD_SCC_PROVIDER_TYPE_ATTRIBUTES") + name := fmt.Sprintf("tf_provider_type_instance_name_%d", acctest.RandIntRange(10, 100)) + nameUpdate := fmt.Sprintf("tf_provider_type_instance_name_%d", acctest.RandIntRange(10, 100)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmSccProviderTypeInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccProviderTypeInstanceConfigBasic(name, providerTypeAttributes), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmSccProviderTypeInstanceExists("ibm_scc_provider_type_instance.scc_provider_type_instance_wlp", conf), + resource.TestCheckResourceAttr("ibm_scc_provider_type_instance.scc_provider_type_instance_wlp", "name", name), + ), + }, + { + Config: testAccCheckIbmSccProviderTypeInstanceConfigBasic(nameUpdate, providerTypeAttributes), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("ibm_scc_provider_type_instance.scc_provider_type_instance_wlp", "name", nameUpdate), + ), + }, + }, + }) +} + +func TestAccIbmSccProviderTypeInstanceAllArgs(t *testing.T) { + var conf securityandcompliancecenterapiv3.ProviderTypeInstanceItem + providerTypeAttributes := os.Getenv("IBMCLOUD_SCC_PROVIDER_TYPE_ATTRIBUTES") + name := fmt.Sprintf("tf_provider_type_instance_name_%d", acctest.RandIntRange(10, 100)) + nameUpdate := fmt.Sprintf("tf_provider_type_instance_name_%d", acctest.RandIntRange(10, 100)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmSccProviderTypeInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccProviderTypeInstanceConfig(name, providerTypeAttributes), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmSccProviderTypeInstanceExists("ibm_scc_provider_type_instance.scc_provider_type_instance_wlp", conf), + resource.TestCheckResourceAttr("ibm_scc_provider_type_instance.scc_provider_type_instance_wlp", "name", name), + ), + }, + { + Config: testAccCheckIbmSccProviderTypeInstanceConfig(nameUpdate, providerTypeAttributes), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("ibm_scc_provider_type_instance.scc_provider_type_instance_wlp", "name", nameUpdate), + ), + }, + { + ResourceName: "ibm_scc_provider_type_instance.scc_provider_type_instance_wlp", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckIbmSccProviderTypeInstanceConfigBasic(name string, attributes string) string { + return fmt.Sprintf(` + resource "ibm_scc_provider_type_instance" "scc_provider_type_instance_wlp" { + provider_type_id = "afa2476ecfa5f09af248492fe991b4d1" + name = "%s" + attributes = %s + } + `, name, attributes) +} + +func testAccCheckIbmSccProviderTypeInstanceConfig(name string, attributes string) string { + return fmt.Sprintf(` + resource "ibm_scc_provider_type_instance" "scc_provider_type_instance_wlp" { + provider_type_id = "afa2476ecfa5f09af248492fe991b4d1" + name = "%s" + attributes = %s + } + `, name, attributes) +} + +func testAccCheckIbmSccProviderTypeInstanceExists(n string, obj securityandcompliancecenterapiv3.ProviderTypeInstanceItem) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + securityAndComplianceCenterApIsClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return err + } + + getProviderTypeInstanceOptions := &securityandcompliancecenterapiv3.GetProviderTypeInstanceOptions{} + + parts, err := flex.SepIdParts(rs.Primary.ID, "/") + if err != nil { + return err + } + + getProviderTypeInstanceOptions.SetProviderTypeID(parts[0]) + getProviderTypeInstanceOptions.SetProviderTypeInstanceID(parts[1]) + + providerTypeInstanceItem, _, err := securityAndComplianceCenterApIsClient.GetProviderTypeInstance(getProviderTypeInstanceOptions) + if err != nil { + return err + } + + obj = *providerTypeInstanceItem + return nil + } +} + +func testAccCheckIbmSccProviderTypeInstanceDestroy(s *terraform.State) error { + securityAndComplianceCenterApIsClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).SecurityAndComplianceCenterV3() + if err != nil { + return err + } + for _, rs := range s.RootModule().Resources { + if rs.Type != "ibm_scc_provider_type_instance" { + continue + } + + getProviderTypeInstanceOptions := &securityandcompliancecenterapiv3.GetProviderTypeInstanceOptions{} + + parts, err := flex.SepIdParts(rs.Primary.ID, "/") + if err != nil { + return err + } + + getProviderTypeInstanceOptions.SetProviderTypeID(parts[0]) + getProviderTypeInstanceOptions.SetProviderTypeInstanceID(parts[1]) + + // Try to find the key + _, response, err := securityAndComplianceCenterApIsClient.GetProviderTypeInstance(getProviderTypeInstanceOptions) + + if err == nil { + return fmt.Errorf("scc_provider_type_instance still exists: %s", rs.Primary.ID) + } else if response.StatusCode != 404 { + return fmt.Errorf("Error checking for scc_provider_type_instance (%s) has been destroyed: %s", rs.Primary.ID, err) + } + } + + return nil +} diff --git a/ibm/service/scc/resource_ibm_scc_rule.go b/ibm/service/scc/resource_ibm_scc_rule.go index 966ae504ab..056ae35cbe 100644 --- a/ibm/service/scc/resource_ibm_scc_rule.go +++ b/ibm/service/scc/resource_ibm_scc_rule.go @@ -1,90 +1,70 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package scc import ( "context" - "errors" "fmt" "log" + "reflect" + "strings" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/go-sdk-core/v5/core" - "github.com/IBM/scc-go-sdk/v3/configurationgovernancev1" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" ) -// Functions that were changed for validation: -// - resourceIBMSccRuleMapToRuleCondition -// - resourceIBMSccRuleMapToRuleSingleProperty - -const maxDepth = 1 - -func ResourceIBMSccRule() *schema.Resource { +func ResourceIbmSccRule() *schema.Resource { return &schema.Resource{ - CreateContext: resourceIBMSccRuleCreate, - ReadContext: resourceIBMSccRuleRead, - UpdateContext: resourceIBMSccRuleUpdate, - DeleteContext: resourceIBMSccRuleDelete, + CreateContext: resourceIbmSccRuleCreate, + ReadContext: resourceIbmSccRuleRead, + UpdateContext: resourceIbmSccRuleUpdate, + DeleteContext: resourceIbmSccRuleDelete, Importer: &schema.ResourceImporter{}, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(60 * time.Minute), + Update: schema.DefaultTimeout(60 * time.Minute), + Delete: schema.DefaultTimeout(20 * time.Minute), + }, Schema: map[string]*schema.Schema{ - "account_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "Your IBM Cloud account ID.", - }, + // Deprecation list "name": &schema.Schema{ Type: schema.TypeString, - Required: true, + Optional: true, Description: "A human-readable alias to assign to your rule.", - }, - "description": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "An extended description of your rule.", + Deprecated: "name is now deprecated", }, "rule_type": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "The type of rule. Rules that you create are `user_defined`.", - }, - "labels": &schema.Schema{ - Type: schema.TypeList, - Optional: true, - Description: "Labels that you can use to group and search for similar rules, such as those that help you to meet a specific organization guideline.", - Elem: &schema.Schema{Type: schema.TypeString}, + Deprecated: "use type instead", }, "creation_date": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "The date the resource was created.", + Deprecated: "use created_on instead", }, - "created_by": &schema.Schema{ + "modification_date": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "The unique identifier for the user or application that created the resource.", - }, - "modification_date": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - // ForceNew: true, // Type 1 Fix Description: "The date the resource was last modified.", + Deprecated: "use updated_on instead", }, "modified_by": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "The unique identifier for the user or application that last modified the resource.", - }, - "version": &schema.Schema{ - Type: schema.TypeString, - Computed: true, + Deprecated: "use updated_by", }, "enforcement_actions": &schema.Schema{ Type: schema.TypeList, @@ -99,167 +79,463 @@ func ResourceIBMSccRule() *schema.Resource { }, }, }, - MaxItems: 1, + MaxItems: 1, + Deprecated: "enforcement_actions is now deprecated", + }, + // End of Deprecation list + "account_id": { + Type: schema.TypeString, + Computed: true, + Description: "The account ID.", + }, + "created_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the rule was created.", + }, + "created_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who created the rule.", + }, + "description": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_rule", "description"), + Description: "The details of a rule's response.", + }, + // Manual Intervention + "etag": { + Type: schema.TypeString, + Computed: true, + Description: "The etag of the rule.", + }, + // End Manual Intervention + "import": { + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + Description: "The collection of import parameters.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "parameters": { + Type: schema.TypeList, + Optional: true, + Description: "The list of import parameters.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "The import parameter name.", + }, + "display_name": { + Type: schema.TypeString, + Optional: true, + Description: "The display name of the property.", + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: "The propery description.", + }, + "type": { + Type: schema.TypeString, + Optional: true, + Description: "The property type.", + }, + }, + }, + }, + }, + }, + }, + "labels": { + Type: schema.TypeList, + Optional: true, + Description: "The list of labels.", + Elem: &schema.Schema{Type: schema.TypeString}, }, - "required_config": &schema.Schema{ - Description: "The requirements that must be met to determine the resource's level of compliance in accordance with the rule. Use logical operators (and/or) to define multiple property checks and conditions. To define requirements for a rule, list one or more property check objects in the and array. To add conditions to a property check, use or.", + "required_config": { Type: schema.TypeList, + MinItems: 1, + MaxItems: 1, Required: true, + Description: "The required configurations.", Elem: &schema.Resource{ - Schema: getRequiredConfigSchema(0), + Schema: map[string]*schema.Schema{ + "description": { + Type: schema.TypeString, + Optional: true, + Description: "The required config description.", + }, + "and": { + Type: schema.TypeList, + Optional: true, + Description: "The `AND` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": { + Type: schema.TypeString, + Optional: true, + Description: "The required config description.", + }, + "or": { + Type: schema.TypeList, + Optional: true, + Description: "The `OR` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": { + Type: schema.TypeString, + Optional: true, + Description: "The required config description.", + }, + "property": { + Type: schema.TypeString, + Required: true, + Description: "The property.", + }, + "operator": { + Type: schema.TypeString, + Required: true, + Description: "The operator.", + }, + "value": { + Type: schema.TypeString, + Optional: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "and": { + Type: schema.TypeList, + Optional: true, + Description: "The `AND` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": { + Type: schema.TypeString, + Optional: true, + Description: "The required config description.", + }, + "property": { + Type: schema.TypeString, + Required: true, + Description: "The property.", + }, + "operator": { + Type: schema.TypeString, + Required: true, + Description: "The operator.", + }, + "value": { + Type: schema.TypeString, + Optional: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "property": { + Type: schema.TypeString, + Optional: true, + Description: "The property.", + }, + "operator": { + Type: schema.TypeString, + Optional: true, + Description: "The operator.", + }, + "value": { + Type: schema.TypeString, + Optional: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "or": { + Type: schema.TypeList, + Optional: true, + Description: "The `OR` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": { + Type: schema.TypeString, + Optional: true, + Description: "The required config description.", + }, + "or": { + Type: schema.TypeList, + Optional: true, + Description: "The `OR` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": { + Type: schema.TypeString, + Optional: true, + Description: "The required config description.", + }, + "property": { + Type: schema.TypeString, + Required: true, + Description: "The property.", + }, + "operator": { + Type: schema.TypeString, + Required: true, + Description: "The operator.", + }, + "value": { + Type: schema.TypeString, + Optional: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "and": { + Type: schema.TypeList, + Optional: true, + Description: "The `AND` required configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": { + Type: schema.TypeString, + Optional: true, + Description: "The required config description.", + }, + "property": { + Type: schema.TypeString, + Required: true, + Description: "The property.", + }, + "operator": { + Type: schema.TypeString, + Required: true, + Description: "The operator.", + }, + "value": { + Type: schema.TypeString, + Optional: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "property": { + Type: schema.TypeString, + Optional: true, + Description: "The property.", + }, + "operator": { + Type: schema.TypeString, + Optional: true, + Description: "The operator.", + }, + "value": { + Type: schema.TypeString, + Optional: true, + Description: "Schema for any JSON type.", + }, + }, + }, + }, + "property": { + Type: schema.TypeString, + Optional: true, + Description: "The property.", + }, + "operator": { + Type: schema.TypeString, + Optional: true, + Description: "The operator.", + }, + "value": { + Type: schema.TypeString, + Optional: true, + Description: "Schema for any JSON type.", + }, + }, }, - MaxItems: 1, }, - "target": &schema.Schema{ + "target": { Type: schema.TypeList, + MinItems: 1, + MaxItems: 1, Required: true, - Description: "The properties that describe the resource that you want to targetwith the rule or template.", + Description: "The rule target.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "service_name": &schema.Schema{ + "service_name": { Type: schema.TypeString, Required: true, - Description: "The programmatic name of the IBM Cloud service that you want to target with the rule or template.", + Description: "The target service name.", + }, + "service_display_name": { + Type: schema.TypeString, + Optional: true, + Description: "The display name of the target service.", + // Manual Intervention + DiffSuppressFunc: func(_, oldVal, newVal string, d *schema.ResourceData) bool { + if newVal == "" { + return true + } + if strings.ToLower(oldVal) == strings.ToLower(newVal) { + return true + } + return false + }, + // End Manual Intervention }, - "resource_kind": &schema.Schema{ + "resource_kind": { Type: schema.TypeString, Required: true, - Description: "The type of resource that you want to target.", + Description: "The target resource kind.", }, - "additional_target_attributes": &schema.Schema{ + "additional_target_attributes": { Type: schema.TypeList, Optional: true, - Description: "An extra qualifier for the resource kind. When you include additional attributes, only the resources that match the definition are included in the rule or template.", + Description: "The list of targets supported properties.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Optional: true, - Description: "The name of the additional attribute that you want to use to further qualify the target.Options differ depending on the service or resource that you are targeting with a rule or template. For more information, refer to the service documentation.", + Description: "The additional target attribute name.", }, - "value": &schema.Schema{ + "operator": { Type: schema.TypeString, Optional: true, - Description: "The value that you want to apply to `name` field.Options differ depending on the rule or template that you configure. For more information, refer to the service documentation.", + Description: "The operator.", }, - "operator": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "The way in which the `name` field is compared to its value.There are three types of operators: string, numeric, and boolean.", - ValidateFunc: validate.InvokeValidator("ibm_scc_rule", "operator"), + "value": { + Type: schema.TypeString, + Optional: true, + Description: "The value.", }, }, }, }, }, }, - MaxItems: 1, + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "The rule type (allowable values are `user_defined` or `system_defined`).", + }, + "updated_on": { + Type: schema.TypeString, + Computed: true, + Description: "The date when the rule was modified.", + }, + "updated_by": { + Type: schema.TypeString, + Computed: true, + Description: "The user who modified the rule.", + }, + "version": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_scc_rule", "version"), + Description: "The version number of a rule.", }, }, - CustomizeDiff: customdiff.All( - // update the version number via API GET if any of the fields are changed - customdiff.ComputedIf("version", func(_ context.Context, diff *schema.ResourceDiff, meta interface{}) bool { - return diff.HasChange("name") || diff.HasChange("description") || - diff.HasChange("target") || diff.HasChange("labels") || - diff.HasChange("required_config") || diff.HasChange("enforcement_actions") - }), - // update the modification_date via API GET if any of the fields are changed - customdiff.ComputedIf("modification_date", func(_ context.Context, diff *schema.ResourceDiff, meta interface{}) bool { - return diff.HasChange("name") || diff.HasChange("description") || - diff.HasChange("target") || diff.HasChange("labels") || - diff.HasChange("required_config") || diff.HasChange("enforcement_actions") - }), - ), } } -func getRequiredConfigSchema(currentDepth int) map[string]*schema.Schema { - baseMap := map[string]*schema.Schema{ - "description": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "The programmatic name of the IBM Cloud service that you want to target with the rule or template.", - }, - "property": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "The name of the additional attribute that you want to use to further qualify the target.Options differ depending on the service or resource that you are targeting with a rule or template. For more information, refer to the service documentation.", +func ResourceIbmSccRuleValidator() *validate.ResourceValidator { + validateSchema := make([]validate.ValidateSchema, 0) + validateSchema = append(validateSchema, + validate.ValidateSchema{ + Identifier: "description", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `[A-Za-z0-9]+`, + MinValueLength: 0, + MaxValueLength: 512, }, - "value": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Default: "", - Description: "The value that you want to apply to `name` field.Options differ depending on the rule or template that you configure. For more information, refer to the service documentation.", + validate.ValidateSchema{ + Identifier: "version", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Optional: true, + Regexp: `^[0-9][0-9.]*$`, + MinValueLength: 5, + MaxValueLength: 10, }, - "operator": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "The way in which the `name` field is compared to its value.There are three types of operators: string, numeric, and boolean.", - ValidateFunc: validate.InvokeValidator("ibm_scc_rule", "operator"), - }, - } + ) - if currentDepth > maxDepth { - return baseMap - } - baseMap["and"] = &schema.Schema{ - Type: schema.TypeList, - Optional: true, - Description: "A condition with the and logical operator.", - Elem: &schema.Resource{ - Schema: getRequiredConfigSchema(currentDepth + 1), - }, - } - baseMap["or"] = &schema.Schema{ - Type: schema.TypeList, - Optional: true, - Description: "A condition with the or logical operator.", - Elem: &schema.Resource{ - Schema: getRequiredConfigSchema(currentDepth + 1), - }, - } - return baseMap + resourceValidator := validate.ResourceValidator{ResourceName: "ibm_scc_rule", Schema: validateSchema} + return &resourceValidator } -func resourceIBMSccRuleCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() +func resourceIbmSccRuleCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + configManagerClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() if err != nil { return diag.FromErr(err) } - createRulesOptions := &configurationgovernancev1.CreateRulesOptions{} - var rule []configurationgovernancev1.CreateRuleRequest - ruleItem, err := resourceIBMSccRuleMapToCreateRuleRequest(d) + createRuleOptions := &securityandcompliancecenterapiv3.CreateRuleOptions{} + + createRuleOptions.SetDescription(d.Get("description").(string)) + // Manual Intervention + targetModel, err := resourceIbmSccRuleMapToTarget(d.Get("target.0").(map[string]interface{})) + // End Manual Intervention + if err != nil { + return diag.FromErr(err) + } + createRuleOptions.SetTarget(targetModel) + requiredConfigModel, err := resourceIbmSccRuleMapToRequiredConfig(d.Get("required_config.0").(map[string]interface{})) if err != nil { return diag.FromErr(err) } - rule = append(rule, *ruleItem) - createRulesOptions.SetRules(rule) + createRuleOptions.SetRequiredConfig(requiredConfigModel) + if _, ok := d.GetOk("version"); ok { + createRuleOptions.SetVersion(d.Get("version").(string)) + } + if _, ok := d.GetOk("import"); ok { + importVarModel, err := resourceIbmSccRuleMapToImport(d.Get("import.0").(map[string]interface{})) + if err != nil { + return diag.FromErr(err) + } + createRuleOptions.SetImport(importVarModel) + } + if _, ok := d.GetOk("labels"); ok { + labels := make([]string, 0) + for _, v := range d.Get("labels").([]interface{}) { + labelsItem := v.(string) + labels = append(labels, labelsItem) + } + createRuleOptions.SetLabels(labels) + } - createRulesResponse, response, err := configurationGovernanceClient.CreateRulesWithContext(context, createRulesOptions) - if err != nil || response.GetStatusCode() == 207 || response.StatusCode > 300 { - log.Printf("[DEBUG] CreateRulesWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateRulesWithContext failed %s\n%s", err, response)) + rule, response, err := configManagerClient.CreateRuleWithContext(context, createRuleOptions) + if err != nil { + log.Printf("[DEBUG] CreateRuleWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("CreateRuleWithContext failed %s\n%s", err, response)) } - d.SetId(*createRulesResponse.Rules[0].Rule.RuleID) + d.SetId(*rule.ID) - return resourceIBMSccRuleRead(context, d, meta) + return resourceIbmSccRuleRead(context, d, meta) } -func resourceIBMSccRuleRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() +func resourceIbmSccRuleRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + configManagerClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() if err != nil { return diag.FromErr(err) } - getRuleOptions := &configurationgovernancev1.GetRuleOptions{} + getRuleOptions := &securityandcompliancecenterapiv3.GetRuleOptions{} getRuleOptions.SetRuleID(d.Id()) - rule, response, err := configurationGovernanceClient.GetRuleWithContext(context, getRuleOptions) - log.Println("[DEBUG] Grabbed a response from the Read Operation") - + rule, response, err := configManagerClient.GetRuleWithContext(context, getRuleOptions) if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -268,142 +544,156 @@ func resourceIBMSccRuleRead(context context.Context, d *schema.ResourceData, met log.Printf("[DEBUG] GetRuleWithContext failed %s\n%s", err, response) return diag.FromErr(fmt.Errorf("GetRuleWithContext failed %s\n%s", err, response)) } - - if err = d.Set("account_id", rule.AccountID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) - } - if err = d.Set("name", rule.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + // Manual Intervention + if err = d.Set("etag", response.Headers.Get("ETag")); err != nil { + return diag.FromErr(fmt.Errorf("Error setting etag: %s", err)) } + // End Manual Intervention + if err = d.Set("description", rule.Description); err != nil { return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) } - if err = d.Set("rule_type", rule.RuleType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rule_type: %s", err)) + + if !core.IsNil(rule.Version) { + if err = d.Set("version", rule.Version); err != nil { + return diag.FromErr(fmt.Errorf("Error setting version: %s", err)) + } + } + + if !core.IsNil(rule.Import) { + importVarMap, err := resourceIbmSccRuleImportToMap(rule.Import) + if err != nil { + return diag.FromErr(err) + } + if err = d.Set("import", []map[string]interface{}{importVarMap}); err != nil { + return diag.FromErr(fmt.Errorf("Error setting import: %s", err)) + } } - targetMap, e := resourceIBMSccRuleTargetResourceToMap(rule.Target) - if e != nil { + + targetMap, err := resourceIbmSccRuleTargetToMap(rule.Target) + if err != nil { return diag.FromErr(err) } if err = d.Set("target", []map[string]interface{}{targetMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting target: %s", err)) } - requiredConfigMap, e := resourceIBMSccRuleRuleRequiredConfigToMap(rule.RequiredConfig) - if e != nil { + requiredConfigMap, err := resourceIbmSccRuleRequiredConfigToMap(rule.RequiredConfig) + if err != nil { return diag.FromErr(err) } if err = d.Set("required_config", []map[string]interface{}{requiredConfigMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting required_config: %s", err)) } - - enforcementAction := []map[string]interface{}{} - for _, enforcementActionItem := range rule.EnforcementActions { - enforcementActionItemMap, err := resourceIBMSccRuleEnforcementActionToMap(&enforcementActionItem) - if err != nil { - return diag.FromErr(err) - } - enforcementAction = append(enforcementAction, enforcementActionItemMap) - } - - if err = d.Set("enforcement_actions", enforcementAction); err != nil { - return diag.FromErr(fmt.Errorf("Error setting enforcement_actions: %s", err)) - } - if rule.Labels != nil { + if !core.IsNil(rule.Labels) { + log.Printf("[INFO] rule.Labels = %v\n", rule.Labels) if err = d.Set("labels", rule.Labels); err != nil { return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) } } - if err = d.Set("creation_date", flex.DateTimeToString(rule.CreationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting creation_date: %s", err)) + if err = d.Set("created_on", flex.DateTimeToString(rule.CreatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting created_on: %s", err)) } if err = d.Set("created_by", rule.CreatedBy); err != nil { return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) } - if err = d.Set("modification_date", flex.DateTimeToString(rule.ModificationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting modification_date: %s", err)) + if err = d.Set("updated_on", flex.DateTimeToString(rule.UpdatedOn)); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_on: %s", err)) } - if err = d.Set("modified_by", rule.ModifiedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting modified_by: %s", err)) + if err = d.Set("updated_by", rule.UpdatedBy); err != nil { + return diag.FromErr(fmt.Errorf("Error setting updated_by: %s", err)) + } + if err = d.Set("account_id", rule.AccountID); err != nil { + return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) } - if err = d.Set("version", response.Headers.Get("Etag")); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version: %s", err)) + if err = d.Set("type", rule.Type); err != nil { + return diag.FromErr(fmt.Errorf("Error setting type: %s", err)) } return nil } -func resourceIBMSccRuleUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() +func resourceIbmSccRuleUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + configManagerClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() if err != nil { return diag.FromErr(err) } - updateRuleOptions := &configurationgovernancev1.UpdateRuleOptions{} - - updateRuleOptions.SetRuleID(d.Id()) + replaceRuleOptions := &securityandcompliancecenterapiv3.ReplaceRuleOptions{} - hasChange := d.HasChange("name") || d.HasChange("description") || - d.HasChange("target") || d.HasChange("labels") || - d.HasChange("required_config") || d.HasChange("enforcement_actions") + replaceRuleOptions.SetRuleID(d.Id()) + // Manual Intervention + replaceRuleOptions.SetIfMatch(d.Get("etag").(string)) - if hasChange { - updateRuleOptions.SetName(d.Get("name").(string)) - updateRuleOptions.SetAccountID(d.Get("account_id").(string)) - updateRuleOptions.SetDescription(d.Get("description").(string)) + // End Manual Intervention + hasChange := false - target, err := resourceIBMSccRuleMapToTargetResource(d.Get("target.0").(map[string]interface{})) + if d.HasChange("description") || d.HasChange("target") || d.HasChange("required_config") { + replaceRuleOptions.SetDescription(d.Get("description").(string)) + target, err := resourceIbmSccRuleMapToTarget(d.Get("target.0").(map[string]interface{})) if err != nil { return diag.FromErr(err) } - updateRuleOptions.SetTarget(target) - labels := []string{} - if d.Get("labels") != nil { - for _, labelsItem := range d.Get("labels").([]interface{}) { - labels = append(labels, labelsItem.(string)) - } + replaceRuleOptions.SetTarget(target) + requiredConfig, err := resourceIbmSccRuleMapToRequiredConfig(d.Get("required_config.0").(map[string]interface{})) + if err != nil { + return diag.FromErr(err) } - updateRuleOptions.SetLabels(labels) - - required_config, err := resourceIBMSccRuleMapToRuleRequiredConfig(d.Get("required_config.0").(map[string]interface{})) + replaceRuleOptions.SetRequiredConfig(requiredConfig) + hasChange = true + } + if d.HasChange("version") { + replaceRuleOptions.SetVersion(d.Get("version").(string)) + hasChange = true + } + if d.HasChange("import") { + importVar, err := resourceIbmSccRuleMapToImport(d.Get("import.0").(map[string]interface{})) if err != nil { return diag.FromErr(err) } - updateRuleOptions.SetRequiredConfig(required_config) + replaceRuleOptions.SetImport(importVar) + hasChange = true + } + if d.HasChange("labels") { + hasChange = true + } - enforcementActions := []configurationgovernancev1.EnforcementAction{} - for _, enforcementActionsItem := range d.Get("enforcement_actions").([]interface{}) { - if enforcementActionsItem != nil { - enforcementActionsItemModel, err := resourceIBMSccRuleMapToEnforcementAction(enforcementActionsItem.(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - enforcementActions = append(enforcementActions, *enforcementActionsItemModel) + if hasChange { + if _, ok := d.GetOk("labels"); ok { + labels := make([]string, 0) + for _, v := range d.Get("labels").([]interface{}) { + labelsItem := v.(string) + labels = append(labels, labelsItem) } + replaceRuleOptions.SetLabels(labels) } - updateRuleOptions.SetEnforcementActions(enforcementActions) - - updateRuleOptions.SetIfMatch(d.Get("version").(string)) - _, response, err := configurationGovernanceClient.UpdateRuleWithContext(context, updateRuleOptions) - if err != nil || response.GetStatusCode() == 207 || response.StatusCode > 300 { - log.Printf("[DEBUG] UpdateRuleWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateRuleWithContext failed %s\n%s", err, response)) + if _, ok := d.GetOk("import"); ok { + importVar, err := resourceIbmSccRuleMapToImport(d.Get("import.0").(map[string]interface{})) + if err != nil { + return diag.FromErr(err) + } + replaceRuleOptions.SetImport(importVar) + } + _, response, err := configManagerClient.ReplaceRuleWithContext(context, replaceRuleOptions) + if err != nil { + log.Printf("[DEBUG] ReplaceRuleWithContext failed %s\n%s", err, response) + return diag.FromErr(fmt.Errorf("ReplaceRuleWithContext failed %s\n%s", err, response)) } } - return resourceIBMSccRuleRead(context, d, meta) + return resourceIbmSccRuleRead(context, d, meta) } -func resourceIBMSccRuleDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() +func resourceIbmSccRuleDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + configManagerClient, err := meta.(conns.ClientSession).SecurityAndComplianceCenterV3() if err != nil { return diag.FromErr(err) } - deleteRuleOptions := &configurationgovernancev1.DeleteRuleOptions{} + deleteRuleOptions := &securityandcompliancecenterapiv3.DeleteRuleOptions{} deleteRuleOptions.SetRuleID(d.Id()) - response, err := configurationGovernanceClient.DeleteRuleWithContext(context, deleteRuleOptions) + response, err := configManagerClient.DeleteRuleWithContext(context, deleteRuleOptions) if err != nil { log.Printf("[DEBUG] DeleteRuleWithContext failed %s\n%s", err, response) return diag.FromErr(fmt.Errorf("DeleteRuleWithContext failed %s\n%s", err, response)) @@ -414,113 +704,99 @@ func resourceIBMSccRuleDelete(context context.Context, d *schema.ResourceData, m return nil } -func resourceIBMSccRuleMapToCreateRuleRequest(d *schema.ResourceData) (*configurationgovernancev1.CreateRuleRequest, error) { - model := &configurationgovernancev1.CreateRuleRequest{} - if d.Get("request_id") != nil { - model.RequestID = core.StringPtr(d.Get("request_id").(string)) +func resourceIbmSccRuleMapToTarget(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.Target, error) { + model := &securityandcompliancecenterapiv3.Target{} + model.ServiceName = core.StringPtr(modelMap["service_name"].(string)) + if modelMap["service_display_name"] != nil && modelMap["service_display_name"].(string) != "" { + model.ServiceDisplayName = core.StringPtr(modelMap["service_display_name"].(string)) } - RuleModel, err := resourceIBMSccRuleMapToRuleRequest(d) - if err != nil { - return model, err + model.ResourceKind = core.StringPtr(modelMap["resource_kind"].(string)) + if modelMap["additional_target_attributes"] != nil { + additionalTargetAttributes := []securityandcompliancecenterapiv3.AdditionalTargetAttribute{} + for _, additionalTargetAttributesItem := range modelMap["additional_target_attributes"].([]interface{}) { + additionalTargetAttributesItemModel, err := resourceIbmSccRuleMapToAdditionalTargetAttribute(additionalTargetAttributesItem.(map[string]interface{})) + if err != nil { + return model, err + } + additionalTargetAttributes = append(additionalTargetAttributes, *additionalTargetAttributesItemModel) + } + model.AdditionalTargetAttributes = additionalTargetAttributes } - model.Rule = RuleModel return model, nil } -func resourceIBMSccRuleMapToRuleRequest(d *schema.ResourceData) (*configurationgovernancev1.RuleRequest, error) { - model := &configurationgovernancev1.RuleRequest{} - if d.Get("account_id") != nil { - model.AccountID = core.StringPtr(d.Get("account_id").(string)) +func resourceIbmSccRuleMapToAdditionalTargetAttribute(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.AdditionalTargetAttribute, error) { + model := &securityandcompliancecenterapiv3.AdditionalTargetAttribute{} + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) } - model.Name = core.StringPtr(d.Get("name").(string)) - model.Description = core.StringPtr(d.Get("description").(string)) - if d.Get("rule_type") != nil { - model.RuleType = core.StringPtr(d.Get("rule_type").(string)) + if modelMap["operator"] != nil && modelMap["operator"].(string) != "" { + model.Operator = core.StringPtr(modelMap["operator"].(string)) } - targetList := d.Get("target").([]interface{}) - TargetModel, err := resourceIBMSccRuleMapToTargetResource(targetList[0].(map[string]interface{})) - if err != nil { - return model, err + if modelMap["value"] != nil && modelMap["value"].(string) != "" { + model.Value = core.StringPtr(modelMap["value"].(string)) } - model.Target = TargetModel - requiredConfigList := d.Get("required_config").([]interface{}) - RequiredConfigModel, err := resourceIBMSccRuleMapToRuleRequiredConfig(requiredConfigList[0].(map[string]interface{})) - if err != nil { - return model, err + return model, nil +} + +func resourceIbmSccRuleMapToRequiredConfig(modelMap map[string]interface{}) (securityandcompliancecenterapiv3.RequiredConfigIntf, error) { + model := &securityandcompliancecenterapiv3.RequiredConfig{} + if modelMap["description"] != nil && modelMap["description"].(string) != "" { + model.Description = core.StringPtr(modelMap["description"].(string)) } - model.RequiredConfig = RequiredConfigModel - enforcementActions := []configurationgovernancev1.EnforcementAction{} - for _, enforcementActionsItem := range d.Get("enforcement_actions").([]interface{}) { - if enforcementActionsItem != nil { - enforcementActionsItemModel, err := resourceIBMSccRuleMapToEnforcementAction(enforcementActionsItem.(map[string]interface{})) + if modelMap["and"] != nil { + and := []securityandcompliancecenterapiv3.RequiredConfigItemsIntf{} + for _, andItem := range modelMap["and"].([]interface{}) { + andItemModel, err := resourceIbmSccRuleMapToRequiredConfigItems(andItem.(map[string]interface{})) if err != nil { return model, err } - enforcementActions = append(enforcementActions, *enforcementActionsItemModel) - } - } - model.EnforcementActions = enforcementActions - if d.Get("labels") != nil { - labels := []string{} - for _, labelsItem := range d.Get("labels").([]interface{}) { - labels = append(labels, labelsItem.(string)) + and = append(and, andItemModel) } - model.Labels = labels + model.And = and } - return model, nil -} - -func resourceIBMSccRuleMapToTargetResource(modelMap map[string]interface{}) (*configurationgovernancev1.TargetResource, error) { - model := &configurationgovernancev1.TargetResource{} - model.ServiceName = core.StringPtr(modelMap["service_name"].(string)) - model.ResourceKind = core.StringPtr(modelMap["resource_kind"].(string)) - if modelMap["additional_target_attributes"] != nil { - additionalTargetAttributes := []configurationgovernancev1.TargetResourceAdditionalTargetAttributesItem{} - for _, additionalTargetAttributesItem := range modelMap["additional_target_attributes"].([]interface{}) { - if additionalTargetAttributesItem != nil { - additionalTargetAttributesItemModel, err := resourceIBMSccRuleMapToTargetResourceAdditionalTargetAttributesItem(additionalTargetAttributesItem.(map[string]interface{})) - if err != nil { - return model, err - } - additionalTargetAttributes = append(additionalTargetAttributes, *additionalTargetAttributesItemModel) + if modelMap["or"] != nil { + or := []securityandcompliancecenterapiv3.RequiredConfigItemsIntf{} + for _, orItem := range modelMap["or"].([]interface{}) { + orItemModel, err := resourceIbmSccRuleMapToRequiredConfigItems(orItem.(map[string]interface{})) + if err != nil { + return model, err } + or = append(or, orItemModel) } - model.AdditionalTargetAttributes = additionalTargetAttributes - } - return model, nil -} - -func resourceIBMSccRuleMapToTargetResourceAdditionalTargetAttributesItem(modelMap map[string]interface{}) (*configurationgovernancev1.TargetResourceAdditionalTargetAttributesItem, error) { - model := &configurationgovernancev1.TargetResourceAdditionalTargetAttributesItem{} - model.Name = core.StringPtr(modelMap["name"].(string)) - model.Value = core.StringPtr(modelMap["value"].(string)) - model.Operator = core.StringPtr(modelMap["operator"].(string)) - return model, nil -} - -func resourceIBMSccRuleMapToRuleRequiredConfig(modelMap map[string]interface{}) (configurationgovernancev1.RuleRequiredConfigIntf, error) { - model := &configurationgovernancev1.RuleRequiredConfig{} - - if modelMap["description"] != nil { - model.Description = core.StringPtr(modelMap["description"].(string)) + model.Or = or } - if modelMap["property"] != nil { + if modelMap["property"] != nil && modelMap["property"].(string) != "" { model.Property = core.StringPtr(modelMap["property"].(string)) } - if modelMap["operator"] != nil { + if modelMap["operator"] != nil && modelMap["operator"].(string) != "" { model.Operator = core.StringPtr(modelMap["operator"].(string)) } - // TODO: handle the usage of Lists/Arrays of strings(can't be done until the go-sdk is modified) + // Manual Intervention if modelMap["value"] != nil { - model.Value = core.StringPtr(modelMap["value"].(string)) + // model.Value = modelMap["value"].(string) + sLit := strings.Trim(modelMap["value"].(string), "[]") + sList := strings.Split(sLit, ",") + if len(sList) == 1 { + model.Value = modelMap["value"].(string) + } else { + model.Value = sList + } + + } + // End Manual Intervention + return model, nil +} + +func resourceIbmSccRuleMapToRequiredConfigItems(modelMap map[string]interface{}) (securityandcompliancecenterapiv3.RequiredConfigItemsIntf, error) { + model := &securityandcompliancecenterapiv3.RequiredConfigItems{} + if modelMap["description"] != nil && modelMap["description"].(string) != "" { + model.Description = core.StringPtr(modelMap["description"].(string)) } if modelMap["or"] != nil { - or := []configurationgovernancev1.RuleConditionIntf{} + or := []securityandcompliancecenterapiv3.RequiredConfigItemsIntf{} for _, orItem := range modelMap["or"].([]interface{}) { - if orItem == nil { - return model, errors.New("or block needs to be populated") - } - orItemModel, err := resourceIBMSccRuleMapToRuleCondition(orItem.(map[string]interface{})) + orItemModel, err := resourceIbmSccRuleMapToRequiredConfigItems(orItem.(map[string]interface{})) if err != nil { return model, err } @@ -529,12 +805,9 @@ func resourceIBMSccRuleMapToRuleRequiredConfig(modelMap map[string]interface{}) model.Or = or } if modelMap["and"] != nil { - and := []configurationgovernancev1.RuleConditionIntf{} + and := []securityandcompliancecenterapiv3.RequiredConfigItemsIntf{} for _, andItem := range modelMap["and"].([]interface{}) { - if andItem == nil { - return model, errors.New("and block needs to be populated") - } - andItemModel, err := resourceIBMSccRuleMapToRuleCondition(andItem.(map[string]interface{})) + andItemModel, err := resourceIbmSccRuleMapToRequiredConfigItems(andItem.(map[string]interface{})) if err != nil { return model, err } @@ -542,274 +815,236 @@ func resourceIBMSccRuleMapToRuleRequiredConfig(modelMap map[string]interface{}) } model.And = and } - // Error out if 'and' and 'or' are set at the same level - if len(model.And) > 0 && len(model.Or) > 0 { - return model, errors.New("attributes of required_config 'or' and 'and' cannot be set at the same level") + if modelMap["property"] != nil && modelMap["property"].(string) != "" { + model.Property = core.StringPtr(modelMap["property"].(string)) } - - // Error out if the property, value, and operator are at the same level as 'and' and 'or' - if (len(*model.Value) > 0 || len(*model.Property) > 0 || len(*model.Operator) > 0) && - (len(model.And) > 0 || len(model.Or) > 0) { - return model, errors.New("'property','value','operator' should be nested inside 'and'/'or' or be by itself") + if modelMap["operator"] != nil && modelMap["operator"].(string) != "" { + model.Operator = core.StringPtr(modelMap["operator"].(string)) } - + // Manual Intervention + if modelMap["value"] != nil && len(modelMap["value"].(string)) > 0 { + // model.Value = modelMap["value"].(string) + sLit := strings.Trim(modelMap["value"].(string), "[]") + sList := strings.Split(sLit, ",") + if len(sList) == 1 { + model.Value = modelMap["value"].(string) + } else { + model.Value = sList + } + } + // Manual Intervention return model, nil } -func resourceIBMSccRuleMapToRuleCondition(modelMap map[string]interface{}) (configurationgovernancev1.RuleConditionIntf, error) { - model := &configurationgovernancev1.RuleCondition{} - if modelMap["description"] != nil { +func resourceIbmSccRuleMapToRequiredConfigBase(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase, error) { + model := &securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase{} + if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } - if modelMap["property"] != nil { - model.Property = core.StringPtr(modelMap["property"].(string)) - } - if modelMap["operator"] != nil { - model.Operator = core.StringPtr(modelMap["operator"].(string)) - } + model.Property = core.StringPtr(modelMap["property"].(string)) + model.Operator = core.StringPtr(modelMap["operator"].(string)) if modelMap["value"] != nil { - model.Value = core.StringPtr(modelMap["value"].(string)) + sLit := strings.Trim(modelMap["value"].(string), "[]") + sList := strings.Split(sLit, ",") + if len(sList) == 1 { + model.Value = modelMap["value"].(string) + } else { + model.Value = sList + } + } + return model, nil +} + +func resourceIbmSccRuleMapToRequiredConfigItemsRequiredConfigOrDepth1(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigOr, error) { + model := &securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigOr{} + if modelMap["description"] != nil && modelMap["description"].(string) != "" { + model.Description = core.StringPtr(modelMap["description"].(string)) } if modelMap["or"] != nil { - or := []configurationgovernancev1.RuleSingleProperty{} + or := []securityandcompliancecenterapiv3.RequiredConfigItemsIntf{} for _, orItem := range modelMap["or"].([]interface{}) { - if orItem == nil { - return model, errors.New("or block needs to be populated") - } - orItemModel, err := resourceIBMSccRuleMapToRuleSingleProperty(orItem.(map[string]interface{})) + orItemModel, err := resourceIbmSccRuleMapToRequiredConfigItemsRequiredConfigBase(orItem.(map[string]interface{})) if err != nil { return model, err } - or = append(or, *orItemModel) + or = append(or, orItemModel) } model.Or = or } if modelMap["and"] != nil { - and := []configurationgovernancev1.RuleSingleProperty{} - for _, andItem := range modelMap["and"].([]interface{}) { - if andItem == nil { - return model, errors.New("and block needs to be populated") - } - andItemModel, err := resourceIBMSccRuleMapToRuleSingleProperty(andItem.(map[string]interface{})) + or := []securityandcompliancecenterapiv3.RequiredConfigItemsIntf{} + for _, orItem := range modelMap["and"].([]interface{}) { + orItemModel, err := resourceIbmSccRuleMapToRequiredConfigItemsRequiredConfigBase(orItem.(map[string]interface{})) if err != nil { return model, err } - and = append(and, *andItemModel) + or = append(or, orItemModel) } - model.And = and - } - // Error out if 'and' and 'or' are set at the same level - if len(model.And) > 0 && len(model.Or) > 0 { - return model, errors.New("attributes of required_config 'or' and 'and' cannot be set at the same level") - } - - // Error out if the property, value, and operator are at the same level as 'and' and 'or' - if (len(*model.Value) > 0 || len(*model.Property) > 0 || len(*model.Operator) > 0) && - (len(model.And) > 0 || len(model.Or) > 0) { - return model, errors.New("'property','value','operator' should be nested inside 'and'/'or' or be by itself") + model.Or = or } return model, nil } -func resourceIBMSccRuleMapToRuleSingleProperty(modelMap map[string]interface{}) (*configurationgovernancev1.RuleSingleProperty, error) { - model := &configurationgovernancev1.RuleSingleProperty{} - if modelMap["description"] != nil { +func resourceIbmSccRuleMapToRequiredConfigItemsRequiredConfigAndDepth1(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigAnd, error) { + model := &securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigAnd{} + if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } - model.Property = core.StringPtr(modelMap["property"].(string)) - model.Operator = core.StringPtr(modelMap["operator"].(string)) - if modelMap["value"] != nil { - model.Value = core.StringPtr(modelMap["value"].(string)) + if modelMap["and"] != nil { + and := []securityandcompliancecenterapiv3.RequiredConfigItemsIntf{} + for _, andItem := range modelMap["and"].([]interface{}) { + andItemModel, err := resourceIbmSccRuleMapToRequiredConfigItemsRequiredConfigBase(andItem.(map[string]interface{})) + if err != nil { + return model, err + } + and = append(and, andItemModel) + } + model.And = and } return model, nil } -func resourceIBMSccRuleMapToRuleConditionSingleProperty(modelMap map[string]interface{}) (*configurationgovernancev1.RuleConditionSingleProperty, error) { - model := &configurationgovernancev1.RuleConditionSingleProperty{} - if modelMap["description"] != nil { +func resourceIbmSccRuleMapToRequiredConfigItemsRequiredConfigBase(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigBase, error) { + model := &securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigBase{} + if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } model.Property = core.StringPtr(modelMap["property"].(string)) model.Operator = core.StringPtr(modelMap["operator"].(string)) if modelMap["value"] != nil { - model.Value = core.StringPtr(modelMap["value"].(string)) + model.Value = modelMap["value"].(string) } return model, nil } -func resourceIBMSccRuleMapToRuleConditionOrLvl2(modelMap map[string]interface{}) (*configurationgovernancev1.RuleConditionOrLvl2, error) { - model := &configurationgovernancev1.RuleConditionOrLvl2{} - if modelMap["description"] != nil { +func resourceIbmSccRuleMapToRequiredConfigAnd(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigAnd, error) { + model := &securityandcompliancecenterapiv3.RequiredConfigRequiredConfigAnd{} + if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } - or := []configurationgovernancev1.RuleSingleProperty{} - for _, orItem := range modelMap["or"].([]interface{}) { - orItemModel, err := resourceIBMSccRuleMapToRuleSingleProperty(orItem.(map[string]interface{})) - if err != nil { - return model, err + if modelMap["and"] != nil { + and := []securityandcompliancecenterapiv3.RequiredConfigItemsIntf{} + for _, andItem := range modelMap["and"].([]interface{}) { + andItemModel, err := resourceIbmSccRuleMapToRequiredConfigItems(andItem.(map[string]interface{})) + if err != nil { + return model, err + } + and = append(and, andItemModel) } - or = append(or, *orItemModel) + model.And = and } - model.Or = or return model, nil } -func resourceIBMSccRuleMapToRuleConditionAndLvl2(modelMap map[string]interface{}) (*configurationgovernancev1.RuleConditionAndLvl2, error) { - model := &configurationgovernancev1.RuleConditionAndLvl2{} - if modelMap["description"] != nil { +func resourceIbmSccRuleMapToRequiredConfigOr(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigOr, error) { + model := &securityandcompliancecenterapiv3.RequiredConfigRequiredConfigOr{} + if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } - and := []configurationgovernancev1.RuleSingleProperty{} - for _, andItem := range modelMap["and"].([]interface{}) { - andItemModel, err := resourceIBMSccRuleMapToRuleSingleProperty(andItem.(map[string]interface{})) - if err != nil { - return model, err + if modelMap["or"] != nil { + or := []securityandcompliancecenterapiv3.RequiredConfigItemsIntf{} + for _, orItem := range modelMap["or"].([]interface{}) { + orItemModel, err := resourceIbmSccRuleMapToRequiredConfigItems(orItem.(map[string]interface{})) + if err != nil { + return model, err + } + or = append(or, orItemModel) } - and = append(and, *andItemModel) + model.Or = or } - model.And = and return model, nil } -func resourceIBMSccRuleMapToRuleRequiredConfigSingleProperty(modelMap map[string]interface{}) (*configurationgovernancev1.RuleRequiredConfigSingleProperty, error) { - model := &configurationgovernancev1.RuleRequiredConfigSingleProperty{} - if modelMap["description"] != nil { +func resourceIbmSccRuleMapToRequiredConfigRequiredConfigBase(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase, error) { + model := &securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase{} + if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } model.Property = core.StringPtr(modelMap["property"].(string)) model.Operator = core.StringPtr(modelMap["operator"].(string)) if modelMap["value"] != nil { - model.Value = core.StringPtr(modelMap["value"].(string)) + model.Value = modelMap["value"].(string) } return model, nil } -func resourceIBMSccRuleMapToRuleRequiredConfigMultipleProperties(modelMap map[string]interface{}) (configurationgovernancev1.RuleRequiredConfigMultiplePropertiesIntf, error) { - model := &configurationgovernancev1.RuleRequiredConfigMultipleProperties{} - if modelMap["description"] != nil { - model.Description = core.StringPtr(modelMap["description"].(string)) - } - if modelMap["or"] != nil { - or := []configurationgovernancev1.RuleConditionIntf{} - for _, orItem := range modelMap["or"].([]interface{}) { - orItemModel, err := resourceIBMSccRuleMapToRuleCondition(orItem.(map[string]interface{})) - if err != nil { - return model, err - } - or = append(or, orItemModel) - } - model.Or = or - } - if modelMap["and"] != nil { - and := []configurationgovernancev1.RuleConditionIntf{} - for _, andItem := range modelMap["and"].([]interface{}) { - andItemModel, err := resourceIBMSccRuleMapToRuleCondition(andItem.(map[string]interface{})) +func resourceIbmSccRuleMapToImport(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.Import, error) { + model := &securityandcompliancecenterapiv3.Import{} + if modelMap["parameters"] != nil { + parameters := []securityandcompliancecenterapiv3.Parameter{} + for _, parametersItem := range modelMap["parameters"].([]interface{}) { + parametersItemModel, err := resourceIbmSccRuleMapToParameter(parametersItem.(map[string]interface{})) if err != nil { return model, err } - and = append(and, andItemModel) + parameters = append(parameters, *parametersItemModel) } - model.And = and + model.Parameters = parameters } return model, nil } -func resourceIBMSccRuleMapToRuleRequiredConfigMultiplePropertiesConditionOr(modelMap map[string]interface{}) (*configurationgovernancev1.RuleRequiredConfigMultiplePropertiesConditionOr, error) { - model := &configurationgovernancev1.RuleRequiredConfigMultiplePropertiesConditionOr{} - if modelMap["description"] != nil { - model.Description = core.StringPtr(modelMap["description"].(string)) +func resourceIbmSccRuleMapToParameter(modelMap map[string]interface{}) (*securityandcompliancecenterapiv3.Parameter, error) { + model := &securityandcompliancecenterapiv3.Parameter{} + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) } - or := []configurationgovernancev1.RuleConditionIntf{} - for _, orItem := range modelMap["or"].([]interface{}) { - orItemModel, err := resourceIBMSccRuleMapToRuleCondition(orItem.(map[string]interface{})) - if err != nil { - return model, err - } - or = append(or, orItemModel) + if modelMap["display_name"] != nil && modelMap["display_name"].(string) != "" { + model.DisplayName = core.StringPtr(modelMap["display_name"].(string)) } - model.Or = or - return model, nil -} - -func resourceIBMSccRuleMapToRuleRequiredConfigMultiplePropertiesConditionAnd(modelMap map[string]interface{}) (*configurationgovernancev1.RuleRequiredConfigMultiplePropertiesConditionAnd, error) { - model := &configurationgovernancev1.RuleRequiredConfigMultiplePropertiesConditionAnd{} - if modelMap["description"] != nil { + if modelMap["description"] != nil && modelMap["description"].(string) != "" { model.Description = core.StringPtr(modelMap["description"].(string)) } - and := []configurationgovernancev1.RuleConditionIntf{} - for _, andItem := range modelMap["and"].([]interface{}) { - andItemModel, err := resourceIBMSccRuleMapToRuleCondition(andItem.(map[string]interface{})) - if err != nil { - return model, err - } - and = append(and, andItemModel) + if modelMap["type"] != nil && modelMap["type"].(string) != "" { + model.Type = core.StringPtr(modelMap["type"].(string)) } - model.And = and return model, nil } -func resourceIBMSccRuleMapToEnforcementAction(modelMap map[string]interface{}) (*configurationgovernancev1.EnforcementAction, error) { - model := &configurationgovernancev1.EnforcementAction{} - model.Action = core.StringPtr(modelMap["action"].(string)) - return model, nil -} - -func resourceIBMSccRuleCreateRuleRequestToMap(model *configurationgovernancev1.CreateRuleRequest) (map[string]interface{}, error) { +func resourceIbmSccRuleImportToMap(model *securityandcompliancecenterapiv3.Import) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - if model.RequestID != nil { - modelMap["request_id"] = model.RequestID - } - ruleMap, err := resourceIBMSccRuleRuleRequestToMap(model.Rule) - if err != nil { - return modelMap, err + if model.Parameters != nil { + parameters := []map[string]interface{}{} + for _, parametersItem := range model.Parameters { + parametersItemMap, err := resourceIbmSccRuleParameterToMap(¶metersItem) + if err != nil { + return modelMap, err + } + parameters = append(parameters, parametersItemMap) + } + modelMap["parameters"] = parameters } - modelMap["rule"] = []map[string]interface{}{ruleMap} return modelMap, nil } -func resourceIBMSccRuleRuleRequestToMap(model *configurationgovernancev1.RuleRequest) (map[string]interface{}, error) { +func resourceIbmSccRuleParameterToMap(model *securityandcompliancecenterapiv3.Parameter) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - if model.AccountID != nil { - modelMap["account_id"] = model.AccountID - } - modelMap["name"] = model.Name - modelMap["description"] = model.Description - if model.RuleType != nil { - modelMap["rule_type"] = model.RuleType + if model.Name != nil { + modelMap["name"] = model.Name } - targetMap, err := resourceIBMSccRuleTargetResourceToMap(model.Target) - if err != nil { - return modelMap, err + if model.DisplayName != nil { + modelMap["display_name"] = model.DisplayName } - modelMap["target"] = []map[string]interface{}{targetMap} - requiredConfigMap, err := resourceIBMSccRuleRuleRequiredConfigToMap(model.RequiredConfig) - if err != nil { - return modelMap, err - } - modelMap["required_config"] = []map[string]interface{}{requiredConfigMap} - enforcementActions := []map[string]interface{}{} - for _, enforcementActionsItem := range model.EnforcementActions { - enforcementActionsItemMap, err := resourceIBMSccRuleEnforcementActionToMap(&enforcementActionsItem) - if err != nil { - return modelMap, err - } - enforcementActions = append(enforcementActions, enforcementActionsItemMap) + if model.Description != nil { + modelMap["description"] = model.Description } - modelMap["enforcement_actions"] = enforcementActions - if model.Labels != nil { - modelMap["labels"] = model.Labels + if model.Type != nil { + modelMap["type"] = model.Type } return modelMap, nil } -func resourceIBMSccRuleTargetResourceToMap(model *configurationgovernancev1.TargetResource) (map[string]interface{}, error) { +func resourceIbmSccRuleTargetToMap(model *securityandcompliancecenterapiv3.Target) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["service_name"] = model.ServiceName + if model.ServiceDisplayName != nil { + modelMap["service_display_name"] = model.ServiceDisplayName + } modelMap["resource_kind"] = model.ResourceKind if model.AdditionalTargetAttributes != nil { additionalTargetAttributes := []map[string]interface{}{} for _, additionalTargetAttributesItem := range model.AdditionalTargetAttributes { - additionalTargetAttributesItemMap, err := resourceIBMSccRuleTargetResourceAdditionalTargetAttributesItemToMap(&additionalTargetAttributesItem) + additionalTargetAttributesItemMap, err := resourceIbmSccRuleAdditionalTargetAttributeToMap(&additionalTargetAttributesItem) if err != nil { return modelMap, err } @@ -820,38 +1055,48 @@ func resourceIBMSccRuleTargetResourceToMap(model *configurationgovernancev1.Targ return modelMap, nil } -func resourceIBMSccRuleTargetResourceAdditionalTargetAttributesItemToMap(model *configurationgovernancev1.TargetResourceAdditionalTargetAttributesItem) (map[string]interface{}, error) { +func resourceIbmSccRuleAdditionalTargetAttributeToMap(model *securityandcompliancecenterapiv3.AdditionalTargetAttribute) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) - modelMap["name"] = model.Name - modelMap["value"] = model.Value - modelMap["operator"] = model.Operator + if model.Name != nil { + modelMap["name"] = model.Name + } + if model.Operator != nil { + modelMap["operator"] = model.Operator + } + if model.Value != nil { + modelMap["value"] = model.Value + } return modelMap, nil } -func resourceIBMSccRuleRuleRequiredConfigToMap(model configurationgovernancev1.RuleRequiredConfigIntf) (map[string]interface{}, error) { - if _, ok := model.(*configurationgovernancev1.RuleRequiredConfigSingleProperty); ok { - return resourceIBMSccRuleRuleRequiredConfigSinglePropertyToMap(model.(*configurationgovernancev1.RuleRequiredConfigSingleProperty)) - } else if _, ok := model.(*configurationgovernancev1.RuleRequiredConfigMultipleProperties); ok { - return resourceIBMSccRuleRuleRequiredConfigMultiplePropertiesToMap(model.(*configurationgovernancev1.RuleRequiredConfigMultipleProperties)) - } else if _, ok := model.(*configurationgovernancev1.RuleRequiredConfig); ok { +func resourceIbmSccRuleRequiredConfigToMap(model securityandcompliancecenterapiv3.RequiredConfigIntf) (map[string]interface{}, error) { + if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigAnd); ok { + return resourceIbmSccRuleRequiredConfigAndToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigAnd)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigOr); ok { + return resourceIbmSccRuleRequiredConfigOrToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigOr)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase); ok { + return resourceIbmSccRuleRequiredConfigRequiredConfigBaseToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfig); ok { modelMap := make(map[string]interface{}) - model := model.(*configurationgovernancev1.RuleRequiredConfig) + model := model.(*securityandcompliancecenterapiv3.RequiredConfig) if model.Description != nil { modelMap["description"] = model.Description } - if model.Property != nil { - modelMap["property"] = model.Property - } - if model.Operator != nil { - modelMap["operator"] = model.Operator - } - if model.Value != nil { - modelMap["value"] = model.Value + if model.And != nil { + and := []map[string]interface{}{} + for _, andItem := range model.And { + andItemMap, err := resourceIbmSccRuleRequiredConfigItemsToMap(andItem) + if err != nil { + return modelMap, err + } + and = append(and, andItemMap) + } + modelMap["and"] = and } if model.Or != nil { or := []map[string]interface{}{} for _, orItem := range model.Or { - orItemMap, err := resourceIBMSccRuleRuleConditionToMap(orItem) + orItemMap, err := resourceIbmSccRuleRequiredConfigItemsToMap(orItem) if err != nil { return modelMap, err } @@ -859,49 +1104,51 @@ func resourceIBMSccRuleRuleRequiredConfigToMap(model configurationgovernancev1.R } modelMap["or"] = or } - if model.And != nil { - and := []map[string]interface{}{} - for _, andItem := range model.And { - andItemMap, err := resourceIBMSccRuleRuleConditionToMap(andItem) - if err != nil { - return modelMap, err + if model.Property != nil { + modelMap["property"] = model.Property + } + if model.Operator != nil { + modelMap["operator"] = model.Operator + } + // Manual Intervention + if model.Value != nil { + // model.Value is a schema.TypeString, so it needs to converted to String Type + switch v := model.Value.(type) { + case string: + modelMap["value"] = v + case []interface{}: + lst := []string{} + for _, val := range v { + vStr := "'" + val.(string) + "'" + lst = append(lst, vStr) } - and = append(and, andItemMap) + modelMap["value"] = "[" + strings.Join(lst, ",") + "]" } - modelMap["and"] = and } + // End Manual Intervention return modelMap, nil } else { - return nil, fmt.Errorf("Unrecognized configurationgovernancev1.RuleRequiredConfigIntf subtype encountered") + return nil, fmt.Errorf("Unrecognized securityandcompliancecenterapiv3.RequiredConfigIntf subtype encountered") } } -func resourceIBMSccRuleRuleConditionToMap(model configurationgovernancev1.RuleConditionIntf) (map[string]interface{}, error) { - if _, ok := model.(*configurationgovernancev1.RuleConditionSingleProperty); ok { - return resourceIBMSccRuleRuleConditionSinglePropertyToMap(model.(*configurationgovernancev1.RuleConditionSingleProperty)) - } else if _, ok := model.(*configurationgovernancev1.RuleConditionOrLvl2); ok { - return resourceIBMSccRuleRuleConditionOrLvl2ToMap(model.(*configurationgovernancev1.RuleConditionOrLvl2)) - } else if _, ok := model.(*configurationgovernancev1.RuleConditionAndLvl2); ok { - return resourceIBMSccRuleRuleConditionAndLvl2ToMap(model.(*configurationgovernancev1.RuleConditionAndLvl2)) - } else if _, ok := model.(*configurationgovernancev1.RuleCondition); ok { +func resourceIbmSccRuleRequiredConfigItemsToMap(model securityandcompliancecenterapiv3.RequiredConfigItemsIntf) (map[string]interface{}, error) { + if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigOr); ok { + return resourceIbmSccRuleRequiredConfigItemsRequiredConfigOrDepth1ToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigOr)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigAnd); ok { + return resourceIbmSccRuleRequiredConfigItemsRequiredConfigAndDepth1ToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigAnd)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigBase); ok { + return resourceIbmSccRuleRequiredConfigItemsRequiredConfigBaseToMap(model.(*securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigBase)) + } else if _, ok := model.(*securityandcompliancecenterapiv3.RequiredConfigItems); ok { modelMap := make(map[string]interface{}) - model := model.(*configurationgovernancev1.RuleCondition) + model := model.(*securityandcompliancecenterapiv3.RequiredConfigItems) if model.Description != nil { modelMap["description"] = model.Description } - if model.Property != nil { - modelMap["property"] = model.Property - } - if model.Operator != nil { - modelMap["operator"] = model.Operator - } - if model.Value != nil { - modelMap["value"] = model.Value - } if model.Or != nil { or := []map[string]interface{}{} for _, orItem := range model.Or { - orItemMap, err := resourceIBMSccRuleRuleSinglePropertyToMap(&orItem) + orItemMap, err := resourceIbmSccRuleRequiredConfigItemsToMap(orItem) if err != nil { return modelMap, err } @@ -912,7 +1159,7 @@ func resourceIBMSccRuleRuleConditionToMap(model configurationgovernancev1.RuleCo if model.And != nil { and := []map[string]interface{}{} for _, andItem := range model.And { - andItemMap, err := resourceIBMSccRuleRuleSinglePropertyToMap(&andItem) + andItemMap, err := resourceIbmSccRuleRequiredConfigItemsToMap(andItem) if err != nil { return modelMap, err } @@ -920,13 +1167,35 @@ func resourceIBMSccRuleRuleConditionToMap(model configurationgovernancev1.RuleCo } modelMap["and"] = and } + if model.Property != nil { + modelMap["property"] = model.Property + } + if model.Operator != nil { + modelMap["operator"] = model.Operator + } + // Manual Intervention + if model.Value != nil { + // modelMap["value"] = model.Value + switch v := model.Value.(type) { + case string: + modelMap["value"] = v + case []interface{}: + lst := []string{} + for _, val := range v { + vStr := val.(string) + lst = append(lst, vStr) + } + modelMap["value"] = strings.Join(lst, ",") + } + } + // End Manual Intervention return modelMap, nil } else { - return nil, fmt.Errorf("Unrecognized configurationgovernancev1.RuleConditionIntf subtype encountered") + return nil, fmt.Errorf("Unrecognized securityandcompliancecenterapiv3.RequiredConfigItemsIntf subtype encountered") } } -func resourceIBMSccRuleRuleSinglePropertyToMap(model *configurationgovernancev1.RuleSingleProperty) (map[string]interface{}, error) { +func resourceIbmSccRuleRequiredConfigBaseToMap(model *securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigBase) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.Description != nil { modelMap["description"] = model.Description @@ -939,141 +1208,127 @@ func resourceIBMSccRuleRuleSinglePropertyToMap(model *configurationgovernancev1. return modelMap, nil } -func resourceIBMSccRuleRuleConditionSinglePropertyToMap(model *configurationgovernancev1.RuleConditionSingleProperty) (map[string]interface{}, error) { +func resourceIbmSccRuleRequiredConfigItemsRequiredConfigOrDepth1ToMap(model *securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigOr) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.Description != nil { modelMap["description"] = model.Description } - modelMap["property"] = model.Property - modelMap["operator"] = model.Operator - if model.Value != nil { - modelMap["value"] = model.Value + if model.Or != nil { + or := []map[string]interface{}{} + for _, orItem := range model.Or { + orItemMap, err := resourceIbmSccRuleRequiredConfigItemsToMap(orItem) + if err != nil { + return modelMap, err + } + or = append(or, orItemMap) + } + modelMap["or"] = or } return modelMap, nil } -func resourceIBMSccRuleRuleConditionOrLvl2ToMap(model *configurationgovernancev1.RuleConditionOrLvl2) (map[string]interface{}, error) { +func resourceIbmSccRuleRequiredConfigItemsRequiredConfigAndDepth1ToMap(model *securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigAnd) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.Description != nil { modelMap["description"] = model.Description } - or := []map[string]interface{}{} - for _, orItem := range model.Or { - orItemMap, err := resourceIBMSccRuleRuleSinglePropertyToMap(&orItem) - if err != nil { - return modelMap, err + if model.And != nil { + and := []map[string]interface{}{} + for _, andItem := range model.And { + andItemMap, err := resourceIbmSccRuleRequiredConfigItemsToMap(andItem) + if err != nil { + return modelMap, err + } + and = append(and, andItemMap) } - or = append(or, orItemMap) + modelMap["and"] = and } - modelMap["or"] = or return modelMap, nil } -func resourceIBMSccRuleRuleConditionAndLvl2ToMap(model *configurationgovernancev1.RuleConditionAndLvl2) (map[string]interface{}, error) { +func resourceIbmSccRuleRequiredConfigItemsRequiredConfigBaseToMap(model *securityandcompliancecenterapiv3.RequiredConfigItemsRequiredConfigBase) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.Description != nil { modelMap["description"] = model.Description } - and := []map[string]interface{}{} - for _, andItem := range model.And { - andItemMap, err := resourceIBMSccRuleRuleSinglePropertyToMap(&andItem) - if err != nil { - return modelMap, err + modelMap["property"] = model.Property + modelMap["operator"] = model.Operator + if model.Value != nil { + // modelMap["value"] = model.Value + switch v := model.Value.(type) { + case string: + modelMap["value"] = v + case []string: + s := strings.Join(v, ",") + modelMap["value"] = s + default: + fmt.Printf("******** the type is %v\n", reflect.TypeOf(v)) } - and = append(and, andItemMap) } - modelMap["and"] = and return modelMap, nil } -func resourceIBMSccRuleRuleRequiredConfigSinglePropertyToMap(model *configurationgovernancev1.RuleRequiredConfigSingleProperty) (map[string]interface{}, error) { +func resourceIbmSccRuleRequiredConfigAndToMap(model *securityandcompliancecenterapiv3.RequiredConfigRequiredConfigAnd) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.Description != nil { modelMap["description"] = model.Description } - modelMap["property"] = model.Property - modelMap["operator"] = model.Operator - if model.Value != nil { - modelMap["value"] = model.Value - } - return modelMap, nil -} - -func resourceIBMSccRuleRuleRequiredConfigMultiplePropertiesToMap(model configurationgovernancev1.RuleRequiredConfigMultiplePropertiesIntf) (map[string]interface{}, error) { - if _, ok := model.(*configurationgovernancev1.RuleRequiredConfigMultiplePropertiesConditionOr); ok { - return resourceIBMSccRuleRuleRequiredConfigMultiplePropertiesConditionOrToMap(model.(*configurationgovernancev1.RuleRequiredConfigMultiplePropertiesConditionOr)) - } else if _, ok := model.(*configurationgovernancev1.RuleRequiredConfigMultiplePropertiesConditionAnd); ok { - return resourceIBMSccRuleRuleRequiredConfigMultiplePropertiesConditionAndToMap(model.(*configurationgovernancev1.RuleRequiredConfigMultiplePropertiesConditionAnd)) - } else if _, ok := model.(*configurationgovernancev1.RuleRequiredConfigMultipleProperties); ok { - modelMap := make(map[string]interface{}) - model := model.(*configurationgovernancev1.RuleRequiredConfigMultipleProperties) - if model.Description != nil { - modelMap["description"] = model.Description - } - if model.Or != nil { - or := []map[string]interface{}{} - for _, orItem := range model.Or { - orItemMap, err := resourceIBMSccRuleRuleConditionToMap(orItem) - if err != nil { - return modelMap, err - } - or = append(or, orItemMap) - } - modelMap["or"] = or - } - if model.And != nil { - and := []map[string]interface{}{} - for _, andItem := range model.And { - andItemMap, err := resourceIBMSccRuleRuleConditionToMap(andItem) - if err != nil { - return modelMap, err - } - and = append(and, andItemMap) + if model.And != nil { + and := []map[string]interface{}{} + for _, andItem := range model.And { + andItemMap, err := resourceIbmSccRuleRequiredConfigItemsToMap(andItem) + if err != nil { + return modelMap, err } - modelMap["and"] = and + and = append(and, andItemMap) } - return modelMap, nil - } else { - return nil, fmt.Errorf("Unrecognized configurationgovernancev1.RuleRequiredConfigMultiplePropertiesIntf subtype encountered") + modelMap["and"] = and } + return modelMap, nil } -func resourceIBMSccRuleRuleRequiredConfigMultiplePropertiesConditionOrToMap(model *configurationgovernancev1.RuleRequiredConfigMultiplePropertiesConditionOr) (map[string]interface{}, error) { +func resourceIbmSccRuleRequiredConfigOrToMap(model *securityandcompliancecenterapiv3.RequiredConfigRequiredConfigOr) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.Description != nil { modelMap["description"] = model.Description } - or := []map[string]interface{}{} - for _, orItem := range model.Or { - orItemMap, err := resourceIBMSccRuleRuleConditionToMap(orItem) - if err != nil { - return modelMap, err + if model.Or != nil { + or := []map[string]interface{}{} + for _, orItem := range model.Or { + orItemMap, err := resourceIbmSccRuleRequiredConfigItemsToMap(orItem) + if err != nil { + return modelMap, err + } + or = append(or, orItemMap) } - or = append(or, orItemMap) + modelMap["or"] = or } - modelMap["or"] = or return modelMap, nil } -func resourceIBMSccRuleRuleRequiredConfigMultiplePropertiesConditionAndToMap(model *configurationgovernancev1.RuleRequiredConfigMultiplePropertiesConditionAnd) (map[string]interface{}, error) { +func resourceIbmSccRuleRequiredConfigRequiredConfigBaseToMap(model *securityandcompliancecenterapiv3.RequiredConfigRequiredConfigBase) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.Description != nil { modelMap["description"] = model.Description } - and := []map[string]interface{}{} - for _, andItem := range model.And { - andItemMap, err := resourceIBMSccRuleRuleConditionToMap(andItem) - if err != nil { - return modelMap, err + modelMap["property"] = model.Property + modelMap["operator"] = model.Operator + // Manual Intervention + if model.Value != nil { + // model.Value is a schema.TypeString, so it needs to converted to String Type + switch v := model.Value.(type) { + case string: + modelMap["value"] = v + case []interface{}: + lst := []string{} + for _, val := range v { + vStr := "'" + val.(string) + "'" + lst = append(lst, vStr) + } + modelMap["value"] = "[" + "'" + strings.Join(lst, ",") + "'" + "]" } - and = append(and, andItemMap) } - modelMap["and"] = and - return modelMap, nil -} + // End Manual Intervention -func resourceIBMSccRuleEnforcementActionToMap(model *configurationgovernancev1.EnforcementAction) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - modelMap["action"] = model.Action return modelMap, nil } diff --git a/ibm/service/scc/resource_ibm_scc_rule_attachment.go b/ibm/service/scc/resource_ibm_scc_rule_attachment.go index 8eafcd195e..03542bc4fb 100644 --- a/ibm/service/scc/resource_ibm_scc_rule_attachment.go +++ b/ibm/service/scc/resource_ibm_scc_rule_attachment.go @@ -5,344 +5,20 @@ package scc import ( "context" - "fmt" - "log" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" - "github.com/IBM/go-sdk-core/v5/core" - "github.com/IBM/scc-go-sdk/v3/configurationgovernancev1" ) func ResourceIBMSccRuleAttachment() *schema.Resource { return &schema.Resource{ - CreateContext: resourceIBMSccRuleAttachmentCreate, - ReadContext: resourceIBMSccRuleAttachmentRead, - UpdateContext: resourceIBMSccRuleAttachmentUpdate, - DeleteContext: resourceIBMSccRuleAttachmentDelete, - Importer: &schema.ResourceImporter{}, - - Schema: map[string]*schema.Schema{ - "attachment_id": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The UUID that uniquely identifies the attachment.", - }, - "rule_id": &schema.Schema{ - ForceNew: true, - Type: schema.TypeString, - Required: true, - Description: "The UUID that uniquely identifies the rule.", - }, - "account_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "Your IBM Cloud account ID.", - }, - "included_scope": &schema.Schema{ - Type: schema.TypeList, - Required: true, - Description: "The extent at which the rule can be attached across your accounts.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "note": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "A short description or alias to assign to the scope.", - }, - "scope_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The ID of the scope, such as an enterprise, account, or account group, that you want to evaluate.", - }, - "scope_type": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The type of scope that you want to evaluate.", - ValidateFunc: validate.InvokeValidator("ibm_scc_rule_attachment", "scope_type"), - }, - }, - }, - MaxItems: 1, - }, - "excluded_scopes": &schema.Schema{ - Type: schema.TypeList, - Optional: true, - Description: "The extent at which the rule can be excluded from the included scope.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "note": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "A short description or alias to assign to the scope.", - }, - "scope_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The ID of the scope, such as an enterprise, account, or account group, that you want to evaluate.", - }, - "scope_type": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The type of scope that you want to evaluate.", - ValidateFunc: validate.InvokeValidator("ibm_scc_rule_attachment", "scope_type"), - }, - }, - }, - }, - "version": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, + CreateContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_rule_attachment has been deprecated") + }, + ReadContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_rule_attachment has been deprecated") + }, + DeleteContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_rule_attachment has been deprecated") }, - CustomizeDiff: customdiff.All( - // update the version number via API GET if any of the fields are true - customdiff.ComputedIf("version", func(_ context.Context, diff *schema.ResourceDiff, meta interface{}) bool { - return diff.HasChange("included_scope") || diff.HasChange("excluded_scopes") - }), - ), - } -} - -func resourceIBMSccRuleAttachmentCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - createRuleAttachmentsOptions := &configurationgovernancev1.CreateRuleAttachmentsOptions{} - - createRuleAttachmentsOptions.SetRuleID(d.Get("rule_id").(string)) - var attachment []configurationgovernancev1.RuleAttachmentRequest - attachmentItem, err := resourceIBMSccRuleAttachmentMapToRuleAttachmentRequest(d) - if err != nil { - return diag.FromErr(err) - } - attachment = append(attachment, *attachmentItem) - createRuleAttachmentsOptions.SetAttachments(attachment) - - createRuleAttachmentsResponse, response, err := configurationGovernanceClient.CreateRuleAttachmentsWithContext(context, createRuleAttachmentsOptions) - if err != nil || response.StatusCode > 300 { - log.Printf("[DEBUG] CreateRuleAttachmentsWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateRuleAttachmentsWithContext failed %s\n%s", err, response)) - } - - d.SetId(fmt.Sprintf("%s/%s", *createRuleAttachmentsOptions.RuleID, *createRuleAttachmentsResponse.Attachments[0].AttachmentID)) - - return resourceIBMSccRuleAttachmentRead(context, d, meta) -} - -func resourceIBMSccRuleAttachmentRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - getRuleAttachmentOptions := &configurationgovernancev1.GetRuleAttachmentOptions{} - - parts, err := flex.SepIdParts(d.Id(), "/") - if err != nil { - return diag.FromErr(err) - } - - getRuleAttachmentOptions.SetRuleID(parts[0]) - getRuleAttachmentOptions.SetAttachmentID(parts[1]) - - ruleAttachment, response, err := configurationGovernanceClient.GetRuleAttachmentWithContext(context, getRuleAttachmentOptions) - if err != nil { - if response != nil && response.StatusCode == 404 { - d.SetId("") - return nil - } - log.Printf("[DEBUG] GetRuleAttachmentWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetRuleAttachmentWithContext failed %s\n%s", err, response)) - } - - // TODO: handle argument of type []interface{} - if err = d.Set("rule_id", ruleAttachment.RuleID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rule_id: %s", err)) - } - if err = d.Set("account_id", ruleAttachment.AccountID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) - } - includedScopeMap, err := resourceIBMSccRuleAttachmentRuleScopeToMap(ruleAttachment.IncludedScope) - if err != nil { - return diag.FromErr(err) - } - if err = d.Set("included_scope", []map[string]interface{}{includedScopeMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting included_scope: %s", err)) - } - - excludedScope := []map[string]interface{}{} - if ruleAttachment.ExcludedScopes != nil { - for _, excludedScopeItem := range ruleAttachment.ExcludedScopes { - excludedScopeItemMap, err := resourceIBMSccRuleAttachmentRuleScopeToMap(&excludedScopeItem) - if err != nil { - return diag.FromErr(err) - } - excludedScope = append(excludedScope, excludedScopeItemMap) - } - } - if err = d.Set("excluded_scopes", excludedScope); err != nil { - return diag.FromErr(fmt.Errorf("Error setting excluded_scopes: %s", err)) - } - if err = d.Set("version", response.Headers.Get("Etag")); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version: %s", err)) - } - - return nil -} - -func resourceIBMSccRuleAttachmentUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - updateRuleAttachmentOptions := &configurationgovernancev1.UpdateRuleAttachmentOptions{} - - parts, err := flex.SepIdParts(d.Id(), "/") - if err != nil { - return diag.FromErr(err) - } - - updateRuleAttachmentOptions.SetRuleID(parts[0]) - updateRuleAttachmentOptions.SetAttachmentID(parts[1]) - - // This code is never going to work since the schema has ForceNew in property rule_id - // if d.HasChange("rule_id") { - // return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ - // " The resource must be re-created to update this property.", "rule_id")) - // } - - hasChange := d.HasChange("included_scope") || d.HasChange("excluded_scopes") - - if hasChange { - updateRuleAttachmentOptions.SetIfMatch(d.Get("version").(string)) - updateRuleAttachmentOptions.SetRuleID(d.Get("rule_id").(string)) - updateRuleAttachmentOptions.SetAccountID(d.Get("account_id").(string)) - - includedScope, err := resourceIBMSccRuleAttachmentMapToRuleScope(d.Get("included_scope.0").(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - updateRuleAttachmentOptions.SetIncludedScope(includedScope) - - excludedScopes := []configurationgovernancev1.RuleScope{} - if d.Get("excluded_scopes") != nil { - for _, scopeItem := range d.Get("excluded_scopes").([]interface{}) { - excludedScope, err := resourceIBMSccRuleAttachmentMapToRuleScope(scopeItem.(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - excludedScopes = append(excludedScopes, *excludedScope) - } - } - updateRuleAttachmentOptions.SetExcludedScopes(excludedScopes) - - _, response, err := configurationGovernanceClient.UpdateRuleAttachmentWithContext(context, updateRuleAttachmentOptions) - if err != nil || response.StatusCode > 300 { - log.Printf("[DEBUG] UpdateRuleAttachmentWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateRuleAttachmentWithContext failed %s\n%s", err, response)) - } - } - - return resourceIBMSccRuleAttachmentRead(context, d, meta) -} - -func resourceIBMSccRuleAttachmentDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - deleteRuleAttachmentOptions := &configurationgovernancev1.DeleteRuleAttachmentOptions{} - - parts, err := flex.SepIdParts(d.Id(), "/") - if err != nil { - return diag.FromErr(err) - } - - deleteRuleAttachmentOptions.SetRuleID(parts[0]) - deleteRuleAttachmentOptions.SetAttachmentID(parts[1]) - - response, err := configurationGovernanceClient.DeleteRuleAttachmentWithContext(context, deleteRuleAttachmentOptions) - if err != nil { - log.Printf("[DEBUG] DeleteRuleAttachmentWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteRuleAttachmentWithContext failed %s\n%s", err, response)) - } - - d.SetId("") - - return nil -} - -func resourceIBMSccRuleAttachmentMapToRuleAttachmentRequest(d *schema.ResourceData) (*configurationgovernancev1.RuleAttachmentRequest, error) { - model := &configurationgovernancev1.RuleAttachmentRequest{} - model.AccountID = core.StringPtr(d.Get("account_id").(string)) - includedScopeList := d.Get("included_scope").([]interface{}) - IncludedScopeModel, err := resourceIBMSccRuleAttachmentMapToRuleScope(includedScopeList[0].(map[string]interface{})) - if err != nil { - return model, err - } - model.IncludedScope = IncludedScopeModel - if d.Get("excluded_scopes") != nil { - excludedScopes := []configurationgovernancev1.RuleScope{} - for _, excludedScopesItem := range d.Get("excluded_scopes").([]interface{}) { - excludedScopesItemModel, err := resourceIBMSccRuleAttachmentMapToRuleScope(excludedScopesItem.(map[string]interface{})) - if err != nil { - return model, err - } - excludedScopes = append(excludedScopes, *excludedScopesItemModel) - } - model.ExcludedScopes = excludedScopes - } - return model, nil -} - -func resourceIBMSccRuleAttachmentMapToRuleScope(modelMap map[string]interface{}) (*configurationgovernancev1.RuleScope, error) { - model := &configurationgovernancev1.RuleScope{} - if modelMap["note"] != nil { - model.Note = core.StringPtr(modelMap["note"].(string)) - } - model.ScopeID = core.StringPtr(modelMap["scope_id"].(string)) - model.ScopeType = core.StringPtr(modelMap["scope_type"].(string)) - return model, nil -} - -func resourceIBMSccRuleAttachmentRuleAttachmentRequestToMap(model *configurationgovernancev1.RuleAttachmentRequest) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - modelMap["account_id"] = model.AccountID - includedScopeMap, err := resourceIBMSccRuleAttachmentRuleScopeToMap(model.IncludedScope) - if err != nil { - return modelMap, err - } - modelMap["included_scope"] = []map[string]interface{}{includedScopeMap} - if model.ExcludedScopes != nil { - excludedScopes := []map[string]interface{}{} - for _, excludedScopesItem := range model.ExcludedScopes { - excludedScopesItemMap, err := resourceIBMSccRuleAttachmentRuleScopeToMap(&excludedScopesItem) - if err != nil { - return modelMap, err - } - excludedScopes = append(excludedScopes, excludedScopesItemMap) - } - modelMap["excluded_scopes"] = excludedScopes - } - return modelMap, nil -} - -func resourceIBMSccRuleAttachmentRuleScopeToMap(model *configurationgovernancev1.RuleScope) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - if model.Note != nil { - modelMap["note"] = model.Note } - modelMap["scope_id"] = model.ScopeID - modelMap["scope_type"] = model.ScopeType - return modelMap, nil } diff --git a/ibm/service/scc/resource_ibm_scc_rule_attachment_test.go b/ibm/service/scc/resource_ibm_scc_rule_attachment_test.go deleted file mode 100644 index 5715a042a4..0000000000 --- a/ibm/service/scc/resource_ibm_scc_rule_attachment_test.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc_test - -import ( - "fmt" - "os" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" - - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" - "github.com/IBM/scc-go-sdk/v3/configurationgovernancev1" -) - -func TestAccIBMSccRuleAttachmentBasic(t *testing.T) { - var conf configurationgovernancev1.RuleAttachment - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - CheckDestroy: testAccCheckIBMSccRuleAttachmentDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckIBMSccRuleAttachmentConfigBasic(), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckIBMSccRuleAttachmentExists("ibm_scc_rule_attachment.scc_rule_attachment", conf), - ), - }, - resource.TestStep{ - ResourceName: "ibm_scc_rule_attachment.scc_rule_attachment", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func testAccCheckIBMSccRuleAttachmentConfigBasic() string { - account_id := os.Getenv("SCC_GOVERNANCE_ACCOUNT_ID") - resource_group_id := os.Getenv("IBM_SCC_RESOURCE_GROUP") - return fmt.Sprintf(` - - resource "ibm_scc_rule" "scc_rule" { - account_id = "%s" - name = "scc_tf_sample_rule" - description = "description" - target { - service_name = "cloud-object-storage" - resource_kind = "bucket" - additional_target_attributes { - name = "location" - value = "us-south" - operator = "string_equals" - } - } - labels = ["test1", "test2"] - required_config { - description = "test config" - or { - property = "location" - operator = "string_equals" - value = "us-south" - } - or { - property = "location" - operator = "string_equals" - value = "us-east" - } - } - enforcement_actions { - action = "disallow" - } - } - - resource "ibm_scc_rule_attachment" "scc_rule_attachment" { - rule_id = ibm_scc_rule.scc_rule.id - account_id = "%s" - included_scope { - note = "note" - scope_id = "%s" - scope_type = "account" - } - excluded_scopes { - note = "note" - scope_id = "%s" - scope_type = "account.resource_group" - } - depends_on = [ - ibm_scc_rule.scc_rule - ] - } - `, account_id, account_id, account_id, resource_group_id) -} - -func testAccCheckIBMSccRuleAttachmentExists(n string, obj configurationgovernancev1.RuleAttachment) resource.TestCheckFunc { - - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - configurationGovernanceClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return err - } - - getRuleAttachmentOptions := &configurationgovernancev1.GetRuleAttachmentOptions{} - parts, err := flex.SepIdParts(rs.Primary.ID, "/") - if err != nil { - return err - } - - ruleID := parts[0] - getRuleAttachmentOptions.SetRuleID(ruleID) - getRuleAttachmentOptions.SetAttachmentID(parts[1]) - - ruleAttachment, _, err := configurationGovernanceClient.GetRuleAttachment(getRuleAttachmentOptions) - if err != nil { - return err - } - - if *ruleAttachment.RuleID != ruleID { - return fmt.Errorf( - "ibm_scc_rule_attachment.scc_rule_attachment: Attribute 'rule_id' expected %#v, got %#v", - ruleID, - ruleAttachment.RuleID, - ) - } - - obj = *ruleAttachment - return nil - } -} - -func testAccCheckIBMSccRuleAttachmentDestroy(s *terraform.State) error { - configurationGovernanceClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return err - } - for _, rs := range s.RootModule().Resources { - if rs.Type != "ibm_scc_rule_attachment" { - continue - } - - getRuleAttachmentOptions := &configurationgovernancev1.GetRuleAttachmentOptions{} - - parts, err := flex.SepIdParts(rs.Primary.ID, "/") - if err != nil { - return err - } - - getRuleAttachmentOptions.SetRuleID(parts[0]) - getRuleAttachmentOptions.SetAttachmentID(parts[1]) - - // Try to find the key - _, response, err := configurationGovernanceClient.GetRuleAttachment(getRuleAttachmentOptions) - - if err == nil { - return fmt.Errorf("scc_rule_attachment still exists: %s", rs.Primary.ID) - } else if response.StatusCode != 404 { - return fmt.Errorf("Error checking for scc_rule_attachment (%s) has been destroyed: %s", rs.Primary.ID, err) - } - } - - return nil -} diff --git a/ibm/service/scc/resource_ibm_scc_rule_attachment_validator.go b/ibm/service/scc/resource_ibm_scc_rule_attachment_validator.go deleted file mode 100644 index ee1079506b..0000000000 --- a/ibm/service/scc/resource_ibm_scc_rule_attachment_validator.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc - -import ( - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" -) - -func ResourceIBMSccRuleAttachmentValidator() *validate.ResourceValidator { - validateSchema := make([]validate.ValidateSchema, 0) - validateSchema = append(validateSchema, - validate.ValidateSchema{ - Identifier: "scope_type", - ValidateFunctionIdentifier: validate.ValidateAllowedStringValue, - Type: validate.TypeString, - Required: true, - AllowedValues: "enterprise, enterprise.account_group, enterprise.account, account, account.resource_group", - }, - ) - - resourceValidator := validate.ResourceValidator{ResourceName: "ibm_scc_rule_attachment", Schema: validateSchema} - return &resourceValidator -} diff --git a/ibm/service/scc/resource_ibm_scc_rule_test.go b/ibm/service/scc/resource_ibm_scc_rule_test.go index d1261cd949..c3c17cdc63 100644 --- a/ibm/service/scc/resource_ibm_scc_rule_test.go +++ b/ibm/service/scc/resource_ibm_scc_rule_test.go @@ -1,37 +1,77 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package scc_test import ( "fmt" - "os" "testing" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM/scc-go-sdk/v3/configurationgovernancev1" + "github.com/IBM/scc-go-sdk/v5/securityandcompliancecenterapiv3" ) -func TestAccIBMSccRuleBasic(t *testing.T) { - var conf configurationgovernancev1.Rule +func TestAccIbmSccRuleBasic(t *testing.T) { + var conf securityandcompliancecenterapiv3.Rule + description := fmt.Sprintf("tf_description_%d", acctest.RandIntRange(10, 100)) + descriptionUpdate := description resource.Test(t, resource.TestCase{ PreCheck: func() { acc.TestAccPreCheck(t) }, Providers: acc.TestAccProviders, - CheckDestroy: testAccCheckIBMSccRuleDestroy, + CheckDestroy: testAccCheckIbmSccRuleDestroy, Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckIBMSccRuleConfigBasic(), + { + Config: testAccCheckIbmSccRuleConfigBasic(description), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckIBMSccRuleExists("ibm_scc_rule.scc_rule", conf), + testAccCheckIbmSccRuleExists("ibm_scc_rule.scc_rule_instance", conf), + resource.TestCheckResourceAttr("ibm_scc_rule.scc_rule_instance", "description", description), ), }, - resource.TestStep{ - ResourceName: "ibm_scc_rule.scc_rule", + { + Config: testAccCheckIbmSccRuleConfigBasic(descriptionUpdate), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("ibm_scc_rule.scc_rule_instance", "description", descriptionUpdate), + ), + }, + }, + }) +} + +func TestAccIbmSccRuleAllArgs(t *testing.T) { + var conf securityandcompliancecenterapiv3.Rule + description := fmt.Sprintf("tf_description_%d", acctest.RandIntRange(10, 100)) + version := fmt.Sprintf("0.0.%d", acctest.RandIntRange(10, 100)) + descriptionUpdate := fmt.Sprintf("tf_description_%d", acctest.RandIntRange(10, 100)) + versionUpdate := fmt.Sprintf("0.0.%d", acctest.RandIntRange(2, 100)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmSccRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmSccRuleConfig(description, version), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmSccRuleExists("ibm_scc_rule.scc_rule_instance", conf), + resource.TestCheckResourceAttr("ibm_scc_rule.scc_rule_instance", "description", description), + resource.TestCheckResourceAttr("ibm_scc_rule.scc_rule_instance", "version", version), + ), + }, + { + Config: testAccCheckIbmSccRuleConfig(descriptionUpdate, versionUpdate), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("ibm_scc_rule.scc_rule_instance", "description", descriptionUpdate), + resource.TestCheckResourceAttr("ibm_scc_rule.scc_rule_instance", "version", versionUpdate), + ), + }, + { + ResourceName: "ibm_scc_rule.scc_rule_instance", ImportState: true, ImportStateVerify: true, }, @@ -39,63 +79,101 @@ func TestAccIBMSccRuleBasic(t *testing.T) { }) } -func testAccCheckIBMSccRuleConfigBasic() string { - // Check if the user has a SCC_GOVERANCE_ACCOUNT_ID - account_id := os.Getenv("SCC_GOVERNANCE_ACCOUNT_ID") +func testAccCheckIbmSccRuleConfigBasic(description string) string { return fmt.Sprintf(` - - resource "ibm_scc_rule" "scc_rule" { - account_id = "%s" - name = "scc_tf_sample_rule" - description = "description" - target { - service_name = "cloud-object-storage" - resource_kind = "bucket" - additional_target_attributes { - name = "location" - value = "us-south" - operator = "string_equals" - } - } - labels = ["test1", "test2"] - required_config { - description = "test config" - or { - property = "location" - operator = "string_equals" - value = "us-west" + resource "ibm_scc_rule" "scc_rule_instance" { + description = "%s" + version = "0.0.1" + target { + service_name = "cloud-object-storage" + resource_kind = "bucket" + additional_target_attributes { + name = "location" + operator = "string_equals" + value = "us-south" + } } - or { - property = "location" - operator = "string_equals" - value = "us-east" + required_config { + and { + or { + description = "description" + property = "storage_class" + operator = "string_equals" + value = "smart" + } + or { + description = "description" + property = "storage_class" + operator = "string_equals" + value = "cold" + } + } } - } - enforcement_actions { - action = "disallow" - } - } - `, account_id) + } + `, description) } -func testAccCheckIBMSccRuleExists(n string, obj configurationgovernancev1.Rule) resource.TestCheckFunc { +func testAccCheckIbmSccRuleConfig(description string, version string) string { + return fmt.Sprintf(` + + resource "ibm_scc_rule" "scc_rule_instance" { + description = "%s" + version = "%s" + import { + parameters { + name = "name" + display_name = "display_name" + description = "description" + type = "string" + } + } + target { + service_name = "cloud-object-storage" + resource_kind = "bucket" + additional_target_attributes { + name = "location" + operator = "string_equals" + value = "$${name}" + } + } + required_config { + and { + or { + description = "description" + property = "storage_class" + operator = "string_equals" + value = "smart" + } + or { + description = "description" + property = "storage_class" + operator = "string_equals" + value = "cold" + } + } + } + labels = ["FIXME"] + } + `, description, version) +} +func testAccCheckIbmSccRuleExists(n string, obj securityandcompliancecenterapiv3.Rule) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } - configurationGovernanceClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).ConfigurationGovernanceV1() + configManagerClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).SecurityAndComplianceCenterV3() if err != nil { return err } - getRuleOptions := &configurationgovernancev1.GetRuleOptions{} + getRuleOptions := &securityandcompliancecenterapiv3.GetRuleOptions{} getRuleOptions.SetRuleID(rs.Primary.ID) - rule, _, err := configurationGovernanceClient.GetRule(getRuleOptions) + rule, _, err := configManagerClient.GetRule(getRuleOptions) if err != nil { return err } @@ -105,8 +183,8 @@ func testAccCheckIBMSccRuleExists(n string, obj configurationgovernancev1.Rule) } } -func testAccCheckIBMSccRuleDestroy(s *terraform.State) error { - configurationGovernanceClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).ConfigurationGovernanceV1() +func testAccCheckIbmSccRuleDestroy(s *terraform.State) error { + configManagerClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).SecurityAndComplianceCenterV3() if err != nil { return err } @@ -115,12 +193,12 @@ func testAccCheckIBMSccRuleDestroy(s *terraform.State) error { continue } - getRuleOptions := &configurationgovernancev1.GetRuleOptions{} + getRuleOptions := &securityandcompliancecenterapiv3.GetRuleOptions{} getRuleOptions.SetRuleID(rs.Primary.ID) // Try to find the key - _, response, err := configurationGovernanceClient.GetRule(getRuleOptions) + _, response, err := configManagerClient.GetRule(getRuleOptions) if err == nil { return fmt.Errorf("scc_rule still exists: %s", rs.Primary.ID) diff --git a/ibm/service/scc/resource_ibm_scc_rule_validator.go b/ibm/service/scc/resource_ibm_scc_rule_validator.go deleted file mode 100644 index d3ef2f6673..0000000000 --- a/ibm/service/scc/resource_ibm_scc_rule_validator.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc - -import ( - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" -) - -func ResourceIBMSccRuleValidator() *validate.ResourceValidator { - - validateSchemaList := make([]validate.ValidateSchema, 2) - validateSchemaList = append(validateSchemaList, validateIBMSccRuleReqConfig()) - resourceValidator := validate.ResourceValidator{ - ResourceName: "ibm_scc_rule", - Schema: validateSchemaList, - } - return &resourceValidator -} - -func validateIBMSccRuleReqConfig() validate.ValidateSchema { - validateSchema := validate.ValidateSchema{ - Identifier: "operator", - ValidateFunctionIdentifier: validate.ValidateAllowedStringValue, - Type: validate.TypeString, - Required: true, - AllowedValues: "is_true, is_false, is_empty, is_not_empty, string_equals, string_not_equals, string_match, string_not_match, num_equals, num_not_equals, num_less_than, num_less_than_equals, num_greater_than, num_greater_than_equals", - } - return validateSchema -} diff --git a/ibm/service/scc/resource_ibm_scc_template.go b/ibm/service/scc/resource_ibm_scc_template.go index 318eb901d5..56e607c9a3 100644 --- a/ibm/service/scc/resource_ibm_scc_template.go +++ b/ibm/service/scc/resource_ibm_scc_template.go @@ -5,402 +5,20 @@ package scc import ( "context" - "fmt" - "log" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" - "github.com/IBM/go-sdk-core/v5/core" - "github.com/IBM/scc-go-sdk/v3/configurationgovernancev1" ) func ResourceIBMSccTemplate() *schema.Resource { return &schema.Resource{ - CreateContext: resourceIBMSccTemplateCreate, - ReadContext: resourceIBMSccTemplateRead, - UpdateContext: resourceIBMSccTemplateUpdate, - DeleteContext: resourceIBMSccTemplateDelete, - Importer: &schema.ResourceImporter{}, - - Schema: map[string]*schema.Schema{ - "account_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "Your IBM Cloud account ID.", - }, - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "A human-readablse alias to assign to your template.", - ValidateFunc: validate.InvokeValidator("ibm_scc_template", "name"), - }, - "description": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "An extended description of your template.", - ValidateFunc: validate.InvokeValidator("ibm_scc_template", "description"), - }, - "template_id": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The UUID that uniquely identifies the template.", - }, - "version": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - "target": &schema.Schema{ - Type: schema.TypeList, - MinItems: 1, - MaxItems: 1, - Required: true, - Description: "The properties that describe the resource that you want to targetwith the rule or template.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "service_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The programmatic name of the IBM Cloud service that you want to target with the rule or template.", - ValidateFunc: validate.InvokeValidator("ibm_scc_template", "service_name"), - }, - "resource_kind": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The type of resource that you want to target.", - }, - "additional_target_attributes": &schema.Schema{ - Type: schema.TypeList, - Optional: true, - Description: "An extra qualifier for the resource kind. When you include additional attributes, only the resources that match the definition are included in the rule or template.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The name of the additional attribute that you want to use to further qualify the target.Options differ depending on the service or resource that you are targeting with a rule or template. For more information, refer to the service documentation.", - }, - "value": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The value that you want to apply to `name` field.Options differ depending on the rule or template that you configure. For more information, refer to the service documentation.", - }, - }, - }, - }, - }, - }, - }, - "customized_defaults": &schema.Schema{ - Type: schema.TypeList, - Required: true, - Description: "A list of default property values to apply to your template.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "property": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The name of the resource property that you want to configure.Property options differ depending on the service or resource that you are targeting with a template. To view a list of properties that are compatible with templates, refer to the service documentation.", - }, - "value": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The custom value that you want to apply as the default for the resource property in the `name` field.This value is used to to override the default value that is provided by IBM when a resource is created. Value options differ depending on the resource that you are configuring. To learn more about your options, refer to the service documentation.", - }, - }, - }, - }, + CreateContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_template has been deprecated") + }, + ReadContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_template has been deprecated") + }, + DeleteContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_template has been deprecated") }, } } - -func resourceIBMSccTemplateCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - createTemplatesOptions := &configurationgovernancev1.CreateTemplatesOptions{} - - var template []configurationgovernancev1.CreateTemplateRequest - templateItem, err := resourceIBMSccTemplateMapToCreateTemplateRequest(d) - template = append(template, *templateItem) - createTemplatesOptions.SetTemplates(template) - - createTemplatesResponse, response, err := configurationGovernanceClient.CreateTemplatesWithContext(context, createTemplatesOptions) - if err != nil || response.GetStatusCode() == 207 || response.StatusCode > 300 { - log.Printf("[DEBUG] CreateTemplatesWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateTemplatesWithContext failed %s\n%s", err, response)) - } - - d.SetId(*createTemplatesResponse.Templates[0].Template.TemplateID) - - return resourceIBMSccTemplateRead(context, d, meta) -} - -func resourceIBMSccTemplateRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - getTemplateOptions := &configurationgovernancev1.GetTemplateOptions{} - - getTemplateOptions.SetTemplateID(d.Id()) - - templateResponse, response, err := configurationGovernanceClient.GetTemplateWithContext(context, getTemplateOptions) - if err != nil { - if response != nil && response.StatusCode == 404 { - d.SetId("") - return nil - } - log.Printf("[DEBUG] GetTemplateWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetTemplateWithContext failed %s\n%s", err, response)) - } - - // TODO: handle argument of type []interface{} - if err = d.Set("account_id", templateResponse.AccountID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) - } - if err = d.Set("name", templateResponse.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } - if err = d.Set("description", templateResponse.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) - } - targetMap, err := resourceIBMSccTemplateSimpleTargetResourceToMap(templateResponse.Target) - if err != nil { - return diag.FromErr(err) - } - if err = d.Set("target", []map[string]interface{}{targetMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting target: %s", err)) - } - - customizedDefaults := []map[string]interface{}{} - for _, customizedDefaultsItem := range templateResponse.CustomizedDefaults { - customizedDefaultsItemMap, err := resourceIBMSccTemplateTemplateCustomizedDefaultPropertyToMap(&customizedDefaultsItem) - if err != nil { - return diag.FromErr(err) - } - customizedDefaults = append(customizedDefaults, customizedDefaultsItemMap) - } - if err = d.Set("customized_defaults", customizedDefaults); err != nil { - return diag.FromErr(fmt.Errorf("Error setting customized_defaults: %s", err)) - } - if err = d.Set("version", response.Headers.Get("Etag")); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version: %s", err)) - } - - return nil -} - -func resourceIBMSccTemplateUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - updateTemplateOptions := &configurationgovernancev1.UpdateTemplateOptions{} - - updateTemplateOptions.SetTemplateID(d.Id()) - - hasChange := d.HasChange("name") || d.HasChange("description") || - d.HasChange("target") || d.HasChange("customized_defaults") - - if hasChange { - updateTemplateOptions.SetIfMatch(d.Get("version").(string)) - updateTemplateOptions.SetName(d.Get("name").(string)) - updateTemplateOptions.SetAccountID(d.Get("account_id").(string)) - updateTemplateOptions.SetDescription(d.Get("description").(string)) - - target, err := resourceIBMSccTemplateMapToSimpleTargetResource(d.Get("target.0").(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - updateTemplateOptions.SetTarget(target) - - customizedDefaults := []configurationgovernancev1.TemplateCustomizedDefaultProperty{} - for _, customizedDefaultsItem := range d.Get("customized_defaults").([]interface{}) { - if customizedDefaultsItem != nil { - customizedDefaultsItemModel, err := resourceIBMSccTemplateMapToTemplateCustomizedDefaultProperty(customizedDefaultsItem.(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - customizedDefaults = append(customizedDefaults, *customizedDefaultsItemModel) - } - } - updateTemplateOptions.SetCustomizedDefaults(customizedDefaults) - - _, response, err := configurationGovernanceClient.UpdateTemplateWithContext(context, updateTemplateOptions) - if err != nil { - log.Printf("[DEBUG] UpdateTemplateWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateTemplateWithContext failed %s\n%s", err, response)) - } - } - - return resourceIBMSccTemplateRead(context, d, meta) -} - -func resourceIBMSccTemplateDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - deleteTemplateOptions := &configurationgovernancev1.DeleteTemplateOptions{} - - deleteTemplateOptions.SetTemplateID(d.Id()) - - response, err := configurationGovernanceClient.DeleteTemplateWithContext(context, deleteTemplateOptions) - if err != nil { - log.Printf("[DEBUG] DeleteTemplateWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteTemplateWithContext failed %s\n%s", err, response)) - } - - d.SetId("") - - return nil -} - -func resourceIBMSccTemplateMapToCreateTemplateRequest(d *schema.ResourceData) (*configurationgovernancev1.CreateTemplateRequest, error) { - model := &configurationgovernancev1.CreateTemplateRequest{} - if d.Get("request_id") != nil { - model.RequestID = core.StringPtr(d.Get("request_id").(string)) - } - TemplateModel, err := resourceIBMSccTemplateMapToTemplate(d) - if err != nil { - return model, err - } - model.Template = TemplateModel - return model, nil -} - -func resourceIBMSccTemplateMapToTemplate(d *schema.ResourceData) (*configurationgovernancev1.Template, error) { - model := &configurationgovernancev1.Template{} - model.AccountID = core.StringPtr(d.Get("account_id").(string)) - model.Name = core.StringPtr(d.Get("name").(string)) - model.Description = core.StringPtr(d.Get("description").(string)) - if d.Get("template_id") != nil { - model.TemplateID = core.StringPtr(d.Get("template_id").(string)) - } - targetList := d.Get("target").([]interface{}) - TargetModel, err := resourceIBMSccTemplateMapToSimpleTargetResource(targetList[0].(map[string]interface{})) - if err != nil { - return model, err - } - model.Target = TargetModel - customizedDefaults := []configurationgovernancev1.TemplateCustomizedDefaultProperty{} - for _, customizedDefaultsItem := range d.Get("customized_defaults").([]interface{}) { - customizedDefaultsItemModel, err := resourceIBMSccTemplateMapToTemplateCustomizedDefaultProperty(customizedDefaultsItem.(map[string]interface{})) - if err != nil { - return model, err - } - customizedDefaults = append(customizedDefaults, *customizedDefaultsItemModel) - } - model.CustomizedDefaults = customizedDefaults - return model, nil -} - -func resourceIBMSccTemplateMapToSimpleTargetResource(modelMap map[string]interface{}) (*configurationgovernancev1.SimpleTargetResource, error) { - model := &configurationgovernancev1.SimpleTargetResource{} - model.ServiceName = core.StringPtr(modelMap["service_name"].(string)) - model.ResourceKind = core.StringPtr(modelMap["resource_kind"].(string)) - if modelMap["additional_target_attributes"] != nil { - additionalTargetAttributes := []configurationgovernancev1.BaseTargetAttribute{} - for _, additionalTargetAttributesItem := range modelMap["additional_target_attributes"].([]interface{}) { - additionalTargetAttributesItemModel, err := resourceIBMSccTemplateMapToBaseTargetAttribute(additionalTargetAttributesItem.(map[string]interface{})) - if err != nil { - return model, err - } - additionalTargetAttributes = append(additionalTargetAttributes, *additionalTargetAttributesItemModel) - } - model.AdditionalTargetAttributes = additionalTargetAttributes - } - return model, nil -} - -func resourceIBMSccTemplateMapToBaseTargetAttribute(modelMap map[string]interface{}) (*configurationgovernancev1.BaseTargetAttribute, error) { - model := &configurationgovernancev1.BaseTargetAttribute{} - model.Name = core.StringPtr(modelMap["name"].(string)) - model.Value = core.StringPtr(modelMap["value"].(string)) - return model, nil -} - -func resourceIBMSccTemplateMapToTemplateCustomizedDefaultProperty(modelMap map[string]interface{}) (*configurationgovernancev1.TemplateCustomizedDefaultProperty, error) { - model := &configurationgovernancev1.TemplateCustomizedDefaultProperty{} - model.Property = core.StringPtr(modelMap["property"].(string)) - model.Value = core.StringPtr(modelMap["value"].(string)) - return model, nil -} - -func resourceIBMSccTemplateCreateTemplateRequestToMap(model *configurationgovernancev1.CreateTemplateRequest) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - if model.RequestID != nil { - modelMap["request_id"] = model.RequestID - } - templateMap, err := resourceIBMSccTemplateTemplateToMap(model.Template) - if err != nil { - return modelMap, err - } - modelMap["template"] = []map[string]interface{}{templateMap} - return modelMap, nil -} - -func resourceIBMSccTemplateTemplateToMap(model *configurationgovernancev1.Template) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - modelMap["account_id"] = model.AccountID - modelMap["name"] = model.Name - modelMap["description"] = model.Description - if model.TemplateID != nil { - modelMap["template_id"] = model.TemplateID - } - targetMap, err := resourceIBMSccTemplateSimpleTargetResourceToMap(model.Target) - if err != nil { - return modelMap, err - } - modelMap["target"] = []map[string]interface{}{targetMap} - customizedDefaults := []map[string]interface{}{} - for _, customizedDefaultsItem := range model.CustomizedDefaults { - customizedDefaultsItemMap, err := resourceIBMSccTemplateTemplateCustomizedDefaultPropertyToMap(&customizedDefaultsItem) - if err != nil { - return modelMap, err - } - customizedDefaults = append(customizedDefaults, customizedDefaultsItemMap) - } - modelMap["customized_defaults"] = customizedDefaults - return modelMap, nil -} - -func resourceIBMSccTemplateSimpleTargetResourceToMap(model *configurationgovernancev1.SimpleTargetResource) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - modelMap["service_name"] = model.ServiceName - modelMap["resource_kind"] = model.ResourceKind - if model.AdditionalTargetAttributes != nil { - additionalTargetAttributes := []map[string]interface{}{} - for _, additionalTargetAttributesItem := range model.AdditionalTargetAttributes { - additionalTargetAttributesItemMap, err := resourceIBMSccTemplateBaseTargetAttributeToMap(&additionalTargetAttributesItem) - if err != nil { - return modelMap, err - } - additionalTargetAttributes = append(additionalTargetAttributes, additionalTargetAttributesItemMap) - } - modelMap["additional_target_attributes"] = additionalTargetAttributes - } - return modelMap, nil -} - -func resourceIBMSccTemplateBaseTargetAttributeToMap(model *configurationgovernancev1.BaseTargetAttribute) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - modelMap["name"] = model.Name - modelMap["value"] = model.Value - return modelMap, nil -} - -func resourceIBMSccTemplateTemplateCustomizedDefaultPropertyToMap(model *configurationgovernancev1.TemplateCustomizedDefaultProperty) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - modelMap["property"] = model.Property - modelMap["value"] = model.Value - return modelMap, nil -} diff --git a/ibm/service/scc/resource_ibm_scc_template_attachment.go b/ibm/service/scc/resource_ibm_scc_template_attachment.go index 28339a0045..8696580a4d 100644 --- a/ibm/service/scc/resource_ibm_scc_template_attachment.go +++ b/ibm/service/scc/resource_ibm_scc_template_attachment.go @@ -5,334 +5,20 @@ package scc import ( "context" - "fmt" - "log" - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" - "github.com/IBM/go-sdk-core/v5/core" - "github.com/IBM/scc-go-sdk/v3/configurationgovernancev1" ) func ResourceIBMSccTemplateAttachment() *schema.Resource { return &schema.Resource{ - CreateContext: resourceIBMSccTemplateAttachmentCreate, - ReadContext: resourceIBMSccTemplateAttachmentRead, - UpdateContext: resourceIBMSccTemplateAttachmentUpdate, - DeleteContext: resourceIBMSccTemplateAttachmentDelete, - Importer: &schema.ResourceImporter{}, - - Schema: map[string]*schema.Schema{ - "attachment_id": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - Description: "The UUID that uniquely identifies the template.", - }, - "template_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The UUID that uniquely identifies the template.", - }, - "account_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "Your IBM Cloud account ID.", - }, - "included_scope": &schema.Schema{ - Type: schema.TypeList, - Required: true, - Description: "The extent at which the template can be attached across your accounts.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "note": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "A short description or alias to assign to the scope.", - }, - "scope_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The ID of the scope, such as an enterprise, account, or account group, where you want to apply the customized defaults that are associated with a template.", - }, - "scope_type": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The type of scope.", - ValidateFunc: validate.InvokeValidator("ibm_scc_template_attachment", "scope_type"), - }, - }, - }, - }, - "excluded_scopes": &schema.Schema{ - Type: schema.TypeList, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "note": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Description: "A short description or alias to assign to the scope.", - }, - "scope_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The ID of the scope, such as an enterprise, account, or account group, where you want to apply the customized defaults that are associated with a template.", - }, - "scope_type": &schema.Schema{ - Type: schema.TypeString, - Required: true, - Description: "The type of scope.", - ValidateFunc: validate.InvokeValidator("ibm_scc_template_attachment", "scope_type"), - }, - }, - }, - }, - "version": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, + CreateContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_template_attachment has been deprecated") + }, + ReadContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_template_attachment has been deprecated") + }, + DeleteContext: func(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return diag.Errorf("resource ibm_scc_template_attachment has been deprecated") }, } } - -func resourceIBMSccTemplateAttachmentCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - createTemplateAttachmentsOptions := &configurationgovernancev1.CreateTemplateAttachmentsOptions{} - - createTemplateAttachmentsOptions.SetTemplateID(d.Get("template_id").(string)) - var attachment []configurationgovernancev1.TemplateAttachmentRequest - attachmentItem, err := resourceIBMSccTemplateAttachmentMapToTemplateAttachmentRequest(d) - if err != nil { - return diag.FromErr(err) - } - attachment = append(attachment, *attachmentItem) - createTemplateAttachmentsOptions.SetAttachments(attachment) - - createTemplateAttachmentsResponse, response, err := configurationGovernanceClient.CreateTemplateAttachmentsWithContext(context, createTemplateAttachmentsOptions) - if err != nil || response.StatusCode > 300 { - log.Printf("[DEBUG] CreateTemplateAttachmentsWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateTemplateAttachmentsWithContext failed %s\n%s", err, response)) - } - - d.SetId(fmt.Sprintf("%s/%s", *createTemplateAttachmentsOptions.TemplateID, *createTemplateAttachmentsResponse.Attachments[0].AttachmentID)) - - return resourceIBMSccTemplateAttachmentRead(context, d, meta) -} - -func resourceIBMSccTemplateAttachmentRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - getTemplateAttachmentOptions := &configurationgovernancev1.GetTemplateAttachmentOptions{} - - parts, err := flex.SepIdParts(d.Id(), "/") - if err != nil { - return diag.FromErr(err) - } - - getTemplateAttachmentOptions.SetTemplateID(parts[0]) - getTemplateAttachmentOptions.SetAttachmentID(parts[1]) - - templateAttachment, response, err := configurationGovernanceClient.GetTemplateAttachmentWithContext(context, getTemplateAttachmentOptions) - if err != nil { - if response != nil && response.StatusCode == 404 { - d.SetId("") - return nil - } - log.Printf("[DEBUG] GetTemplateAttachmentWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetTemplateAttachmentWithContext failed %s\n%s", err, response)) - } - - // TODO: handle argument of type []interface{} - if err = d.Set("template_id", templateAttachment.TemplateID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting template_id: %s", err)) - } - if err = d.Set("account_id", templateAttachment.AccountID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) - } - includedScopeMap, err := resourceIBMSccTemplateAttachmentTemplateScopeToMap(templateAttachment.IncludedScope) - if err != nil { - return diag.FromErr(err) - } - if err = d.Set("included_scope", []map[string]interface{}{includedScopeMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting included_scope: %s", err)) - } - - excludedScope := []map[string]interface{}{} - if templateAttachment.ExcludedScopes != nil { - for _, excludedScopeItem := range templateAttachment.ExcludedScopes { - excludedScopeItemMap, err := resourceIBMSccTemplateAttachmentTemplateScopeToMap(&excludedScopeItem) - if err != nil { - return diag.FromErr(err) - } - excludedScope = append(excludedScope, excludedScopeItemMap) - } - } - if err = d.Set("excluded_scopes", excludedScope); err != nil { - return diag.FromErr(fmt.Errorf("Error setting excluded_scopes: %s", err)) - } - if err = d.Set("version", response.Headers.Get("Etag")); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version: %s", err)) - } - - return nil -} - -func resourceIBMSccTemplateAttachmentUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - updateTemplateAttachmentOptions := &configurationgovernancev1.UpdateTemplateAttachmentOptions{} - - parts, err := flex.SepIdParts(d.Id(), "/") - if err != nil { - return diag.FromErr(err) - } - - updateTemplateAttachmentOptions.SetTemplateID(parts[0]) - updateTemplateAttachmentOptions.SetAttachmentID(parts[1]) - - if d.HasChange("template_id") { - return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ - " The resource must be re-created to update this property.", "template_id")) - } - - hasChange := d.HasChange("included_scope") || d.HasChange("excluded_scopes") - - updateTemplateAttachmentOptions.SetIfMatch(d.Get("version").(string)) - - if hasChange { - updateTemplateAttachmentOptions.SetIfMatch(d.Get("version").(string)) - updateTemplateAttachmentOptions.SetTemplateID(d.Get("template_id").(string)) - updateTemplateAttachmentOptions.SetAccountID(d.Get("account_id").(string)) - - includedScope, err := resourceIBMSccTemplateAttachmentMapToTemplateScope(d.Get("included_scope.0").(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - updateTemplateAttachmentOptions.SetIncludedScope(includedScope) - - excludedScopes := []configurationgovernancev1.TemplateScope{} - if d.Get("excluded_scopes") != nil { - for _, scopeItem := range d.Get("excluded_scopes").([]interface{}) { - excludedScope, err := resourceIBMSccTemplateAttachmentMapToTemplateScope(scopeItem.(map[string]interface{})) - if err != nil { - return diag.FromErr(err) - } - excludedScopes = append(excludedScopes, *excludedScope) - } - } - updateTemplateAttachmentOptions.SetExcludedScopes(excludedScopes) - - _, response, err := configurationGovernanceClient.UpdateTemplateAttachmentWithContext(context, updateTemplateAttachmentOptions) - if err != nil { - log.Printf("[DEBUG] UpdateTemplateAttachmentWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateTemplateAttachmentWithContext failed %s\n%s", err, response)) - } - } - - return resourceIBMSccTemplateAttachmentRead(context, d, meta) -} - -func resourceIBMSccTemplateAttachmentDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - configurationGovernanceClient, err := meta.(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return diag.FromErr(err) - } - - deleteTemplateAttachmentOptions := &configurationgovernancev1.DeleteTemplateAttachmentOptions{} - - parts, err := flex.SepIdParts(d.Id(), "/") - if err != nil { - return diag.FromErr(err) - } - - deleteTemplateAttachmentOptions.SetTemplateID(parts[0]) - deleteTemplateAttachmentOptions.SetAttachmentID(parts[1]) - - response, err := configurationGovernanceClient.DeleteTemplateAttachmentWithContext(context, deleteTemplateAttachmentOptions) - if err != nil { - log.Printf("[DEBUG] DeleteTemplateAttachmentWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteTemplateAttachmentWithContext failed %s\n%s", err, response)) - } - - d.SetId("") - - return nil -} - -func resourceIBMSccTemplateAttachmentMapToTemplateAttachmentRequest(d *schema.ResourceData) (*configurationgovernancev1.TemplateAttachmentRequest, error) { - model := &configurationgovernancev1.TemplateAttachmentRequest{} - model.AccountID = core.StringPtr(d.Get("account_id").(string)) - IncludedScopeModel, err := resourceIBMSccTemplateAttachmentMapToTemplateScope(d.Get("included_scope.0").(map[string]interface{})) - if err != nil { - return model, err - } - model.IncludedScope = IncludedScopeModel - if d.Get("excluded_scopes") != nil { - excludedScopes := []configurationgovernancev1.TemplateScope{} - for _, excludedScopesItem := range d.Get("excluded_scopes").([]interface{}) { - excludedScopesItemModel, err := resourceIBMSccTemplateAttachmentMapToTemplateScope(excludedScopesItem.(map[string]interface{})) - if err != nil { - return model, err - } - excludedScopes = append(excludedScopes, *excludedScopesItemModel) - } - model.ExcludedScopes = excludedScopes - } - return model, nil -} - -func resourceIBMSccTemplateAttachmentMapToTemplateScope(modelMap map[string]interface{}) (*configurationgovernancev1.TemplateScope, error) { - model := &configurationgovernancev1.TemplateScope{} - if modelMap["note"] != nil { - model.Note = core.StringPtr(modelMap["note"].(string)) - } - model.ScopeID = core.StringPtr(modelMap["scope_id"].(string)) - model.ScopeType = core.StringPtr(modelMap["scope_type"].(string)) - return model, nil -} - -func resourceIBMSccTemplateAttachmentTemplateAttachmentRequestToMap(model *configurationgovernancev1.TemplateAttachmentRequest) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - modelMap["account_id"] = model.AccountID - includedScopeMap, err := resourceIBMSccTemplateAttachmentTemplateScopeToMap(model.IncludedScope) - if err != nil { - return modelMap, err - } - modelMap["included_scope"] = []map[string]interface{}{includedScopeMap} - if model.ExcludedScopes != nil { - excludedScopes := []map[string]interface{}{} - for _, excludedScopesItem := range model.ExcludedScopes { - excludedScopesItemMap, err := resourceIBMSccTemplateAttachmentTemplateScopeToMap(&excludedScopesItem) - if err != nil { - return modelMap, err - } - excludedScopes = append(excludedScopes, excludedScopesItemMap) - } - modelMap["excluded_scopes"] = excludedScopes - } - return modelMap, nil -} - -func resourceIBMSccTemplateAttachmentTemplateScopeToMap(model *configurationgovernancev1.TemplateScope) (map[string]interface{}, error) { - modelMap := make(map[string]interface{}) - if model.Note != nil { - modelMap["note"] = model.Note - } - modelMap["scope_id"] = model.ScopeID - modelMap["scope_type"] = model.ScopeType - return modelMap, nil -} diff --git a/ibm/service/scc/resource_ibm_scc_template_attachment_test.go b/ibm/service/scc/resource_ibm_scc_template_attachment_test.go deleted file mode 100644 index 8dab7ddf4b..0000000000 --- a/ibm/service/scc/resource_ibm_scc_template_attachment_test.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc_test - -import ( - "fmt" - "os" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" - - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" - "github.com/IBM/scc-go-sdk/v3/configurationgovernancev1" -) - -func TestAccIBMSccTemplateAttachmentBasic(t *testing.T) { - var conf configurationgovernancev1.TemplateAttachment - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - CheckDestroy: testAccCheckIBMSccTemplateAttachmentDestroy, - - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckIBMSccTemplateAttachmentConfigBasic(), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckIBMSccTemplateAttachmentExists("ibm_scc_template_attachment.scc_template_attachment", conf), - ), - }, - resource.TestStep{ - ResourceName: "ibm_scc_template_attachment.scc_template_attachment", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func testAccCheckIBMSccTemplateAttachmentConfigBasic() string { - account_id := os.Getenv("SCC_GOVERNANCE_ACCOUNT_ID") - resource_group_id := os.Getenv("IBM_SCC_RESOURCE_GROUP") - return fmt.Sprintf(` - resource "ibm_scc_template" "scc_template" { - account_id = "%s" - name = "Terraform template" - description = "description" - target { - service_name = "cloud-object-storage" - resource_kind = "bucket" - additional_target_attributes { - name = "location" - value = "us-south" - } - } - customized_defaults { - property = "activity_tracking.write_data_events" - value = "true" - } - } - - resource "ibm_scc_template_attachment" "scc_template_attachment" { - template_id = ibm_scc_template.scc_template.id - account_id = "%s" - included_scope { - note = "note" - scope_id = "%s" - scope_type = "account" - } - excluded_scopes { - note = "note" - scope_id = "%s" - scope_type = "account.resource_group" - } - depends_on = [ - ibm_scc_template.scc_template - ] - } - `, account_id, account_id, account_id, resource_group_id) -} - -func testAccCheckIBMSccTemplateAttachmentExists(n string, obj configurationgovernancev1.TemplateAttachment) resource.TestCheckFunc { - - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - configurationGovernanceClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return err - } - - getTemplateAttachmentOptions := &configurationgovernancev1.GetTemplateAttachmentOptions{} - - parts, err := flex.SepIdParts(rs.Primary.ID, "/") - if err != nil { - return err - } - - templateID := parts[0] - getTemplateAttachmentOptions.SetTemplateID(templateID) - getTemplateAttachmentOptions.SetAttachmentID(parts[1]) - - templateAttachment, _, err := configurationGovernanceClient.GetTemplateAttachment(getTemplateAttachmentOptions) - if err != nil { - return err - } - - if *templateAttachment.TemplateID != templateID { - return fmt.Errorf( - "ibm_scc_template_attachment.scc_template_attachment: Attribute 'template_id' expected %#v, got %#v", - templateID, - templateAttachment.TemplateID, - ) - } - obj = *templateAttachment - return nil - } -} - -func testAccCheckIBMSccTemplateAttachmentDestroy(s *terraform.State) error { - configurationGovernanceClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return err - } - for _, rs := range s.RootModule().Resources { - if rs.Type != "ibm_scc_template_attachment" { - continue - } - - getTemplateAttachmentOptions := &configurationgovernancev1.GetTemplateAttachmentOptions{} - - parts, err := flex.SepIdParts(rs.Primary.ID, "/") - if err != nil { - return err - } - - getTemplateAttachmentOptions.SetTemplateID(parts[0]) - getTemplateAttachmentOptions.SetAttachmentID(parts[1]) - - // Try to find the key - _, response, err := configurationGovernanceClient.GetTemplateAttachment(getTemplateAttachmentOptions) - - if err == nil { - return fmt.Errorf("scc_template_attachment still exists: %s", rs.Primary.ID) - } else if response.StatusCode != 404 { - return fmt.Errorf("Error checking for scc_template_attachment (%s) has been destroyed: %s", rs.Primary.ID, err) - } - } - - return nil -} diff --git a/ibm/service/scc/resource_ibm_scc_template_attachment_validator.go b/ibm/service/scc/resource_ibm_scc_template_attachment_validator.go deleted file mode 100644 index a55862b2da..0000000000 --- a/ibm/service/scc/resource_ibm_scc_template_attachment_validator.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc - -import ( - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" -) - -func ResourceIBMSccTemplateAttachmentValidator() *validate.ResourceValidator { - validateSchema := make([]validate.ValidateSchema, 0) - validateSchema = append(validateSchema, - validate.ValidateSchema{ - Identifier: "scope_type", - ValidateFunctionIdentifier: validate.ValidateAllowedStringValue, - Type: validate.TypeString, - Required: true, - AllowedValues: "enterprise, enterprise.account_group, enterprise.account, account, account.resource_group", - }, - ) - - resourceValidator := validate.ResourceValidator{ResourceName: "ibm_scc_template_attachment", Schema: validateSchema} - return &resourceValidator -} diff --git a/ibm/service/scc/resource_ibm_scc_template_test.go b/ibm/service/scc/resource_ibm_scc_template_test.go deleted file mode 100644 index d8f03e4425..0000000000 --- a/ibm/service/scc/resource_ibm_scc_template_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc_test - -import ( - "fmt" - "os" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" - - acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" - "github.com/IBM/scc-go-sdk/v3/configurationgovernancev1" -) - -func TestAccIBMSccTemplateBasic(t *testing.T) { - var conf configurationgovernancev1.TemplateResponse - - resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, - CheckDestroy: testAccCheckIBMSccTemplateDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccCheckIBMSccTemplateConfigBasic(), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckIBMSccTemplateExists("ibm_scc_template.scc_template", conf), - ), - }, - resource.TestStep{ - ResourceName: "ibm_scc_template.scc_template", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func testAccCheckIBMSccTemplateConfigBasic() string { - account_id := os.Getenv("SCC_GOVERNANCE_ACCOUNT_ID") - return fmt.Sprintf(` - - resource "ibm_scc_template" "scc_template" { - account_id = "%s" - name = "Terraform template" - description = "description" - target { - service_name = "cloud-object-storage" - resource_kind = "bucket" - additional_target_attributes { - name = "location" - value = "us-south" - } - } - customized_defaults { - property = "activity_tracking.write_data_events" - value = "true" - } - } - `, account_id) -} - -func testAccCheckIBMSccTemplateExists(n string, obj configurationgovernancev1.TemplateResponse) resource.TestCheckFunc { - - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - configurationGovernanceClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return err - } - - getTemplateOptions := &configurationgovernancev1.GetTemplateOptions{} - - getTemplateOptions.SetTemplateID(rs.Primary.ID) - - template, _, err := configurationGovernanceClient.GetTemplate(getTemplateOptions) - if err != nil { - return err - } - - obj = *template - return nil - } -} - -func testAccCheckIBMSccTemplateDestroy(s *terraform.State) error { - configurationGovernanceClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).ConfigurationGovernanceV1() - if err != nil { - return err - } - for _, rs := range s.RootModule().Resources { - if rs.Type != "ibm_scc_template" { - continue - } - - getTemplateOptions := &configurationgovernancev1.GetTemplateOptions{} - - getTemplateOptions.SetTemplateID(rs.Primary.ID) - - // Try to find the key - _, response, err := configurationGovernanceClient.GetTemplate(getTemplateOptions) - - if err == nil { - return fmt.Errorf("scc_template still exists: %s", rs.Primary.ID) - } else if response.StatusCode != 404 { - return fmt.Errorf("Error checking for scc_template (%s) has been destroyed: %s", rs.Primary.ID, err) - } - } - - return nil -} diff --git a/ibm/service/scc/resource_ibm_scc_template_validator.go b/ibm/service/scc/resource_ibm_scc_template_validator.go deleted file mode 100644 index 5e4bff9a38..0000000000 --- a/ibm/service/scc/resource_ibm_scc_template_validator.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. -// Licensed under the Mozilla Public License v2.0 - -package scc - -import ( - "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" -) - -func ResourceIBMSccTemplateValidator() *validate.ResourceValidator { - validateSchema := make([]validate.ValidateSchema, 3) - validateSchema = append(validateSchema, - validate.ValidateSchema{ - Identifier: "name", - ValidateFunctionIdentifier: validate.ValidateRegexpLen, - Type: validate.TypeString, - Required: true, - MinValueLength: 1, - MaxValueLength: 32, - Regexp: ".*", - }, - ) - validateSchema = append(validateSchema, - validate.ValidateSchema{ - Identifier: "description", - ValidateFunctionIdentifier: validate.ValidateRegexpLen, - Type: validate.TypeString, - Required: true, - MinValueLength: 1, - MaxValueLength: 256, - Regexp: ".*", - }, - ) - validateSchema = append(validateSchema, - validate.ValidateSchema{ - Identifier: "service_name", - ValidateFunctionIdentifier: validate.ValidateRegexp, - Type: validate.TypeString, - Required: true, - Regexp: "^[a-z-]*$", - }, - ) - - resourceValidator := validate.ResourceValidator{ResourceName: "ibm_scc_template", Schema: validateSchema} - return &resourceValidator -} diff --git a/website/docs/d/scc_account_location.html.markdown b/website/docs/d/scc_account_location.html.markdown deleted file mode 100644 index 1bfb155f57..0000000000 --- a/website/docs/d/scc_account_location.html.markdown +++ /dev/null @@ -1,50 +0,0 @@ ---- -layout: "ibm" -subcategory: "Security and Compliance Center" -page_title: "IBM : ibm_scc_account_location" -description: |- - Get information about scc_account_location ---- - -# ibm_scc_account_location - -Provides a read-only data source for scc_account_location. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. - -~> **NOTE**: exporting out the environmental variable `IBM_CLOUD_SCC_ADMIN_API_ENDPOINT` will help out if the account fails to resolve. -## Example usage - -```terraform -data "ibm_scc_account_location" "scc_account_location" { - location_id = "us" -} -``` - -## Argument reference - -Review the argument reference that you can specify for your data source. - -* `location_id` - (Required, Forces new resource, String) The programatic ID of the location that you want to work in. - * Constraints: Allowable values are: `us`, `eu`, `uk`. - -## Attribute reference - -In addition to all argument references listed, you can access the following attribute references after your data source is created. - -* `id` - The unique identifier of the scc_account_location_properties. - -* `location_id` - (Required, String) The programatic ID of the location that you want to work in. - * Constraints: Allowable values are: `us`, `eu`, `uk`. - -* `analytics_endpoint_url` - (Optional, String) The endpoint that is used to generate analytics for the Posture Management component. - -* `compliance_endpoint_url` - (Optional, String) The endpoint that is used to call the Posture Management APIs. - -* `governance_endpoint_url` - (Optional, String) The endpoint that is used to call the Configuration Governance APIs. - -* `main_endpoint_url` - (Optional, String) The base URL for the service. - -* `results_endpoint_url` - (Optional, String) The endpoint that is used to get the results for the Configuration Governance component. - -* `regions` - (Optional, List) Nested scheme for **regions**: - * `id` - (Required, String) The programatic ID of the available regions. - * Constraints: Allowable values are: `us`, `eu`, `uk`. \ No newline at end of file diff --git a/website/docs/d/scc_account_location_settings.html.markdown b/website/docs/d/scc_account_location_settings.html.markdown deleted file mode 100644 index 6a7cc255e7..0000000000 --- a/website/docs/d/scc_account_location_settings.html.markdown +++ /dev/null @@ -1,27 +0,0 @@ ---- -layout: "ibm" -subcategory: "Security and Compliance Center" -page_title: "IBM : ibm_scc_account_settings" -description: |- - Get information about scc_account_location_settings ---- - -# ibm_scc_account_settings - -Provides a read-only data source for scc_account_location_settings. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. - -~> **NOTE**: exporting out the environmental variable `IBM_CLOUD_SCC_ADMIN_API_ENDPOINT` will help out if the account fails to resolve. -## Example usage - -```terraform -data "ibm_scc_account_settings" "scc_account_location_settings" { -} -``` - - -## Attribute reference - -In addition to all argument references listed, you can access the following attribute references after your data source is created. - -* `id` - (String) The programatic ID of the location that you want to work in. - * Constraints: Allowable values are: `us`, `eu`, `uk`. diff --git a/website/docs/d/scc_account_locations.html.markdown b/website/docs/d/scc_account_locations.html.markdown deleted file mode 100644 index 27addeafba..0000000000 --- a/website/docs/d/scc_account_locations.html.markdown +++ /dev/null @@ -1,38 +0,0 @@ ---- -layout: "ibm" -subcategory: "Security and Compliance Center" -page_title: "IBM : ibm_scc_account_locations" -description: |- - Get information about scc_account_locations ---- - -# ibm_scc_account_locations - -Provides a read-only data source for scc_account_locations. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. - -## Example usage - -```terraform -data "ibm_scc_account_locations" "scc_account_locations" { -} -``` - - -## Attribute reference - -In addition to all argument references listed, you can access the following attribute references after your data source is created. - -* `id` - The unique identifier of the scc_account_locations. -* `locations` - (List) -Nested scheme for **locations**: - * `analytics_endpoint_url` - (String) The endpoint that is used to generate analytics for the Posture Management component. - * `compliance_endpoint_url` - (String) The endpoint that is used to call the Posture Management APIs. - * `governance_endpoint_url` - (String) The endpoint that is used to call the Configuration Governance APIs. - * `id` - (String) The programatic ID of the location that you want to work in. - * Constraints: Allowable values are: `us`, `eu`, `uk`. - * `main_endpoint_url` - (String) The base URL for the service. - * `regions` - (List) - Nested scheme for **regions**: - * `id` - (String) The programatic ID of the available regions. - * Constraints: Allowable values are: `us`, `eu`, `uk`. - * `results_endpoint_url` - (String) The endpoint that is used to get the results for the Configuration Governance component. diff --git a/website/docs/d/scc_account_notification_settings.html.markdown b/website/docs/d/scc_account_notification_settings.html.markdown deleted file mode 100644 index 921ac31d4d..0000000000 --- a/website/docs/d/scc_account_notification_settings.html.markdown +++ /dev/null @@ -1,27 +0,0 @@ ---- -layout: "ibm" -page_title: "IBM : ibm_scc_account_notification_settings" -description: |- - Get information about scc_account_notification_settings -subcategory: "Security and Compliance Center" ---- - -# ibm_scc_account_notification_settings - -Provides a read-only data source for scc_account_notification_settings. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. - -~> **NOTE**: exporting out the environmental variable `IBM_CLOUD_SCC_ADMIN_API_ENDPOINT` will help out if the account fails to resolve. - -## Example Usage - -```hcl -data "ibm_scc_account_notification_settings" "scc_account_notification_settings" { -} -``` - - -## Attribute Reference - -In addition to all argument references listed, you can access the following attribute references after your data source is created. - -* `instance_crn` - (Optional, String) The Cloud Resource Name (CRN) of the Event Notifications instance that you want to connect. diff --git a/website/docs/d/scc_control_library.html.markdown b/website/docs/d/scc_control_library.html.markdown new file mode 100644 index 0000000000..d0c0fe7521 --- /dev/null +++ b/website/docs/d/scc_control_library.html.markdown @@ -0,0 +1,133 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_control_library" +description: |- + Get information about scc_control_library +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_control_library + +Retrieve information about a scc_control_library from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_control_library" "scc_control_library" { + control_library_id = ibm_scc_control_library.scc_control_library_instance.controlLibrary_id +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `control_library_id` - (Required, Forces new resource, String) The control library ID. + * Constraints: The maximum length is `256` characters. The minimum length is `1` character. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_control_library. +* `account_id` - (String) The account ID. + * Constraints: The maximum length is `32` characters. The minimum length is `0` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + +* `control_library_description` - (String) The control library description. + * Constraints: The maximum length is `256` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `control_library_name` - (String) The control library name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_\\s\\-]*$/`. + +* `control_library_type` - (String) The control library type. + * Constraints: Allowable values are: `predefined`, `custom`. + +* `control_library_version` - (String) The control library version. + * Constraints: The maximum length is `64` characters. The minimum length is `5` characters. The value must match regular expression `/^[a-zA-Z0-9_\\-.]*$/`. + +* `control_parents_count` - (Integer) The number of parent controls in the control library. + +* `controls` - (List) The list of controls in a control library. + * Constraints: The maximum length is `1200` items. The minimum length is `0` items. +Nested schema for **controls**: + * `control_category` - (String) The control category. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,\\-\\s]*$/`. + * `control_description` - (String) The control description. + * Constraints: The maximum length is `1024` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'"\\s\\-\\[\\]]+$/`. + * `control_docs` - (List) The control documentation. + Nested schema for **control_docs**: + * `control_docs_id` - (String) The ID of the control documentation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_docs_type` - (String) The type of control documentation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_id` - (String) The control name. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_name` - (String) The ID of the control library that contains the profile. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_parent` - (String) The parent control. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]*/`. + * `control_requirement` - (Boolean) The indication of whether a control can be automated or manually evaluated. + * `control_specifications` - (List) The control specifications. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + Nested schema for **control_specifications**: + * `assessments` - (List) The assessments. + * Constraints: The maximum length is `10` items. The minimum length is `0` items. + Nested schema for **assessments**: + * `assessment_description` - (String) The assessment description. + * Constraints: The maximum length is `256` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `assessment_id` - (String) The assessment ID. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_method` - (String) The assessment method. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_type` - (String) The assessment type. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `parameter_count` - (Integer) The parameter count. + * `parameters` - (List) The parameters. + * Constraints: The maximum length is `512` items. The minimum length is `0` items. + Nested schema for **parameters**: + * `parameter_display_name` - (String) The parameter display name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `parameter_name` - (String) The parameter name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_\\s\\-]*$/`. + * `parameter_type` - (String) The parameter type. + * Constraints: Allowable values are: `string`, `numeric`, `general`, `boolean`, `string_list`, `ip_list`, `timestamp`. + * `assessments_count` - (Integer) The number of assessments. + * `componenet_name` - (String) The component name. + * Constraints: The maximum length is `512` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `component_id` - (String) The component ID. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `control_specification_description` - (String) The control specifications description. + * Constraints: The maximum length is `1024` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `control_specification_id` - (String) The control specification ID. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. + * `environment` - (String) The control specifications environment. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `responsibility` - (String) The responsibility for managing the control. + * Constraints: Allowable values are: `user`. + * `control_tags` - (List) The control tags. + * Constraints: The list items must match regular expression `/^[a-zA-Z0-9_,'"\\s\\-\\[\\]]+$/`. The maximum length is `512` items. The minimum length is `0` items. + * `status` - (String) The control status. + * Constraints: Allowable values are: `enabled`, `disabled`. + +* `controls_count` - (Integer) The number of controls. + +* `created_by` - (String) The user who created the control library. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. + +* `created_on` - (String) The date when the control library was created. + +* `hierarchy_enabled` - (Boolean) The indication of whether hierarchy is enabled for the control library. + +* `id` - (String) The control library ID. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + +* `latest` - (Boolean) The latest version of the control library. + +* `updated_by` - (String) The user who updated the control library. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. + +* `updated_on` - (String) The date when the control library was updated. + +* `version_group_label` - (String) The version group label. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. + diff --git a/website/docs/d/scc_instance_settings.html.markdown b/website/docs/d/scc_instance_settings.html.markdown new file mode 100644 index 0000000000..42e46b64c1 --- /dev/null +++ b/website/docs/d/scc_instance_settings.html.markdown @@ -0,0 +1,36 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_instance_settings" +description: |- + Manages scc_instance_settings. +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_instance_settings + +Provides a read-only data source to retrieve information about scc_instance_settings. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + + +## Example Usage + +```hcl +resource "ibm_scc_instance_settings" "scc_instance_settings_instance" { +} +``` + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `event_notifications` - (List) The Event Notifications settings. +Nested schema for **event_notifications**: + * `instance_crn` - (String) The Event Notifications instance CRN. + * `source_id` - (String) The connected Security and Compliance Center instance CRN. + * `updated_on` - (String) The date when the Event Notifications connection was updated. +* `object_storage` - (List) The Cloud Object Storage settings. +Nested schema for **object_storage**: + * `bucket` - (String) The connected Cloud Object Storage bucket name. + * `bucket_endpoint` - (String) The connected Cloud Object Storage bucket endpoint. + * `bucket_location` - (String) The connected Cloud Object Storage bucket location. + * `instance_crn` - (String) The connected Cloud Object Storage instance CRN. + * `updated_on` - (String) The date when the bucket connection was updated. diff --git a/website/docs/d/scc_latest_reports.html.markdown b/website/docs/d/scc_latest_reports.html.markdown new file mode 100644 index 0000000000..5afa715527 --- /dev/null +++ b/website/docs/d/scc_latest_reports.html.markdown @@ -0,0 +1,97 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_latest_reports" +description: |- + Get information about scc_latest_reports +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_latest_reports + +Retrieve information about the latest reports from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_latest_reports" "scc_latest_reports" { + sort = "profile_name" +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `sort` - (Optional, String) This field sorts results by using a valid sort field. To learn more, see [Sorting](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-sorting). + * Constraints: The maximum length is `32` characters. The minimum length is `1` character. The value must match regular expression `/^[\\-]?[a-z0-9_]+$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_latest_reports. +* `controls_summary` - (List) The compliance stats. +Nested schema for **controls_summary**: + * `compliant_count` - (Integer) The number of compliant checks. + * `not_compliant_count` - (Integer) The number of checks that are not compliant. + * `status` - (String) The allowed values of an aggregated status for controls, specifications, assessments, and resources. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + * `total_count` - (Integer) The total number of checks. + * `unable_to_perform_count` - (Integer) The number of checks that are unable to perform. + * `user_evaluation_required_count` - (Integer) The number of checks that require a user evaluation. + +* `evaluations_summary` - (List) The evaluation stats. +Nested schema for **evaluations_summary**: + * `completed_count` - (Integer) The total number of completed evaluations. + * `error_count` - (Integer) The number of evaluations that started, but did not finish, and ended with errors. + * `failure_count` - (Integer) The number of failed evaluations. + * `pass_count` - (Integer) The number of passed evaluations. + * `status` - (String) The allowed values of an aggregated status for controls, specifications, assessments, and resources. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + * `total_count` - (Integer) The total number of evaluations. + +* `home_account_id` - (String) The ID of the home account. + +* `reports` - (List) The list of reports. + * Constraints: The maximum length is `1000` items. The minimum length is `0` items. +Nested schema for **reports**: + * `account` - (List) The account that is associated with a report. + Nested schema for **account**: + * `id` - (String) The account ID. + * `name` - (String) The account name. + * `type` - (String) The account type. + * `attachment` - (List) The attachment that is associated with a report. + Nested schema for **attachment**: + * `description` - (String) The description of the attachment. + * `id` - (String) The attachment ID. + * `name` - (String) The name of the attachment. + * `schedule` - (String) The attachment schedule. + * `scope` - (List) The scope of the attachment. + * Constraints: The maximum length is `8` items. The minimum length is `0` items. + Nested schema for **scope**: + * `environment` - (String) The environment that relates to this scope. + * `id` - (String) The unique identifier for this scope. + * `properties` - (List) The properties that are supported for scoping by this environment. + * Constraints: The maximum length is `99999` items. The minimum length is `0` items. + Nested schema for **properties**: + * `name` - (String) The property name. + * `value` - (String) The property value. + * `cos_object` - (String) The Cloud Object Storage object that is associated with the report. + * `created_on` - (String) The date when the report was created. + * `group_id` - (String) The group ID that is associated with the report. The group ID combines profile, scope, and attachment IDs. + * `id` - (String) The ID of the report. + * `instance_id` - (String) Instance ID. + * `profile` - (List) The profile information. + Nested schema for **profile**: + * `id` - (String) The profile ID. + * `name` - (String) The profile name. + * `version` - (String) The profile version. + * `scan_time` - (String) The date when the scan was run. + * `type` - (String) The type of the scan. + +* `score` - (List) The compliance score. +Nested schema for **score**: + * `passed` - (Integer) The number of successful evaluations. + * `percent` - (Integer) The percentage of successful evaluations. + * `total_count` - (Integer) The total number of evaluations. + diff --git a/website/docs/d/scc_profile.html.markdown b/website/docs/d/scc_profile.html.markdown new file mode 100644 index 0000000000..d5cec8a076 --- /dev/null +++ b/website/docs/d/scc_profile.html.markdown @@ -0,0 +1,152 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_profile" +description: |- + Get information about scc_profile +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_profile + +Retrieve information about a profile from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_profile" "scc_profile" { + profile_id = ibm_scc_profile.scc_profile_instance.profile_id +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `profile_id` - (Required, Forces new resource, String) The profile ID. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_profile. +* `attachments_count` - (Integer) The number of attachments related to this profile. + +* `control_parents_count` - (Integer) The number of parent controls for the profile. + +* `controls` - (List) The array of controls that are used to create the profile. + * Constraints: The maximum length is `600` items. The minimum length is `0` items. +Nested schema for **controls**: + * `control_category` - (String) The control category. + * Constraints: The maximum length is `512` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_description` - (String) The control description. + * Constraints: The maximum length is `1024` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_docs` - (List) The control documentation. + Nested schema for **control_docs**: + * `control_docs_id` - (String) The ID of the control documentation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_docs_type` - (String) The type of control documentation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_id` - (String) The unique ID of the control library that contains the profile. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/[A-Z0-9]+/`. + * `control_library_id` - (String) The ID of the control library that contains the profile. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_library_version` - (String) The most recent version of the control library. + * Constraints: The maximum length is `36` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_name` - (String) The control name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_parent` - (String) The parent control. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]*/`. + * `control_requirement` - (Boolean) Is this a control that can be automated or manually evaluated. + * `control_specifications` - (List) The control specifications. + * Constraints: The maximum length is `400` items. The minimum length is `0` items. + Nested schema for **control_specifications**: + * `assessments` - (List) The assessments. + * Constraints: The maximum length is `10` items. The minimum length is `0` items. + Nested schema for **assessments**: + * `assessment_description` - (String) The assessment description. + * Constraints: The maximum length is `256` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `assessment_id` - (String) The assessment ID. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_method` - (String) The assessment method. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_type` - (String) The assessment type. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `parameter_count` - (Integer) The parameter count. + * `parameters` - (List) The parameters. + * Constraints: The maximum length is `512` items. The minimum length is `0` items. + Nested schema for **parameters**: + * `parameter_display_name` - (String) The parameter display name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `parameter_name` - (String) The parameter name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_\\s\\-]*$/`. + * `parameter_type` - (String) The parameter type. + * Constraints: Allowable values are: `string`, `numeric`, `general`, `boolean`, `string_list`, `ip_list`, `timestamp`. + * `assessments_count` - (Integer) The number of assessments. + * `componenet_name` - (String) The component name. + * Constraints: The maximum length is `512` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `component_id` - (String) The component ID. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `control_specification_description` - (String) The control specifications description. + * Constraints: The maximum length is `1024` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `control_specification_id` - (String) The control specification ID. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. + * `environment` - (String) The control specifications environment. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `responsibility` - (String) The responsibility for managing the control. + * Constraints: Allowable values are: `user`. + * `control_specifications_count` - (Integer) The number of control specifications. + +* `controls_count` - (Integer) The number of controls for the profile. + +* `created_by` - (String) The user who created the profile. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. + +* `created_on` - (String) The date when the profile was created. + +* `default_parameters` - (List) The default parameters of the profile. + * Constraints: The maximum length is `512` items. The minimum length is `0` items. +Nested schema for **default_parameters**: + * `assessment_id` - (String) The implementation ID of the parameter. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_type` - (String) The type of the implementation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `parameter_default_value` - (String) The default value of the parameter. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'"\\s\\-\\[\\]]+$/`. + * `parameter_display_name` - (String) The parameter display name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `parameter_name` - (String) The parameter name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_]*$/`. + * `parameter_type` - (String) The parameter type. + * Constraints: Allowable values are: `string`, `numeric`, `general`, `boolean`, `string_list`, `ip_list`, `timestamp`. + +* `hierarchy_enabled` - (Boolean) The indication of whether hierarchy is enabled for the profile. + +* `id` - (String) The unique ID of the profile. + * Constraints: The maximum length is `36` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `instance_id` - (String) The instance ID. + * Constraints: The maximum length is `36` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `latest` - (Boolean) The latest version of the profile. + +* `profile_description` - (String) The profile description. + * Constraints: The maximum length is `256` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `profile_name` - (String) The profile name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `profile_type` - (String) The profile type, such as custom or predefined. + * Constraints: Allowable values are: `predefined`, `custom`. + +* `profile_version` - (String) The version status of the profile. + * Constraints: The maximum length is `64` characters. The minimum length is `5` characters. The value must match regular expression `/^[a-zA-Z0-9_\\-.]*$/`. + +* `updated_by` - (String) The user who updated the profile. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. + +* `updated_on` - (String) The date when the profile was updated. + +* `version_group_label` - (String) The version group label of the profile. + * Constraints: The maximum length is `36` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + diff --git a/website/docs/d/scc_profile_attachment.html.markdown b/website/docs/d/scc_profile_attachment.html.markdown new file mode 100644 index 0000000000..7c239c317f --- /dev/null +++ b/website/docs/d/scc_profile_attachment.html.markdown @@ -0,0 +1,117 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_profile_attachment" +description: |- + Get information about scc_profile_attachment +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_profile_attachment + +Retrieve information about a profile attachment from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_profile_attachment" "scc_profile_attachment" { + attachment_id = "attachment_id" + profile_id = ibm_scc_profile_attachment.scc_profile_attachment.profiles_id +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `attachment_id` - (Required, Forces new resource, String) The attachment ID. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$|^$/`. +* `profile_id` - (Required, Forces new resource, String) The profile ID. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_profile_attachment. +* `account_id` - (String) The account ID that is associated to the attachment. + * Constraints: The maximum length is `32` characters. The minimum length is `32` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + +* `attachment_item_id` - (String) The ID of the attachment. + * Constraints: The maximum length is `32` characters. The minimum length is `32` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + +* `attachment_parameters` - (List) The profile parameters for the attachment. + * Constraints: The maximum length is `512` items. The minimum length is `0` items. +Nested schema for **attachment_parameters**: + * `assessment_id` - (String) The implementation ID of the parameter. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_type` - (String) The type of the implementation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `parameter_display_name` - (String) The parameter display name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `parameter_name` - (String) The parameter name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_]*$/`. + * `parameter_type` - (String) The parameter type. + * Constraints: Allowable values are: `string`, `numeric`, `general`, `boolean`, `string_list`, `ip_list`, `timestamp`. + * `parameter_value` - (String) The value of the parameter. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'"\\s\\-\\[\\]]+$/`. + +* `created_by` - (String) The user who created the attachment. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. + +* `created_on` - (String) The date when the attachment was created. + +* `description` - (String) The description for the attachment. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + +* `instance_id` - (String) The instance ID of the account that is associated to the attachment. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$|^$/`. + +* `last_scan` - (List) The details of the last scan of an attachment. +Nested schema for **last_scan**: + * `id` - (String) The ID of the last scan of an attachment. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `status` - (String) The status of the last scan of an attachment. + * Constraints: Allowable values are: `in_progress`, `completed`. + * `time` - (String) The time when the last scan started. + +* `name` - (String) The name of the attachment. + * Constraints: The maximum length is `128` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + +* `next_scan_time` - (String) The start time of the next scan. + +* `notifications` - (List) The request payload of the attachment notifications. +Nested schema for **notifications**: + * `controls` - (List) The failed controls. + Nested schema for **controls**: + * `failed_control_ids` - (List) The failed control IDs. + * Constraints: The list items must match regular expression `/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$|^$/`. The maximum length is `512` items. The minimum length is `0` items. + * `threshold_limit` - (Integer) The threshold limit. + * `enabled` - (Boolean) enabled notifications. + +* `profile_id` - (String) The ID of the profile that is specified in the attachment. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. + +* `schedule` - (String) The schedule of an attachment evaluation. + * Constraints: Allowable values are: `daily`, `every_7_days`, `every_30_days`. + +* `scope` - (List) The scope payload for the multi cloud feature. + * Constraints: The maximum length is `8` items. The minimum length is `0` items. +Nested schema for **scope**: + * `environment` - (String) The environment that relates to this scope. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `properties` - (List) The properties supported for scoping by this environment. + * Constraints: The maximum length is `8` items. The minimum length is `0` items. + Nested schema for **properties**: + * `name` - (String) The name of the property. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (String) The value of the property. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `status` - (String) The status of an attachment evaluation. + * Constraints: Allowable values are: `enabled`, `disabled`. + +* `updated_by` - (String) The user who updated the attachment. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. + +* `updated_on` - (String) The date when the attachment was updated. + diff --git a/website/docs/d/scc_provider_type.html.markdown b/website/docs/d/scc_provider_type.html.markdown new file mode 100644 index 0000000000..0bb1d28b18 --- /dev/null +++ b/website/docs/d/scc_provider_type.html.markdown @@ -0,0 +1,61 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_provider_type" +description: |- + Get information about scc_provider_type +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_provider_type + +Retrieve information about a provider type from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_provider_type" "scc_provider_type" { + provider_type_id = "provider_type_id" +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `provider_type_id` - (Required, Forces new resource, String) The provider type ID. + * Constraints: The maximum length is `36` characters. The minimum length is `32` characters. The value must match regular expression `/^[a-zA-Z0-9 ,\\-_]+$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_provider_type. +* `attributes` - (Map) The attributes that are required when you're creating an instance of a provider type. The attributes field can have multiple keys in its value. Each of those keys has a value object that includes the type, and display name as keys. For example, `{type:"", display_name:""}`. **NOTE;** If the provider type is s2s-enabled, which means that if the `s2s_enabled` field is set to `true`, then a CRN field of type text is required in the attributes value object. + +* `created_at` - (String) The time when the resource was created. + +* `data_type` - (String) The format of the results that a provider supports. + +* `description` - (String) The provider type description. + +* `icon` - (String) The icon of a provider in .svg format that is encoded as a base64 string. + +* `id` - (String) The unique identifier of the provider type. + +* `instance_limit` - (Integer) The maximum number of instances that can be created for the provider type. + +* `label` - (List) The label that is associated with the provider type. +Nested schema for **label**: + * `text` - (String) The text of the label. + * `tip` - (String) The text to be shown when user hover overs the label. + +* `mode` - (String) The mode that is used to get results from provider (`PUSH` or `PULL`). + +* `name` - (String) The name of the provider type. + +* `s2s_enabled` - (Boolean) A boolean that indicates whether the provider type is s2s-enabled. + +* `type` - (String) The type of the provider type. + +* `updated_at` - (String) The time when the resource was updated. + diff --git a/website/docs/d/scc_provider_type_collection.html.markdown b/website/docs/d/scc_provider_type_collection.html.markdown new file mode 100644 index 0000000000..c704adfa5c --- /dev/null +++ b/website/docs/d/scc_provider_type_collection.html.markdown @@ -0,0 +1,44 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_provider_type_collection" +description: |- + Get information about scc_provider_type_collection +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_provider_type_collection + +Retrieve information about a provider type collection from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_provider_type_collection" "scc_provider_type_collection" { +} +``` + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_provider_type_collection. +* `provider_types` - (List) The array of provder type. + * Constraints: The minimum length is `0` items. +Nested schema for **provider_types**: + * `attributes` - (Map) The attributes that are required when you're creating an instance of a provider type. The attributes field can have multiple keys in its value. Each of those keys has a value object that includes the type, and display name as keys. For example, `{type:"", display_name:""}`. **NOTE;** If the provider type is s2s-enabled, which means that if the `s2s_enabled` field is set to `true`, then a CRN field of type text is required in the attributes value object. + * `created_at` - (String) The time when the resource was created. + * `data_type` - (String) The format of the results that a provider supports. + * `description` - (String) The provider type description. + * `icon` - (String) The icon of a provider in .svg format that is encoded as a base64 string. + * `id` - (String) The unique identifier of the provider type. + * `instance_limit` - (Integer) The maximum number of instances that can be created for the provider type. + * `label` - (List) The label that is associated with the provider type. + Nested schema for **label**: + * `text` - (String) The text of the label. + * `tip` - (String) The text to be shown when user hover overs the label. + * `mode` - (String) The mode that is used to get results from provider (`PUSH` or `PULL`). + * `name` - (String) The name of the provider type. + * `s2s_enabled` - (Boolean) A boolean that indicates whether the provider type is s2s-enabled. + * `type` - (String) The type of the provider type. + * `updated_at` - (String) The time when the resource was updated. + diff --git a/website/docs/d/scc_provider_type_instance.html.markdown b/website/docs/d/scc_provider_type_instance.html.markdown new file mode 100644 index 0000000000..6b028f7ce3 --- /dev/null +++ b/website/docs/d/scc_provider_type_instance.html.markdown @@ -0,0 +1,48 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_provider_type_instance" +description: |- + Get information about scc_provider_type_instance +subcategory: "Security and Compliance Center APIs" +--- + +# ibm_scc_provider_type_instance + +Retrieve information about a provider type instance from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_provider_type_instance" "scc_provider_type_instance" { + provider_type_id = ibm_scc_provider_type_instance.scc_provider_type_instance.provider_type_id + provider_type_instance_id = ibm_scc_provider_type_instance.scc_provider_type_instance_instance.providerTypeInstanceItem_id +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `provider_type_id` - (Required, Forces new resource, String) The provider type ID. + * Constraints: The maximum length is `36` characters. The minimum length is `32` characters. The value must match regular expression `/^[a-zA-Z0-9 ,\\-_]+$/`. +* `provider_type_instance_id` - (Required, Forces new resource, String) The provider type instance ID. + * Constraints: The maximum length is `36` characters. The minimum length is `32` characters. The value must match regular expression `/^[a-zA-Z0-9 ,\\-_]+$/` + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_provider_type_instance. +* `attributes` - (List) The attributes for connecting to the provider type instance. +Nested schema for **attributes**: + +* `created_at` - (String) The time when the resource was created. + +* `name` - (String) The name of the provider type instance. + +* `provider_type_instance_item_id` - (String) The unique identifier of the provider type instance. + +* `type` - (String) The type of the provider type. + +* `updated_at` - (String) The time when the resource was updated. + diff --git a/website/docs/d/scc_report.html.markdown b/website/docs/d/scc_report.html.markdown new file mode 100644 index 0000000000..4d7b4b60ab --- /dev/null +++ b/website/docs/d/scc_report.html.markdown @@ -0,0 +1,75 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_report" +description: |- + Get information about scc_report +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_report + +Retrieve information about a report from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_report" "scc_report" { + report_id = "report_id" +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `report_id` - (Required, Forces new resource, String) The ID of the scan that is associated with a report. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_report. +* `account` - (List) The account that is associated with a report. +Nested schema for **account**: + * `id` - (String) The account ID. + * `name` - (String) The account name. + * `type` - (String) The account type. + +* `attachment` - (List) The attachment that is associated with a report. +Nested schema for **attachment**: + * `description` - (String) The description of the attachment. + * `id` - (String) The attachment ID. + * `name` - (String) The name of the attachment. + * `schedule` - (String) The attachment schedule. + * `scope` - (List) The scope of the attachment. + * Constraints: The maximum length is `8` items. The minimum length is `0` items. + Nested schema for **scope**: + * `environment` - (String) The environment that relates to this scope. + * `id` - (String) The unique identifier for this scope. + * `properties` - (List) The properties that are supported for scoping by this environment. + * Constraints: The maximum length is `99999` items. The minimum length is `0` items. + Nested schema for **properties**: + * `name` - (String) The property name. + * `value` - (String) The property value. + +* `cos_object` - (String) The Cloud Object Storage object that is associated with the report. + +* `created_on` - (String) The date when the report was created. + +* `group_id` - (String) The group ID that is associated with the report. The group ID combines profile, scope, and attachment IDs. + +* `id` - (String) The ID of the report. + +* `instance_id` - (String) Instance ID. + +* `profile` - (List) The profile information. +Nested schema for **profile**: + * `id` - (String) The profile ID. + * `name` - (String) The profile name. + * `version` - (String) The profile version. + +* `scan_time` - (String) The date when the scan was run. + +* `type` - (String) The type of the scan. + diff --git a/website/docs/d/scc_report_controls.html.markdown b/website/docs/d/scc_report_controls.html.markdown new file mode 100644 index 0000000000..8c7223d410 --- /dev/null +++ b/website/docs/d/scc_report_controls.html.markdown @@ -0,0 +1,105 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_report_controls" +description: |- + Get information about scc_report_controls +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_report_controls + +Retrieve information about report controls from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_report_controls" "scc_report_controls" { + report_id = "report_id" + status = "compliant" +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `control_category` - (Optional, String) A control category value. + * Constraints: The maximum length is `1024` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `control_description` - (Optional, String) The description of the control. + * Constraints: The maximum length is `1024` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\s]+$/`. +* `control_id` - (Optional, String) The ID of the control. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `control_name` - (Optional, String) The name of the control. + * Constraints: The maximum length is `1024` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `report_id` - (Required, Forces new resource, String) The ID of the scan that is associated with a report. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `sort` - (Optional, String) This field sorts controls by using a valid sort field. To learn more, see [Sorting](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-sorting). + * Constraints: Allowable values are: `control_name`, `control_category`, `status`. +* `status` - (Optional, String) The compliance status value. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_report_controls. +* `compliant_count` - (Integer) The number of compliant checks. + +* `controls` - (List) The list of controls that are in the report. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. +Nested schema for **controls**: + * `compliant_count` - (Integer) The number of compliant checks. + * `control_category` - (String) The control category. + * `control_description` - (String) The control description. + * `control_library_id` - (String) The control library ID. + * `control_library_version` - (String) The control library version. + * `control_name` - (String) The control name. + * `control_path` - (String) The control path. + * `control_specifications` - (List) The list of specifications that are on the page. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + Nested schema for **control_specifications**: + * `assessments` - (List) The list of assessments. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + Nested schema for **assessments**: + * `assessment_description` - (String) The assessment description. + * `assessment_id` - (String) The assessment ID. + * `assessment_method` - (String) The assessment method. + * `assessment_type` - (String) The assessment type. + * `parameter_count` - (Integer) The number of parameters of this assessment. + * `parameters` - (List) The list of parameters of this assessment. + * Constraints: The maximum length is `1000` items. The minimum length is `0` items. + Nested schema for **parameters**: + * `parameter_display_name` - (String) The parameter display name. + * `parameter_name` - (String) The parameter name. + * `parameter_type` - (String) The parameter type. + * `parameter_value` - (String) The property value. + * `compliant_count` - (Integer) The number of compliant checks. + * `component_id` - (String) The component ID. + * `control_specification_description` - (String) The component description. + * `control_specification_id` - (String) The control specification ID. + * `environment` - (String) The environment. + * `not_compliant_count` - (Integer) The number of checks that are not compliant. + * `responsibility` - (String) The responsibility for managing control specifications. + * `status` - (String) The allowed values of an aggregated status for controls, specifications, assessments, and resources. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + * `total_count` - (Integer) The total number of checks. + * `unable_to_perform_count` - (Integer) The number of checks that are unable to perform. + * `user_evaluation_required_count` - (Integer) The number of checks that require a user evaluation. + * `id` - (String) The control ID. + * `not_compliant_count` - (Integer) The number of checks that are not compliant. + * `status` - (String) The allowed values of an aggregated status for controls, specifications, assessments, and resources. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + * `total_count` - (Integer) The total number of checks. + * `unable_to_perform_count` - (Integer) The number of checks that are unable to perform. + * `user_evaluation_required_count` - (Integer) The number of checks that require a user evaluation. + +* `home_account_id` - (String) The ID of the home account. + +* `not_compliant_count` - (Integer) The number of checks that are not compliant. + +* `total_count` - (Integer) The total number of checks. + +* `unable_to_perform_count` - (Integer) The number of checks that are unable to perform. + +* `user_evaluation_required_count` - (Integer) The number of checks that require a user evaluation. + diff --git a/website/docs/d/scc_report_evaluations.html.markdown b/website/docs/d/scc_report_evaluations.html.markdown new file mode 100644 index 0000000000..de4db941f2 --- /dev/null +++ b/website/docs/d/scc_report_evaluations.html.markdown @@ -0,0 +1,92 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_report_evaluations" +description: |- + Get information about scc_report_evaluations +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_report_evaluations + +Retrieve information about report evaluations from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_report_evaluations" "scc_report_evaluations" { + report_id = "report_id" + status = "failure" +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `assessment_id` - (Optional, String) The ID of the assessment. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `component_id` - (Optional, String) The ID of component. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9.\\-]+$/`. +* `report_id` - (Required, Forces new resource, String) The ID of the scan that is associated with a report. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `status` - (Optional, String) The evaluation status value. + * Constraints: Allowable values are: `pass`, `failure`, `error`, `skipped`. +* `target_id` - (Optional, String) The ID of the evaluation target. + * Constraints: The maximum length is `1024` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `target_name` - (Optional, String) The name of the evaluation target. + * Constraints: The maximum length is `1024` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_report_evaluations. +* `evaluations` - (List) The list of evaluations that are on the page. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. +Nested schema for **evaluations**: + * `assessment` - (List) The control specification assessment. + Nested schema for **assessment**: + * `assessment_description` - (String) The assessment description. + * `assessment_id` - (String) The assessment ID. + * `assessment_method` - (String) The assessment method. + * `assessment_type` - (String) The assessment type. + * `parameter_count` - (Integer) The number of parameters of this assessment. + * `parameters` - (List) The list of parameters of this assessment. + * Constraints: The maximum length is `1000` items. The minimum length is `0` items. + Nested schema for **parameters**: + * `parameter_display_name` - (String) The parameter display name. + * `parameter_name` - (String) The parameter name. + * `parameter_type` - (String) The parameter type. + * `parameter_value` - (String) The property value. + * `component_id` - (String) The component ID. + * `control_id` - (String) The control ID. + * `details` - (List) The evaluation details. + Nested schema for **details**: + * `properties` - (List) The evaluation properties. + * Constraints: The maximum length is `1000` items. The minimum length is `0` items. + Nested schema for **properties**: + * `expected_value` - (String) The property value. + * `found_value` - (String) The property value. + * `operator` - (String) The property operator. + * `property` - (String) The property name. + * `property_description` - (String) The property description. + * `evaluate_time` - (String) The time when the evaluation was made. + * `home_account_id` - (String) The ID of the home account. + * `reason` - (String) The reason for the evaluation failure. + * `report_id` - (String) The ID of the report that is associated to the evaluation. + * `status` - (String) The allowed values of an evaluation status. + * Constraints: Allowable values are: `pass`, `failure`, `error`, `skipped`. + * `target` - (List) The evaluation target. + Nested schema for **target**: + * `account_id` - (String) The target account ID. + * `id` - (String) The target ID. + * `resource_crn` - (String) The target resource CRN. + * `resource_name` - (String) The target resource name. + * `service_name` - (String) The target service name. + +* `first` - (List) The page reference. +Nested schema for **first**: + * `href` - (String) The URL for the first and next page. + +* `home_account_id` - (String) The ID of the home account. + diff --git a/website/docs/d/scc_report_resources.html.markdown b/website/docs/d/scc_report_resources.html.markdown new file mode 100644 index 0000000000..c57af64836 --- /dev/null +++ b/website/docs/d/scc_report_resources.html.markdown @@ -0,0 +1,72 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_report_resources" +description: |- + Get information about scc_report_resources +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_report_resources + +Retrieve information about report resources from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_report_resources" "scc_report_resources" { + report_id = "report_id" + status = "compliant" +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `account_id` - (Optional, String) The ID of the account owning a resource. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `component_id` - (Optional, String) The ID of component. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9.\\-]+$/`. +* `id` - (Optional, String) The ID of the resource. + * Constraints: The maximum length is `1024` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `report_id` - (Required, Forces new resource, String) The ID of the scan that is associated with a report. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `resource_name` - (Optional, String) The name of the resource. + * Constraints: The maximum length is `1024` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `sort` - (Optional, String) This field sorts resources by using a valid sort field. To learn more, see [Sorting](https://cloud.ibm.com/docs/api-handbook?topic=api-handbook-sorting). + * Constraints: Allowable values are: `account_id`, `component_id`, `resource_name`, `status`. +* `status` - (Optional, String) The compliance status value. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_report_resources. +* `first` - (List) The page reference. +Nested schema for **first**: + * `href` - (String) The URL for the first and next page. + +* `home_account_id` - (String) The ID of the home account. + +* `resources` - (List) The list of resource evaluation summaries that are on the page. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. +Nested schema for **resources**: + * `account` - (List) The account that is associated with a report. + Nested schema for **account**: + * `id` - (String) The account ID. + * `name` - (String) The account name. + * `type` - (String) The account type. + * `completed_count` - (Integer) The total number of completed evaluations. + * `component_id` - (String) The ID of the component. + * `environment` - (String) The environment. + * `error_count` - (Integer) The number of evaluations that started, but did not finish, and ended with errors. + * `failure_count` - (Integer) The number of failed evaluations. + * `id` - (String) The resource CRN. + * `pass_count` - (Integer) The number of passed evaluations. + * `report_id` - (String) The ID of the report. + * `resource_name` - (String) The resource name. + * `status` - (String) The allowed values of an aggregated status for controls, specifications, assessments, and resources. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + * `total_count` - (Integer) The total number of evaluations. + diff --git a/website/docs/d/scc_report_rule.html.markdown b/website/docs/d/scc_report_rule.html.markdown new file mode 100644 index 0000000000..ed2221dea7 --- /dev/null +++ b/website/docs/d/scc_report_rule.html.markdown @@ -0,0 +1,56 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_report_rule" +description: |- + Get information about scc_report_rule +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_report_rule + +Retrieve information about a report rule from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_report_rule" "scc_report_rule" { + report_id = "report_id" + rule_id = "rule-8d444f8c-fd1d-48de-bcaa-f43732568761" +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `report_id` - (Required, Forces new resource, String) The ID of the scan that is associated with a report. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `rule_id` - (Required, Forces new resource, String) The ID of a rule in a report. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_report_rule. +* `account_id` - (String) The rule account ID. + +* `created_by` - (String) The ID of the user who created the rule. + +* `created_on` - (String) The date when the rule was created. + +* `description` - (String) The rule description. + +* `id` - (String) The rule ID. + +* `labels` - (List) The rule labels. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + +* `type` - (String) The rule type. + +* `updated_by` - (String) The ID of the user who updated the rule. + +* `updated_on` - (String) The date when the rule was updated. + +* `version` - (String) The rule version. + diff --git a/website/docs/d/scc_report_summary.html.markdown b/website/docs/d/scc_report_summary.html.markdown new file mode 100644 index 0000000000..4a3c375da0 --- /dev/null +++ b/website/docs/d/scc_report_summary.html.markdown @@ -0,0 +1,98 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_report_summary" +description: |- + Get information about scc_report_summary +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_report_summary + +Retrieve information about a report summary from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_report_summary" "scc_report_summary" { + report_id = "report_id" +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `report_id` - (Required, Forces new resource, String) The ID of the scan that is associated with a report. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_report_summary. +* `account` - (List) The account that is associated with a report. +Nested schema for **account**: + * `id` - (String) The account ID. + * `name` - (String) The account name. + * `type` - (String) The account type. + +* `controls` - (List) The compliance stats. +Nested schema for **controls**: + * `compliant_count` - (Integer) The number of compliant checks. + * `not_compliant_count` - (Integer) The number of checks that are not compliant. + * `status` - (String) The allowed values of an aggregated status for controls, specifications, assessments, and resources. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + * `total_count` - (Integer) The total number of checks. + * `unable_to_perform_count` - (Integer) The number of checks that are unable to perform. + * `user_evaluation_required_count` - (Integer) The number of checks that require a user evaluation. + +* `evaluations` - (List) The evaluation stats. +Nested schema for **evaluations**: + * `completed_count` - (Integer) The total number of completed evaluations. + * `error_count` - (Integer) The number of evaluations that started, but did not finish, and ended with errors. + * `failure_count` - (Integer) The number of failed evaluations. + * `pass_count` - (Integer) The number of passed evaluations. + * `status` - (String) The allowed values of an aggregated status for controls, specifications, assessments, and resources. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + * `total_count` - (Integer) The total number of evaluations. + +* `isntance_id` - (String) Instance ID. + +* `resources` - (List) The resource summary. +Nested schema for **resources**: + * `compliant_count` - (Integer) The number of compliant checks. + * `not_compliant_count` - (Integer) The number of checks that are not compliant. + * `status` - (String) The allowed values of an aggregated status for controls, specifications, assessments, and resources. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + * `top_failed` - (List) The top 10 resources that have the most failures. + * Constraints: The maximum length is `10` items. The minimum length is `0` items. + Nested schema for **top_failed**: + * `account` - (String) The account that owns the resource. + * `completed_count` - (Integer) The total number of completed evaluations. + * `error_count` - (Integer) The number of evaluations that started, but did not finish, and ended with errors. + * `failure_count` - (Integer) The number of failed evaluations. + * `id` - (String) The resource ID. + * `name` - (String) The resource name. + * `pass_count` - (Integer) The number of passed evaluations. + * `service` - (String) The service that is managing the resource. + * `status` - (String) The allowed values of an aggregated status for controls, specifications, assessments, and resources. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + * `tags` - (List) The collection of different types of tags. + Nested schema for **tags**: + * `access` - (List) The collection of access tags. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + * `service` - (List) The collection of service tags. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + * `user` - (List) The collection of user tags. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + * `total_count` - (Integer) The total number of evaluations. + * `total_count` - (Integer) The total number of checks. + * `unable_to_perform_count` - (Integer) The number of checks that are unable to perform. + * `user_evaluation_required_count` - (Integer) The number of checks that require a user evaluation. + +* `score` - (List) The compliance score. +Nested schema for **score**: + * `passed` - (Integer) The number of successful evaluations. + * `percent` - (Integer) The percentage of successful evaluations. + * `total_count` - (Integer) The total number of evaluations. + diff --git a/website/docs/d/scc_report_tags.html.markdown b/website/docs/d/scc_report_tags.html.markdown new file mode 100644 index 0000000000..82e388fa7b --- /dev/null +++ b/website/docs/d/scc_report_tags.html.markdown @@ -0,0 +1,41 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_report_tags" +description: |- + Get information about scc_report_tags +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_report_tags + +Retrieve information about report tags from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_report_tags" "scc_report_tags" { + report_id = "report_id" +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `report_id` - (Required, Forces new resource, String) The ID of the scan that is associated with a report. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_report_tags. +* `tags` - (List) The collection of different types of tags. +Nested schema for **tags**: + * `access` - (List) The collection of access tags. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + * `service` - (List) The collection of service tags. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + * `user` - (List) The collection of user tags. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + diff --git a/website/docs/d/scc_report_violation_drift.html.markdown b/website/docs/d/scc_report_violation_drift.html.markdown new file mode 100644 index 0000000000..fac3217bd8 --- /dev/null +++ b/website/docs/d/scc_report_violation_drift.html.markdown @@ -0,0 +1,53 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_report_violation_drift" +description: |- + Get information about scc_report_violation_drift +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_report_violation_drift + +Retrieve information about a report violation drift from a read-only data source. Then, yo can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_report_violation_drift" "scc_report_violation_drift" { + report_id = "report_id" +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `report_id` - (Required, Forces new resource, String) The ID of the scan that is associated with a report. + * Constraints: The maximum length is `128` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9\\-]+$/`. +* `scan_time_duration` - (Optional, Integer) The duration of the `scan_time` timestamp in number of days. + * Constraints: The default value is `0`. The maximum value is `366`. The minimum value is `0`. + + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_report_violation_drift. +* `data_points` - (List) The list of report violations data points. + * Constraints: The maximum length is `1000` items. The minimum length is `0` items. +Nested schema for **data_points**: + * `controls` - (List) The compliance stats. + Nested schema for **controls**: + * `compliant_count` - (Integer) The number of compliant checks. + * `not_compliant_count` - (Integer) The number of checks that are not compliant. + * `status` - (String) The allowed values of an aggregated status for controls, specifications, assessments, and resources. + * Constraints: Allowable values are: `compliant`, `not_compliant`, `unable_to_perform`, `user_evaluation_required`. + * `total_count` - (Integer) The total number of checks. + * `unable_to_perform_count` - (Integer) The number of checks that are unable to perform. + * `user_evaluation_required_count` - (Integer) The number of checks that require a user evaluation. + * `report_group_id` - (String) The group ID that is associated with the report. The group ID combines profile, scope, and attachment IDs. + * `report_id` - (String) The ID of the report. + * `scan_time` - (String) The date when the scan was run. + +* `home_account_id` - (String) The ID of the home account. + diff --git a/website/docs/d/scc_rule.html.markdown b/website/docs/d/scc_rule.html.markdown new file mode 100644 index 0000000000..c78a372590 --- /dev/null +++ b/website/docs/d/scc_rule.html.markdown @@ -0,0 +1,162 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_rule" +description: |- + Get information about scc_rule +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_rule + +Retrieve information about a rule from a read-only data source. Then, you can reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_scc_rule" "scc_rule" { + rule_id = ibm_scc_rule.scc_rule_instance.rule_id +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `rule_id` - (Required, Forces new resource, String) The ID of the corresponding rule. + * Constraints: The maximum length is `41` characters. The minimum length is `41` characters. The value must match regular expression `/rule-[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the scc_rule. +* `account_id` - (String) The account ID. + * Constraints: The maximum length is `32` characters. The minimum length is `3` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `created_by` - (String) The user who created the rule. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `created_on` - (String) The date when the rule was created. + +* `description` - (String) The details of a rule's response. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `id` - (String) The rule ID. + * Constraints: The maximum length is `41` characters. The minimum length is `41` characters. The value must match regular expression `/rule-[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}/`. + +* `import` - (List) The collection of import parameters. +Nested schema for **import**: + * `parameters` - (List) The list of import parameters. + * Constraints: The maximum length is `8` items. The minimum length is `0` items. + Nested schema for **parameters**: + * `description` - (String) The propery description. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `display_name` - (String) The display name of the property. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `name` - (String) The import parameter name. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `type` - (String) The property type. + * Constraints: Allowable values are: `string`, `numeric`, `general`, `boolean`, `string_list`, `ip_list`, `timestamp`. The maximum length is `11` characters. The minimum length is `6` characters. The value must match regular expression `/[A-Za-z]+/`. + +* `labels` - (List) The list of labels. + * Constraints: The list items must match regular expression `/[A-Za-z0-9]+/`. The maximum length is `32` items. The minimum length is `0` items. + +* `required_config` - (List) The required configurations. +Nested schema for **required_config**: + * `and` - (List) The `AND` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **and**: + * `and` - (List) The `AND` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **and**: + * `description` - (String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `property` - (String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (String) Schema for any JSON type. + * `description` - (String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `or` - (List) The `OR` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **or**: + * `description` - (String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `property` - (String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (String) Schema for any JSON type. + * `property` - (String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (String) Schema for any JSON type. + * `description` - (String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `or` - (List) The `OR` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **or**: + * `and` - (List) The `AND` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **and**: + * `description` - (String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `property` - (String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (String) Schema for any JSON type. + * `description` - (String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `or` - (List) The `OR` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **or**: + * `description` - (String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `property` - (String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (String) Schema for any JSON type. + * `property` - (String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (String) Schema for any JSON type. + * `property` - (String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (String) Schema for any JSON type. + +* `target` - (List) The rule target. +Nested schema for **target**: + * `additional_target_attributes` - (List) The list of targets supported properties. + * Constraints: The maximum length is `99999` items. The minimum length is `0` items. + Nested schema for **additional_target_attributes**: + * `name` - (String) The additional target attribute name. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. + * `value` - (String) The value. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `resource_kind` - (String) The target resource kind. + * Constraints: The maximum length is `99999` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `service_display_name` - (String) The display name of the target service. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `service_name` - (String) The target service name. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `type` - (String) The rule type (allowable values are `user_defined` or `system_defined`). + * Constraints: Allowable values are: `user_defined`, `system_defined`. The maximum length is `14` characters. The minimum length is `12` characters. The value must match regular expression `/[A-Za-z]+_[A-Za-z]+/`. + +* `updated_by` - (String) The user who modified the rule. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + +* `updated_on` - (String) The date when the rule was modified. + +* `version` - (String) The version number of a rule. + * Constraints: The maximum length is `10` characters. The minimum length is `5` characters. The value must match regular expression `/^[0-9][0-9.]*$/`. + diff --git a/website/docs/d/scc_si_note.html.markdown b/website/docs/d/scc_si_note.html.markdown deleted file mode 100644 index 0812f599e3..0000000000 --- a/website/docs/d/scc_si_note.html.markdown +++ /dev/null @@ -1,123 +0,0 @@ ---- -layout: "ibm" -subcategory: "Security and Compliance Center" -page_title: "IBM : ibm_scc_si_note" -description: |- - Get information about scc_si_note ---- - -# DEPRECATED -Security and Compliance Center - Security Insights has now deprecated, backend services are no longer available. The docs will be removed in next release. - -# ibm_scc_si_note - -Provides a read-only data source for scc_si_note. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. - -## Example usage - -```terraform -data "ibm_scc_si_note" "scc_si_note" { - note_id = "note_id" - provider_id = "provider_id" -} -``` - -## Argument reference - -Review the argument reference that you can specify for your data source. - -* `account_id` - (Optional, String) Account ID is optional, if not provided value will be inferred from the token retrieved from the IBM Cloud API key. -* `note_id` - (Required, Forces new resource, String) Second part of note `name`: providers/{provider_id}/notes/{note_id}. -* `provider_id` - (Required, Forces new resource, String) Part of the parent. This field contains the provider ID. For example: providers/{provider_id}. - -## Attribute reference - -In addition to all argument references listed, you can access the following attribute references after your data source is created. - -* `id` - The unique identifier of the scc_si_note. -* `card` - (Optional, List) Card provides details about a card kind of note. -Nested scheme for **card**: - * `section` - (Required, String) The section this card belongs to. - * Constraints: The maximum length is `30` characters. - * `title` - (Required, String) The title of this card. - * Constraints: The maximum length is `28` characters. - * `subtitle` - (Required, String) The subtitle of this card. - * Constraints: The maximum length is `30` characters. - * `order` - (Optional, Integer) The order of the card in which it will appear on SA dashboard in the mentioned section. - * Constraints: Allowable values are: 1, 2, 3, 4, 5, 6 - * `finding_note_names` - (Required, List) The finding note names associated to this card. - * `requires_configuration` - (Optional, Boolean) - * Constraints: The default value is `false`. - * `badge_text` - (Optional, String) The text associated to the card's badge. - * `badge_image` - (Optional, String) The base64 content of the image associated to the card's badge. - * `elements` - (Required, List) The elements of this card. - Nested scheme for **elements**: - * `text` - (Optional, String) The text of this card element. - * Constraints: The maximum length is `60` characters. - * `kind` - (Optional, String) Kind of element- NUMERIC: Single numeric value- BREAKDOWN: Breakdown of numeric values- TIME_SERIES: Time-series of numeric values. - * Constraints: The default value is `NUMERIC`. Allowable values are: NUMERIC, BREAKDOWN, TIME_SERIES - * `default_time_range` - (Optional, String) The default time range of this card element. - * Constraints: The default value is `4d`. Allowable values are: 1d, 2d, 3d, 4d - * `value_type` - (Optional, List) - Nested scheme for **value_type**: - * `kind` - (Optional, String) Kind of element- KPI: Kind of value derived from a KPI occurrence. - * Constraints: Allowable values are: KPI - * `kpi_note_name` - (Optional, String) The name of the kpi note associated to the occurrence with the value for this card element value type. - * `text` - (Optional, String) The text of this element type. - * Constraints: The default value is `label`. The maximum length is `22` characters. - * `finding_note_names` - (Optional, List) the names of the finding note associated that act as filters for counting the occurrences. - * `value_types` - (Optional, List) the value types associated to this card element. - Nested scheme for **value_types**: - * `kind` - (Optional, String) Kind of element- KPI: Kind of value derived from a KPI occurrence. - * Constraints: Allowable values are: KPI - * `kpi_note_name` - (Optional, String) The name of the kpi note associated to the occurrence with the value for this card element value type. - * `text` - (Optional, String) The text of this element type. - * Constraints: The default value is `label`. The maximum length is `22` characters. - * `finding_note_names` - (Optional, List) the names of the finding note associated that act as filters for counting the occurrences. - * `default_interval` - (Optional, String) The default interval of the time series. - * Constraints: The default value is `d`. - -* `create_time` - (Optional, String) Output only. The time this note was created. This field can be used as a filter in list requests. - -* `finding` - (Optional, List) FindingType provides details about a finding note. -Nested scheme for **finding**: - * `severity` - (Required, String) Note provider-assigned severity/impact ranking- LOW: Low Impact- MEDIUM: Medium Impact- HIGH: High Impact- CRITICAL: Critical Impact. - * Constraints: Allowable values are: LOW, MEDIUM, HIGH, CRITICAL - * `next_steps` - (Optional, List) Common remediation steps for the finding of this type. - Nested scheme for **next_steps**: - * `title` - (Optional, String) Title of this next step. - * `url` - (Optional, String) The URL associated to this next steps. - -* `kind` - (Required, String) The type of note. Use this field to filter notes and occurences by kind. - FINDING: The note and occurrence represent a finding. - KPI: The note and occurrence represent a KPI value. - CARD: The note represents a card showing findings and related metric values. - CARD_CONFIGURED: The note represents a card configured for a user account. - SECTION: The note represents a section in a dashboard. - * Constraints: Allowable values are: FINDING, KPI, CARD, CARD_CONFIGURED, SECTION - -* `kpi` - (Optional, List) KpiType provides details about a KPI note. -Nested scheme for **kpi**: - * `aggregation_type` - (Required, String) The aggregation type of the KPI values. - SUM: A single-value metrics aggregation type that sums up numeric values that are extracted from KPI occurrences. - * Constraints: The default value is `SUM`. Allowable values are: SUM - -* `long_description` - (Required, String) A more detailed description of your note. - -* `related_url` - (Optional, List) -Nested scheme for **related_url**: - * `label` - (Required, String) Label to describe usage of the URL. - * `url` - (Required, String) The URL that you want to associate with the note. - -* `reported_by` - (Required, List) The entity reporting a note. -Nested scheme for **reported_by**: - * `id` - (Required, String) The id of this reporter. - * `title` - (Required, String) The title of this reporter. - * `url` - (Optional, String) The url of this reporter. - -* `section` - (Optional, List) Card provides details about a card kind of note. -Nested scheme for **section**: - * `title` - (Required, String) The title of this section. - * `image` - (Required, String) The image of this section. - -* `shared` - (Optional, Boolean) True if this note can be shared by multiple accounts. - * Constraints: The default value is `true`. - -* `short_description` - (Required, String) A one sentence description of your note. - -* `update_time` - (Optional, String) Output only. The time this note was last updated. This field can be used as a filter in list requests. - diff --git a/website/docs/d/scc_si_notes.html.markdown b/website/docs/d/scc_si_notes.html.markdown deleted file mode 100644 index 72056ffd05..0000000000 --- a/website/docs/d/scc_si_notes.html.markdown +++ /dev/null @@ -1,125 +0,0 @@ ---- -layout: "ibm" -subcategory: "Security and Compliance Center" -page_title: "IBM : ibm_scc_si_notes" -description: |- - Get information about scc_si_notes ---- - -# DEPRECATED -Security and Compliance Center - Security Insights has now deprecated, backend services are no longer available. The docs will be removed in next release. - -# ibm_scc_si_notes - -Provides a read-only data source for scc_si_notes. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. - -## Example usage - -```terraform -data "ibm_scc_si_notes" "notes" { - provider_id = "tf-test" -} -``` - -## Argument reference - -Review the argument reference that you can specify for your data source. - -* `account_id` - (Optional, String) Account ID is optional, if not provided value will be inferred from the token retrieved from the IBM Cloud API key. -* `provider_id` - (Required, Forces new resource, String) Part of the parent. This field contains the provider ID. For example: providers/{provider_id}. -* `pages_size` - (Optional, String) Number of notes to return in the list. -* `page_token` - (Optional, String) Token to provide to skip to a particular spot in the list. - -## Attribute reference - -In addition to all argument references listed, you can access the following attribute references after your data source is created. - -* `id` - The unique identifier of the scc_si_note. -* `notes`: (Optional, List) The notes requested. -Nested scheme for **notes**: - * `card` - (Optional, List) Card provides details about a card kind of note. - Nested scheme for **card**: - * `section` - (Required, String) The section this card belongs to. - * Constraints: The maximum length is `30` characters. - * `title` - (Required, String) The title of this card. - * Constraints: The maximum length is `28` characters. - * `subtitle` - (Required, String) The subtitle of this card. - * Constraints: The maximum length is `30` characters. - * `order` - (Optional, Integer) The order of the card in which it will appear on SA dashboard in the mentioned section. - * Constraints: Allowable values are: 1, 2, 3, 4, 5, 6 - * `finding_note_names` - (Required, List) The finding note names associated to this card. - * `requires_configuration` - (Optional, Boolean) - * Constraints: The default value is `false`. - * `badge_text` - (Optional, String) The text associated to the card's badge. - * `badge_image` - (Optional, String) The base64 content of the image associated to the card's badge. - * `elements` - (Required, List) The elements of this card. - Nested scheme for **elements**: - * `text` - (Optional, String) The text of this card element. - * Constraints: The maximum length is `60` characters. - * `kind` - (Optional, String) Kind of element- NUMERIC: Single numeric value- BREAKDOWN: Breakdown of numeric values- TIME_SERIES: Time-series of numeric values. - * Constraints: The default value is `NUMERIC`. Allowable values are: NUMERIC, BREAKDOWN, TIME_SERIES - * `default_time_range` - (Optional, String) The default time range of this card element. - * Constraints: The default value is `4d`. Allowable values are: 1d, 2d, 3d, 4d - * `value_type` - (Optional, List) - Nested scheme for **value_type**: - * `kind` - (Optional, String) Kind of element- KPI: Kind of value derived from a KPI occurrence. - * Constraints: Allowable values are: KPI - * `kpi_note_name` - (Optional, String) The name of the kpi note associated to the occurrence with the value for this card element value type. - * `text` - (Optional, String) The text of this element type. - * Constraints: The default value is `label`. The maximum length is `22` characters. - * `finding_note_names` - (Optional, List) the names of the finding note associated that act as filters for counting the occurrences. - * `value_types` - (Optional, List) the value types associated to this card element. - Nested scheme for **value_types**: - * `kind` - (Optional, String) Kind of element- KPI: Kind of value derived from a KPI occurrence. - * Constraints: Allowable values are: KPI - * `kpi_note_name` - (Optional, String) The name of the kpi note associated to the occurrence with the value for this card element value type. - * `text` - (Optional, String) The text of this element type. - * Constraints: The default value is `label`. The maximum length is `22` characters. - * `finding_note_names` - (Optional, List) the names of the finding note associated that act as filters for counting the occurrences. - * `default_interval` - (Optional, String) The default interval of the time series. - * Constraints: The default value is `d`. - - * `create_time` - (Optional, String) Output only. The time this note was created. This field can be used as a filter in list requests. - - * `finding` - (Optional, List) FindingType provides details about a finding note. - Nested scheme for **finding**: - * `severity` - (Required, String) Note provider-assigned severity/impact ranking- LOW: Low Impact- MEDIUM: Medium Impact- HIGH: High Impact- CRITICAL: Critical Impact. - * Constraints: Allowable values are: LOW, MEDIUM, HIGH, CRITICAL - * `next_steps` - (Optional, List) Common remediation steps for the finding of this type. - Nested scheme for **next_steps**: - * `title` - (Optional, String) Title of this next step. - * `url` - (Optional, String) The URL associated to this next steps. - - * `kind` - (Required, String) The type of note. Use this field to filter notes and occurences by kind. - FINDING: The note and occurrence represent a finding. - KPI: The note and occurrence represent a KPI value. - CARD: The note represents a card showing findings and related metric values. - CARD_CONFIGURED: The note represents a card configured for a user account. - SECTION: The note represents a section in a dashboard. - * Constraints: Allowable values are: FINDING, KPI, CARD, CARD_CONFIGURED, SECTION - - * `kpi` - (Optional, List) KpiType provides details about a KPI note. - Nested scheme for **kpi**: - * `aggregation_type` - (Required, String) The aggregation type of the KPI values. - SUM: A single-value metrics aggregation type that sums up numeric values that are extracted from KPI occurrences. - * Constraints: The default value is `SUM`. Allowable values are: SUM - - * `long_description` - (Required, String) A more detailed description of your note. - - * `related_url` - (Optional, List) - Nested scheme for **related_url**: - * `label` - (Required, String) Label to describe usage of the URL. - * `url` - (Required, String) The URL that you want to associate with the note. - - * `reported_by` - (Required, List) The entity reporting a note. - Nested scheme for **reported_by**: - * `id` - (Required, String) The id of this reporter. - * `title` - (Required, String) The title of this reporter. - * `url` - (Optional, String) The url of this reporter. - - * `section` - (Optional, List) Card provides details about a card kind of note. - Nested scheme for **section**: - * `title` - (Required, String) The title of this section. - * `image` - (Required, String) The image of this section. - - * `shared` - (Optional, Boolean) True if this note can be shared by multiple accounts. - * Constraints: The default value is `true`. - - * `short_description` - (Required, String) A one sentence description of your note. - - * `update_time` - (Optional, String) Output only. The time this note was last updated. This field can be used as a filter in list requests. - diff --git a/website/docs/d/scc_si_occurrence.html.markdown b/website/docs/d/scc_si_occurrence.html.markdown deleted file mode 100644 index f5061caa23..0000000000 --- a/website/docs/d/scc_si_occurrence.html.markdown +++ /dev/null @@ -1,106 +0,0 @@ ---- -layout: "ibm" -subcategory: "Security and Compliance Center" -page_title: "IBM : ibm_scc_si_occurence" -description: |- - Get information about Security and Compliance Center ---- - -# DEPRECATED -Security and Compliance Center - Security Insights has now deprecated, backend services are no longer available. The docs will be removed in next release. - -# ibm_scc_si_occurence - -Retrieve information about a Security and Compliance Center occurrence. For more information, about Security and Compliance Center, see [getting started with Security and Compliance Center](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-getting-started). - -## Example usage - -```terraform -data "ibm_scc_si_occurence" "scc_si_occurence" { - occurrence_id = "occurrence_id" - provider_id = "provider_id" -} -``` - -## Argument reference - -Review the argument reference that you can specify for your data source. - -- `account_id` - (Optional, String) Account ID is optional, if not provided value will be inferred from the token retrieved from the IBM Cloud API key. -- `occurrence_id` - (Required, Forces new resource, String) Second part of occurrence `name`: **providers/{provider_id}/occurrences/{occurrence_id}**. -- `provider_id` - (Required, Forces new resource, String) Part of the parent. This field contains the provider ID. For example: **providers/{provider_id}**. - -## Attribute reference - -In addition to all argument references listed, you can access the following attribute references after your data source is created. - -- `id` - The unique identifier of the scc_si_occurence. -- `context` - (Optional, List) - - Nested scheme for **context**: - - `component_name` - (Optional, String) The name of the component the occurrence applies to. - - `environment_name` - (Optional, String) The name of the environment the occurrence applies to. - - `region` - (Optional, String) The IBM Cloud region. - - `resource_crn` - (Optional, String) The resource CRN (e.g. certificate CRN, image CRN). - - `resource_id` - (Optional, String) The resource ID, in case the CRN is not available. - - `resource_name` - (Optional, String) The user-friendly resource name. - - `resource_type` - (Optional, String) The resource type name (e.g. Pod, Cluster, Certificate, Image). - - `service_crn` - (Optional, String) The service CRN (e.g. CertMgr Instance CRN). - - `service_name` - (Optional, String) The service name (e.g. CertMgr). - - `toolchain_id` - (Optional, String) The id of the toolchain the occurrence applies to. - -- `create_time` - (Optional, String) Output only. The time this `Occurrence` was created. - -- `finding` - (Optional, List) Finding provides details about a finding occurrence. - - Nested scheme for **finding**: - - `certainty` - (Optional, String) Note provider-assigned confidence on the validity of an occurrence- LOW: Low Certainty- MEDIUM: Medium Certainty- HIGH: High Certainty. - - Constraints: Allowable values are: `LOW`, `MEDIUM`, `HIGH`. - - `data_transferred` - (Optional, List) It provides details about data transferred between clients and servers. - - Nested scheme for **data_transferred**: - - `client_bytes` - (Optional, Integer) The number of client bytes transferred. - - `client_packets` - (Optional, Integer) The number of client packets transferred. - - `server_bytes` - (Optional, Integer) The number of server bytes transferred. - - `server_packets` - (Optional, Integer) The number of server packets transferred. - - `network_connection` - (Optional, List) It provides details about a network connection. - - Nested scheme for **network_connection**: - - `client` - (Optional, List) It provides details about a socket address. - - Nested scheme for **client**: - - `address` - (Required, String) The IP address of this socket address. - - `port` - (Optional, Integer) The port number of this socket address. - - `direction` - (Optional, String) The direction of this network connection. - - `protocol` - (Optional, String) The protocol of this network connection. - - `server` - (Optional, List) It provides details about a socket address. - - Nested scheme for **server**: - - `address` - (Required, String) The IP address of this socket address. - - `port` - (Optional, Integer) The port number of this socket address. - - `next_steps` - (Optional, List) Remediation steps for the issues reported in this finding. They override the note's next steps. - - Nested scheme for **next_steps**: - - `title` - (Optional, String) Title of this next step. - - `url` - (Optional, String) The URL associated to this next steps. - - `severity` - (Optional, String) Note provider-assigned severity/impact ranking- LOW: Low Impact- MEDIUM: Medium Impact- HIGH: High Impact- CRITICAL: Critical Impact. - - Constraints: Allowable values are: `LOW`, `MEDIUM`, `HIGH`, `CRITICAL`. - -- `id` - (Required, String) The id of the occurrence. - -- `kind` - (Required, String) The type of note. Use this field to filter notes and occurences by kind. - FINDING: The note and occurrence represent a finding. - KPI: The note and occurrence represent a KPI value. - CARD: The note represents a card showing findings and related metric values. - CARD_CONFIGURED: The note represents a card configured for a user account. - SECTION: The note represents a section in a dashboard. - - Constraints: Allowable values are: `FINDING`, `KPI`, `CARD`, `CARD_CONFIGURED`, `SECTION`. - -- `kpi` - (Optional, List) Kpi provides details about a KPI occurrence. - - Nested scheme for **kpi**: - - `total` - (Optional, Float) The total value of this KPI. - - `value` - (Required, Float) The value of this KPI. - -- `note_name` - (Required, String) An analysis note associated with this image, in the form "{account_id}/providers/{provider_id}/notes/{note_id}" This field can be used as a filter in list requests. - -- `remediation` - (Optional, String) A description of actions that can be taken to remedy the `Note`. - -- `resource_url` - (Optional, String) The unique URL of the resource, image or the container, for which the `Occurrence` applies. For example, https://gcr.io/provider/image@sha256:foo. This field can be used as a filter in list requests. - -- `update_time` - (Optional, String) Output only. The time this `Occurrence` was last updated. \ No newline at end of file diff --git a/website/docs/d/scc_si_occurrences.html.markdown b/website/docs/d/scc_si_occurrences.html.markdown deleted file mode 100644 index cff8e82712..0000000000 --- a/website/docs/d/scc_si_occurrences.html.markdown +++ /dev/null @@ -1,106 +0,0 @@ ---- -layout: "ibm" -subcategory: "Security and Compliance Center" -page_title: "IBM : ibm_scc_si_occurrences" -description: |- - Get information about Security and Compliance Center ---- - -# DEPRECATED -Security and Compliance Center - Security Insights has now deprecated, backend services are no longer available. The docs will be removed in next release. - -# ibm_scc_si_occurences - -Retrieve information about a Security and Compliance Center occurrences. For more information, about Security and Compliance Center, see [custom findings](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-setup_custom). - -## Example usage - -```terraform -data "ibm_scc_si_occurences" "scc_si_occurences" { - provider_id = "tf-test" -} -``` - -## Argument reference - -Review the argument reference that you can specify for your data source. - -- `account_id` - (Optional, String) Account ID is optional, if not provided value will be inferred from the token retrieved from the IBM Cloud API key. -- `provider_id` - (Required, Forces new resource, String) Part of the parent. This field contains the provider ID. For example: providers/{provider_id}. -- `pages_size` - (Optional, String) Number of notes to return in the list. -- `page_token` - (Optional, String) Token to provide to skip to a particular spot in the list. - -## Attribute reference - -In addition to all argument references listed, you can access the following attribute references after your data source is created. - -- `id` - The unique identifier of the `scc_si_occurences`. -- `context` - (Optional, List) - - Nested scheme for **context**: - - `component_name` - (Optional, String) The name of the component the occurrence applies to. - - `environment_name` - (Optional, String) The name of the environment the occurrence applies to. - - `region` - (Optional, String) The IBM Cloud region. - - `resource_crn` - (Optional, String) The resource CRN For example certificate CRN, image CRN. - - `resource_id` - (Optional, String) The resource ID, in case the CRN is not available. - - `resource_name` - (Optional, String) The user-friendly resource name. - - `resource_type` - (Optional, String) The resource type name For example Pod, Cluster, Certificate, Image. - - `service_crn` - (Optional, String) The service CRN For example CertMgr Instance CRN. - - `service_name` - (Optional, String) The service name For example CertMgr. - - `toolchain_id` - (Optional, String) The ID of the toolchain the occurrence applies to. - -- `create_time` - (Optional, String) Output only. The time this `Occurrence` was created. - -- `finding` - (Optional, List) Finding provides details about a finding occurrence. - - Nested scheme for **finding**: - - `certainty` - (Optional, String) Note provider-assigned confidence on the validity of an occurrence- LOW: Low Certainty- MEDIUM: Medium Certainty- HIGH: High Certainty. - - Constraints: Allowable values are: `LOW`, `MEDIUM`, `HIGH`. - - `data_transferred` - (Optional, List) It provides details about data transferred between clients and servers. - - Nested scheme for **data_transferred**: - - `client_bytes` - (Optional, Integer) The number of client bytes transferred. - - `client_packets` - (Optional, Integer) The number of client packets transferred. - - `server_bytes` - (Optional, Integer) The number of server bytes transferred. - - `server_packets` - (Optional, Integer) The number of server packets transferred. - - `network_connection` - (Optional, List) It provides details about a network connection. - - Nested scheme for **network_connection**: - - `client` - (Optional, List) It provides details about a socket address. - - Nested scheme for **client**: - - `address` - (Required, String) The IP address of this socket address. - - `port` - (Optional, Integer) The port number of this socket address. - - `direction` - (Optional, String) The direction of this network connection. - - `protocol` - (Optional, String) The protocol of this network connection. - - `server` - (Optional, List) It provides details about a socket address. - - Nested scheme for **server**: - - `address` - (Required, String) The IP address of this socket address. - - `port` - (Optional, Integer) The port number of this socket address. - - `next_steps` - (Optional, List) Remediation steps for the issues reported in this finding. They override the note's next steps. - - Nested scheme for **next_steps**: - - `title` - (Optional, String) Title of this next step. - - `url` - (Optional, String) The URL associated to this next steps. - - `severity` - (Optional, String) Note provider-assigned severity/impact ranking- LOW: Low Impact- MEDIUM: Medium Impact- HIGH: High Impact- CRITICAL: Critical Impact. - - Constraints: Allowable values are: `LOW`, `MEDIUM`, `HIGH`, `CRITICAL`. - -- `id` - (Required, String) The ID of the occurrence. - -- `kind` - (Required, String) The type of note. Use this field to filter notes and occurences by kind. - FINDING: The note and occurrence represent a finding. - KPI: The note and occurrence represent a KPI value. - CARD: The note represents a card showing findings and related metric values. - CARD_CONFIGURED: The note represents a card configured for a user account. - SECTION: The note represents a section in a dashboard. - - Constraints: Allowable values are: `FINDING`, `KPI`, `CARD`, `CARD_CONFIGURED`, `SECTION`. - -- `kpi` - (Optional, List) Kpi provides details about a KPI occurrence. -Nested scheme for **kpi**: - - `total` - (Optional, Float) The total value of this KPI. - - `value` - (Required, Float) The value of this KPI. - -- `note_name` - (Required, String) An analysis note associated with this image, in the form **{account_id}/providers/{provider_id}/notes/{note_id}** This field can be used as a filter in list requests. - -- `remediation` - (Optional, String) A description of actions that can be taken to remedy the `Note`. - -- `resource_url` - (Optional, String) The unique URL of the resource, image or the container, for which the `Occurrence` applies. For example, https://gcr.io/provider/image@sha256:foo. This field can be used as a filter in list requests. - -- `update_time` - (Optional, String) Output only. The time this `Occurrence` was last updated. - diff --git a/website/docs/d/scc_si_providers.html.markdown b/website/docs/d/scc_si_providers.html.markdown deleted file mode 100644 index a46a8d5e5e..0000000000 --- a/website/docs/d/scc_si_providers.html.markdown +++ /dev/null @@ -1,46 +0,0 @@ ---- -layout: "ibm" -subcategory: "Security and Compliance Center" -page_title: "IBM : ibm_scc_si_providers" -description: |- - Get information about scc_si_providers ---- - -# DEPRECATED -Security and Compliance Center - Security Insights has now deprecated, backend services are no longer available. The docs will be removed in next release. - -# ibm_scc_si_providers - -Provides a read-only data source for scc_si_providers. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. - -## Example usage - -```terraform -data "ibm_scc_si_providers" "providers" { - limit = 4 -} -``` - -## Argument reference - -Review the argument reference that you can specify for your data source. - -* `limit` - (Optional, String) Limit the number of the returned documents to the specified number. -* `skip` - (Optional, String) The offset is the index of the item from which you want to start returning data from. Default is 0. - -## Attribute reference - -In addition to all argument references listed, you can access the following attribute references after your data source is created. - -* `id` - The unique identifier of the scc_si_providers. -* `limit` - (Optional, Integer) The number of elements returned in the current instance. The default is 200. - -* `providers` - (Optional, List) The providers requested. -Nested scheme for **providers**: - * `name` - (Required, String) The name of the provider in the form '{account_id}/providers/{provider_id}'. - * `id` - (Required, String) The ID of the provider. - -* `skip` - (Optional, Integer) The offset is the index of the item from which you want to start returning data from. The default is 0. - -* `total_count` - (Optional, Integer) The total number of providers available. - diff --git a/website/docs/r/scc_account_settings.html.markdown b/website/docs/r/scc_account_settings.html.markdown deleted file mode 100644 index 5c4bab92c3..0000000000 --- a/website/docs/r/scc_account_settings.html.markdown +++ /dev/null @@ -1,56 +0,0 @@ ---- -layout: "ibm" -page_title: "IBM : ibm_scc_account_settings" -description: |- - Manages the account settings scc_account_settings -subcategory: "Security and Compliance Center" ---- - -# ibm_scc_account_settings - -Provides a resource for scc_account_settings. This allows scc_account_settings to be created, updated and deleted. - -~> **NOTE**: exporting out the environmental variable `IBM_CLOUD_SCC_ADMIN_API_ENDPOINT` will help out if the account fails to resolve(e.g. `export IBMCLOUD_SCC_ADMIN_API_ENDPOINT=https://compliance.cloud.ibm.com`) - -## Example Usage - -```terraform -resource "ibm_scc_account_settings" "scc_account_settings" { - location { - location_id = "uk" - } - event_notifications { - instance_crn = "" // Optional field - } -} -``` - -## Argument Reference - -Review the argument reference that you can specify for your resource. - -> `location_id` will be Deprecated in the near future. Please adjust to using the argument `location` -* `location_id` **Deprecated** - (Optional, Forces new resource, String) The programatic ID of the location that you want to work in. - * Constraints: Allowable values are: `us`, `eu`, `uk`. -* `event_notifications` - (Optional, List) The Event Notification settings to register. -Nested scheme for **event_notifications**: - * `instance_crn` - (Optional, String) The Cloud Resource Name (CRN) of the Event Notifications instance that you want to connect. If this field is left blank, no Event Notifications instance will be used. -* `location` - (Optional, List) Location Settings. -Nested scheme for **location**: - * `location_id` - (Required, String) The programatic ID of the location that you want to work in. - * Constraints: Allowable values are: `us`, `eu`, `uk`. - -## Attribute Reference - -In addition to all argument references listed, you can access the following attribute references after your resource is created. - -* `id` - The unique identifier of the scc_account_settings. - -## Import - -You can import the `ibm_scc_account_settings` resource by using `terraform import `, with the `` being anything you want. - -# Syntax -``` -$ terraform import ibm_scc_account_settings.scc_account_settings -``` diff --git a/website/docs/r/scc_control_library.html.markdown b/website/docs/r/scc_control_library.html.markdown new file mode 100644 index 0000000000..7761ae9f96 --- /dev/null +++ b/website/docs/r/scc_control_library.html.markdown @@ -0,0 +1,167 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_control_library" +description: |- + Manages scc_control_library. +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_control_library + +Create, update, and delete control libraries by using this resource. + +## Example Usage + +```hcl +resource "ibm_scc_control_library" "scc_control_library_instance" { + control_library_description = "control_library_description" + control_library_name = "control_library_name" + control_library_type = "predefined" + controls { + control_name = "control_name" + control_id = "1fa45e17-9322-4e6c-bbd6-1c51db08e790" + control_description = "control_description" + control_category = "control_category" + control_parent = "control_parent" + control_tags = [ "control_tags" ] + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + component_name = "componenet_name" + environment = "environment" + control_specification_description = "control_specification_description" + assessments_count = 1 + assessments { + assessment_id = "assessment_id" + assessment_method = "assessment_method" + assessment_type = "assessment_type" + assessment_description = "assessment_description" + parameter_count = 1 + parameters { + parameter_name = "parameter_name" + parameter_display_name = "parameter_display_name" + parameter_type = "string" + } + } + } + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_requirement = true + status = "enabled" + } + version_group_label = "e0923045-f00d-44de-b49b-6f1f0e8033cc" +} +``` + +## Argument Reference + +You can specify the following arguments for this resource. + +* `control_library_description` - (Required, String) The control library description. + * Constraints: The maximum length is `256` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. +* `control_library_name` - (Required, String) The control library name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_\\s\\-]*$/`. +* `control_library_type` - (Required, String) The control library type. + * Constraints: Allowable values are: `predefined`, `custom`. +* `control_library_version` - (Optional, String) The control library version. + * Constraints: The maximum length is `64` characters. The minimum length is `5` characters. The value must match regular expression `/^[a-zA-Z0-9_\\-.]*$/`. +* `controls` - (Required, List) The list of controls in a control library. + * Constraints: The maximum length is `1200` items. The minimum length is `0` items. +Nested schema for **controls**: + * `control_category` - (Optional, String) The control category. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,\\-\\s]*$/`. + * `control_description` - (Optional, String) The control description. + * Constraints: The maximum length is `1024` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'"\\s\\-\\[\\]]+$/`. + * `control_docs` - (Optional, List) The control documentation. + Nested schema for **control_docs**: + * `control_docs_id` - (Optional, String) The ID of the control documentation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_docs_type` - (Optional, String) The type of control documentation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_id` - (Optional, String) The control name. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_name` - (Optional, String) The ID of the control library that contains the profile. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_parent` - (Optional, String) The parent control. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]*/`. + * `control_requirement` - (Optional, Boolean) Is this a control that can be automated or manually evaluated. + * `control_specifications` - (Optional, List) The control specifications. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. + Nested schema for **control_specifications**: + * `assessments` - (Optional, List) The assessments. + * Constraints: The maximum length is `10` items. The minimum length is `0` items. + Nested schema for **assessments**: + * `assessment_description` - (Optional, String) The assessment description. + * Constraints: The maximum length is `256` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `assessment_id` - (Optional, String) The assessment ID. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_method` - (Optional, String) The assessment method. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_type` - (Optional, String) The assessment type. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `parameter_count` - (Optional, Integer) The parameter count. + * `parameters` - (Optional, List) The parameters. + * Constraints: The maximum length is `512` items. The minimum length is `0` items. + Nested schema for **parameters**: + * `parameter_display_name` - (Optional, String) The parameter display name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `parameter_name` - (Optional, String) The parameter name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_\\s\\-]*$/`. + * `parameter_type` - (Optional, String) The parameter type. + * Constraints: Allowable values are: `string`, `numeric`, `general`, `boolean`, `string_list`, `ip_list`, `timestamp`. + * `assessments_count` - (Optional, Integer) The number of assessments. + * `component_name` - (Optional, String) The component name. + * Constraints: The maximum length is `512` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `component_id` - (Optional, String) The component ID. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `control_specification_description` - (Optional, String) The control specifications description. + * Constraints: The maximum length is `1024` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `control_specification_id` - (Optional, String) The control specification ID. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. + * `environment` - (Optional, String) The control specifications environment. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `responsibility` - (Optional, String) The responsibility for managing the control. + * Constraints: Allowable values are: `user`. + * `control_tags` - (Optional, List) The control tags. + * Constraints: The list items must match regular expression `/^[a-zA-Z0-9_,'"\\s\\-\\[\\]]+$/`. The maximum length is `512` items. The minimum length is `0` items. + * `status` - (Optional, String) The control status. + * Constraints: Allowable values are: `enabled`, `disabled`. + +* `latest` - (Optional, Boolean) The latest version of the control library. +* `version_group_label` - (Optional, String) The version group label. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. + +## Attribute Reference + +After your resource is created, you can read values from the listed arguments and the following attributes. + +* `controls_count` - (Optional, Integer) The number of controls. +* `id` - The unique identifier of the scc_control_library. +* `account_id` - (String) The account ID. + * Constraints: The maximum length is `32` characters. The minimum length is `0` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. +* `control_parents_count` - (Integer) The number of parent controls in the control library. +* `created_by` - (String) The user who created the control library. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. +* `created_on` - (String) The date when the control library was created. +* `hierarchy_enabled` - (Boolean) The indication of whether hierarchy is enabled for the control library. +* `updated_by` - (String) The user who updated the control library. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. +* `updated_on` - (String) The date when the control library was updated. + + +## Import + +You can import the `ibm_scc_control_library` resource by using `id`. The control library ID. + +# Syntax +``` +$ terraform import ibm_scc_control_library.scc_control_library +``` + +# Example +``` +$ terraform import ibm_scc_control_library.scc_control_library f3517159-889e-4781-819a-89d89b747c85 +``` diff --git a/website/docs/r/scc_profile.html.markdown b/website/docs/r/scc_profile.html.markdown new file mode 100644 index 0000000000..8226fdf06d --- /dev/null +++ b/website/docs/r/scc_profile.html.markdown @@ -0,0 +1,186 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_profile" +description: |- + Manages scc_profile. +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_profile + +Create, update, and delete profiles with this resource. + +## Example Usage + +```hcl +resource "ibm_scc_profile" "scc_profile_instance" { + controls { + control_library_id = "e98a56ff-dc24-41d4-9875-1e188e2da6cd" + control_id = "5C453578-E9A1-421E-AD0F-C6AFCDD67CCF" + control_library_version = "control_library_version" + control_name = "control_name" + control_description = "control_description" + control_category = "control_category" + control_parent = "control_parent" + control_requirement = true + control_docs { + control_docs_id = "control_docs_id" + control_docs_type = "control_docs_type" + } + control_specifications_count = 1 + control_specifications { + control_specification_id = "f3517159-889e-4781-819a-89d89b747c85" + responsibility = "user" + component_id = "f3517159-889e-4781-819a-89d89b747c85" + componenet_name = "componenet_name" + environment = "environment" + control_specification_description = "control_specification_description" + assessments_count = 1 + assessments { + assessment_id = "assessment_id" + assessment_method = "assessment_method" + assessment_type = "assessment_type" + assessment_description = "assessment_description" + parameter_count = 1 + parameters { + parameter_name = "parameter_name" + parameter_display_name = "parameter_display_name" + parameter_type = "string" + } + } + } + } + default_parameters { + assessment_type = "assessment_type" + assessment_id = "assessment_id" + parameter_name = "parameter_name" + parameter_default_value = "parameter_default_value" + parameter_display_name = "parameter_display_name" + parameter_type = "string" + } + profile_description = "profile_description" + profile_name = "profile_name" + profile_type = "predefined" +} +``` + +## Argument Reference + +You can specify the following arguments for this resource. + +* `controls` - (Required, List) The array of controls that are used to create the profile. + * Constraints: The maximum length is `600` items. The minimum length is `0` items. +Nested schema for **controls**: + * `control_category` - (Optional, String) The control category. + * Constraints: The maximum length is `512` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_description` - (Optional, String) The control description. + * Constraints: The maximum length is `1024` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_docs` - (Optional, List) The control documentation. + Nested schema for **control_docs**: + * `control_docs_id` - (Optional, String) The ID of the control documentation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_docs_type` - (Optional, String) The type of control documentation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_id` - (Optional, String) The unique ID of the control library that contains the profile. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/[A-Z0-9]+/`. + * `control_library_id` - (Optional, String) The ID of the control library that contains the profile. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_library_version` - (Optional, String) The most recent version of the control library. + * Constraints: The maximum length is `36` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_name` - (Optional, String) The control name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `control_parent` - (Optional, String) The parent control. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]*/`. + * `control_requirement` - (Optional, Boolean) Is this a control that can be automated or manually evaluated. + * `control_specifications` - (Optional, List) The control specifications. + * Constraints: The maximum length is `400` items. The minimum length is `0` items. + Nested schema for **control_specifications**: + * `assessments` - (Optional, List) The assessments. + * Constraints: The maximum length is `10` items. The minimum length is `0` items. + Nested schema for **assessments**: + * `assessment_description` - (Optional, String) The assessment description. + * Constraints: The maximum length is `256` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `assessment_id` - (Optional, String) The assessment ID. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_method` - (Optional, String) The assessment method. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_type` - (Optional, String) The assessment type. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `parameter_count` - (Optional, Integer) The parameter count. + * `parameters` - (Optional, List) The parameters. + * Constraints: The maximum length is `512` items. The minimum length is `0` items. + Nested schema for **parameters**: + * `parameter_display_name` - (Optional, String) The parameter display name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `parameter_name` - (Optional, String) The parameter name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_\\s\\-]*$/`. + * `parameter_type` - (Optional, String) The parameter type. + * Constraints: Allowable values are: `string`, `numeric`, `general`, `boolean`, `string_list`, `ip_list`, `timestamp`. + * `assessments_count` - (Optional, Integer) The number of assessments. + * `componenet_name` - (Optional, String) The component name. + * Constraints: The maximum length is `512` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `component_id` - (Optional, String) The component ID. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `control_specification_description` - (Optional, String) The control specifications description. + * Constraints: The maximum length is `1024` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `control_specification_id` - (Optional, String) The control specification ID. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. + * `environment` - (Optional, String) The control specifications environment. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `responsibility` - (Optional, String) The responsibility for managing the control. + * Constraints: Allowable values are: `user`. + * `control_specifications_count` - (Optional, Integer) The number of control specifications. +* `default_parameters` - (Required, List) The default parameters of the profile. + * Constraints: The maximum length is `512` items. The minimum length is `0` items. +Nested schema for **default_parameters**: + * `assessment_id` - (Optional, String) The implementation ID of the parameter. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_type` - (Optional, String) The type of the implementation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `parameter_default_value` - (Optional, String) The default value of the parameter. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'"\\s\\-\\[\\]]+$/`. + * `parameter_display_name` - (Optional, String) The parameter display name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `parameter_name` - (Optional, String) The parameter name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_]*$/`. + * `parameter_type` - (Optional, String) The parameter type. + * Constraints: Allowable values are: `string`, `numeric`, `general`, `boolean`, `string_list`, `ip_list`, `timestamp`. +* `profile_description` - (Required, String) The profile description. + * Constraints: The maximum length is `256` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. +* `profile_name` - (Required, String) The profile name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. +* `profile_type` - (Required, String) The profile type, such as custom or predefined. + * Constraints: Allowable values are: `predefined`, `custom`. + +## 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 scc_profile. +* `attachments_count` - (Integer) The number of attachments related to this profile. +* `control_parents_count` - (Integer) The number of parent controls for the profile. +* `controls_count` - (Integer) The number of controls for the profile. +* `created_by` - (String) The user who created the profile. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. +* `created_on` - (String) The date when the profile was created. +* `hierarchy_enabled` - (Boolean) The indication of whether hierarchy is enabled for the profile. +* `instance_id` - (String) The instance ID. + * Constraints: The maximum length is `36` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. +* `latest` - (Boolean) The latest version of the profile. +* `profile_version` - (String) The version status of the profile. + * Constraints: The maximum length is `64` characters. The minimum length is `5` characters. The value must match regular expression `/^[a-zA-Z0-9_\\-.]*$/`. +* `updated_by` - (String) The user who updated the profile. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. +* `updated_on` - (String) The date when the profile was updated. +* `version_group_label` - (String) The version group label of the profile. + * Constraints: The maximum length is `36` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + + +## Import + +You can import the `ibm_scc_profile` resource by using `id`. The unique ID of the profile. + +# Syntax +``` +$ terraform import ibm_scc_profile.scc_profile +``` diff --git a/website/docs/r/scc_profile_attachment.html.markdown b/website/docs/r/scc_profile_attachment.html.markdown new file mode 100644 index 0000000000..9fb803f686 --- /dev/null +++ b/website/docs/r/scc_profile_attachment.html.markdown @@ -0,0 +1,112 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_profile_attachment" +description: |- + Manages scc_profile_attachment. +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_profile_attachment + +Create, update, and delete profile attachments with this resource. + +## Example Usage + +```hcl +resource "ibm_scc_profile_attachment" "scc_profile_attachment_instance" { + profiles_id = ibm_scc_profile.scc_profile_instance.id +} +``` + +## Argument Reference + +You can specify the following arguments for this resource. + +* `profile_id` - (Required, Forces new resource, String) The profile ID. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/`. +* `scope` - (List) The scope payload for the multi cloud feature. + * Constraints: The maximum length is `8` items. The minimum length is `0` items. +Nested schema for **scope**: + * `environment` - (String) The environment that relates to this scope. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `properties` - (List) The properties supported for scoping by this environment. + * Constraints: The maximum length is `8` items. The minimum length is `0` items. + Nested schema for **properties**: + * `name` - (String) The name of the property. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (String) The value of the property. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. +* `notifications` - (List) The request payload of the attachment notifications. +Nested schema for **notifications**: + * `controls` - (List) The failed controls. + Nested schema for **controls**: + * `failed_control_ids` - (List) The failed control IDs. + * Constraints: The list items must match regular expression `/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$|^$/`. The maximum length is `512` items. The minimum length is `0` items. + * `threshold_limit` - (Integer) The threshold limit. + * `enabled` - (Boolean) enabled notifications. +* `schedule` - (String) The schedule of an attachment evaluation. + * Constraints: Allowable values are: `daily`, `every_7_days`, `every_30_days`. +* `name` - (String) The name of the attachment. + * Constraints: The maximum length is `128` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + +## Attribute Reference + +After your resource is created, you can read values from the listed arguments and the following attributes. + +* `id` - The unique identifier of the scc_profile_attachment. +* `account_id` - (String) The account ID that is associated to the attachment. + * Constraints: The maximum length is `32` characters. The minimum length is `32` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. +* `attachment_id` - (String) The ID of the attachment. + * Constraints: The maximum length is `32` characters. The minimum length is `32` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. +* `attachment_parameters` - (List) The profile parameters for the attachment. + * Constraints: The maximum length is `512` items. The minimum length is `0` items. +Nested schema for **attachment_parameters**: + * `assessment_id` - (String) The implementation ID of the parameter. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `assessment_type` - (String) The type of the implementation. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `parameter_display_name` - (String) The parameter display name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. + * `parameter_name` - (String) The parameter name. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_]*$/`. + * `parameter_type` - (String) The parameter type. + * Constraints: Allowable values are: `string`, `numeric`, `general`, `boolean`, `string_list`, `ip_list`, `timestamp`. + * `parameter_value` - (String) The value of the parameter. + * Constraints: The maximum length is `64` characters. The minimum length is `2` characters. The value must match regular expression `/^[a-zA-Z0-9_,'"\\s\\-\\[\\]]+$/`. +* `created_by` - (String) The user who created the attachment. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. +* `created_on` - (String) The date when the attachment was created. +* `description` - (String) The description for the attachment. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/^[a-zA-Z0-9_,'\\s\\-]*$/`. +* `instance_id` - (String) The instance ID of the account that is associated to the attachment. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$|^$/`. +* `last_scan` - (List) The details of the last scan of an attachment. +Nested schema for **last_scan**: + * `id` - (String) The ID of the last scan of an attachment. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `status` - (String) The status of the last scan of an attachment. + * Constraints: Allowable values are: `in_progress`, `completed`. + * `time` - (String) The time when the last scan started. +* `next_scan_time` - (String) The start time of the next scan. +* `status` - (String) The status of an attachment evaluation. + * Constraints: Allowable values are: `enabled`, `disabled`. +* `updated_by` - (String) The user who updated the attachment. + * Constraints: The maximum length is `255` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9-\\.:,_\\s]*$/`. +* `updated_on` - (String) The date when the attachment was updated. + + +## Import + +You can import the `ibm_scc_profile_attachment` resource by using `id`. +The `id` property can be formed from `profiles_id`, and `attachment_id` in the following format: + +``` +/ +``` +* `profiles_id`: A string. The profile ID. +* `attachment_id`: A string. The attachment ID. + +# Syntax +``` +$ terraform import ibm_scc_profile_attachment.scc_profile_attachment / +``` diff --git a/website/docs/r/scc_provider_type_instance.html.markdown b/website/docs/r/scc_provider_type_instance.html.markdown new file mode 100644 index 0000000000..06eaf1f337 --- /dev/null +++ b/website/docs/r/scc_provider_type_instance.html.markdown @@ -0,0 +1,55 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_scc_provider_type_instance" +description: |- + Manages scc_provider_type_instance. +subcategory: "Security and Compliance Center" +--- + +# ibm_scc_provider_type_instance + +Create, update, and delete provider type instances with this resource. + +## Example Usage + +```hcl +resource "ibm_scc_provider_type_instance" "scc_provider_type_instance_instance" { + attributes = {"wp_crn":"crn:v1:staging:public:sysdig-secure:eu-gb:a/14q5SEnVIbwxzvP4AWPCjr2dJg5BAvPb:d1461d1ae-df1eee12fa81812e0-12-aa259::"} + name = "workload-protection-instance-1" + provider_type_id = "provider_type_id" +} +``` + +## Argument Reference + +You can specify the following arguments for this resource. + +* `attributes` - (Required, Map) The attributes for connecting to the provider type instance. +* `name` - (Required, String) The name for the provider_type instance +* `provider_type_id` - (Required, String) The unique identifier of the provider type instance. + +## 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 scc_provider_type_instance. +* `created_at` - (String) The time when resource was created. +* `type` - (String) The type of the provider type. +* `updated_at` - (String) The time when resource was updated. + + +## Import + +You can import the `ibm_scc_provider_type_instance` resource by using `id`. +The `id` property can be formed from `provider_type_id`, and `provider_type_instance_id` in the following format: + +``` +/ +``` +* `provider_type_id`: A string. The provider type ID. +* `provider_type_instance_id`: A string. The provider type instance ID. + +# Syntax +``` +$ terraform import ibm_scc_provider_type_instance.scc_provider_type_instance / +``` diff --git a/website/docs/r/scc_rule.html.markdown b/website/docs/r/scc_rule.html.markdown index c785534907..41b37572a5 100644 --- a/website/docs/r/scc_rule.html.markdown +++ b/website/docs/r/scc_rule.html.markdown @@ -8,221 +8,186 @@ subcategory: "Security and Compliance Center" # ibm_scc_rule -Provides a resource for scc_rule. This allows scc_rule to be created, updated and deleted. For more information about Security and Compliance Center rules, see [Defining Rules](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-rules-define&interface=ui). +Create, update, and delete rules with this resource. ## Example Usage ```hcl -resource "ibm_scc_rule" "scc_rule_tf_example" { - account_id = "thisIsAFake32CharacterAccountID" - name = "Terraform rule" - description = "Cloud Object Storage buckets can only be created in us-south." - labels = ["example"] - target { - service_name = "cloud-object-storage" - resource_kind = "bucket" +resource "ibm_scc_rule" "scc_rule_instance" { + description = "Example rule" + import { + parameters { + name = "name" + display_name = "display_name" + description = "description" + type = "string" + } } required_config { - // example of a Cloud Object Storage configuration - description = "Cloud Object Storage buckets can only be created in us-south." - property = "location" - operator = "string_equals" - value = "us-south" + description = "description" + and { + or { + description = "description" + property = "property" + operator = "string_equals" + value = "anything as a string" + } + } } - enforcement_actions { - action = "disallow" + target { + service_name = "service_name" + service_display_name = "service_display_name" + resource_kind = "resource_kind" + additional_target_attributes { + name = "name" + operator = "string_equals" + value = "value" + } } + version = "1.0.0" } ``` -In the above example, COS buckets must have `location` set to `us-south` to be compliant. +## Timeouts -## Argument Reference +scc_rule provides the following [Timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) configuration options: -Review the argument reference that you can specify for your resource. - -* `account_id` - (Required, String) Your IBM Cloud account ID, or the account ID that you want to target. -* `name` - (Required, String) A human-readable alias to assign to your rule. - * Constraints: The maximum length is `32` characters. The minimum length is `1` character. -* `description` - (Required, String) An extended description of your rule. - * Constraints: The maximum length is `256` characters. The minimum length is `1` character. -* `labels` - (Optional, List) Labels that you can use to group and search for similar rules, such as those that help you to meet a specific organization guideline. - * Constraints: The maximum length is `32` items. -* `enforcement_actions` - (Optional, List) The actions that the service must run on your behalf when a request to create or modify the target resource does not comply with your conditions. - * Constraints: The maximum length is `1` items. -Nested scheme for **enforcement_actions**: - * `action` - (Required, String) To block a request from completing, use `disallow`. - * Constraints: Allowable values are: `disallow`. -* `target` - (Required, List) The properties that describe the resource that you want the rule or template to target. - Nested scheme for **target**: - * `additional_target_attributes` - (Optional, List) An extra qualifier for the resource kind. When you include additional attributes, only the resources that match the definition are included in the rule or template. - Nested scheme for **additional_target_attributes**: - * `name` - (Required, String) The name of the additional attribute that you want to use to further qualify the target. Options differ depending on the service or resource that you are targeting with a rule or template. For more information, refer to the service documentation. - * `operator` - (Required, String) The way in which the `name` field is compared to its value.There are three types of operators: string, numeric, and boolean. - * Constraints: Allowable values are: - * `string_equals` - * `string_not_equals` - * `string_match` - * `string_not_match` - * `num_equals` - * `num_not_equals` - * `num_less_than` - * `num_less_than_equals` - * `num_greater_than` - * `num_greater_than_equals` - * `is_empty` - * `is_not_empty` - * `is_true` - * `is_false` - * `value` - (Optional, String) The value that you want to apply to `name` field. Options differ depending on the rule or template that you configure. For more information, refer to the service documentation. - * `resource_kind` - (Required, String) The type of resource that you want to target. - * `service_name` - (Required, String) The programmatic name of the IBM Cloud service that you want to target with the rule or template. - * Constraints: The value must match regular expression `/^[a-z-]*$/`. -* `required_config` - (Required, List) -Nested scheme for **required_config**: - * `description` - (Optional, String) - One of the following: - 1. `rule_condition`: - ~> **NOTE**: Currently the `ips_in_range` and `strings_in_list` cannot be used due to a limitation of the scc-go-sdk - * `operator` - (Required, String) The way in which the `property` field is compared to its value. To learn more, see the [docs](/docs/security-compliance?topic=security-compliance-what-is-rule#rule-operators). - * Constraints: Allowable values are: - * `is_true` - * `is_false` - * `is_empty` - * `is_not_empty` - * `string_equals` - * `string_not_equals` - * `string_match` - * `string_not_match` - * `num_equals` - * `num_not_equals` - * `num_less_than` - * `num_less_than_equals` - * `num_greater_than` - * `num_greater_than_equals` - * `property` - (Required, String) A resource configuration variable that describes the property that you want to apply to the target resource.Available options depend on the target service and resource. - * `value` - (Optional, String) The way in which you want your property to be applied. Value options differ depending on the rule that you configure. If you use a boolean operator, you do not need to input a value. - - example schema for using `rule_condition`: - ```terraform - required_config { - description = "test config" - property = "location" - operator = "string_not_equals" - value = "eu-de" - } - ``` - The above example details a `required_config` that has a single rule_condition - 2. `and/or` - (Optional, List) A list of `rule_condition` that should be set for the rule. If `and` is being used, it means that every `rule_condition` in the list must be true. If `or` is being used, it means that at least one `rule_condition` in the list needs to be true. - - ~> **NOTE**: The required_config must have only one of following: `and`, `or`, or `rule_condtion`. These values cannot be mixed with each other at the same depth (i.e. 'or' and 'and' cannot be defined at the same level/depth) - - example schema for using `and/or`: - - - - - - - - - -
Terraform JSON
- - ```hcl - required_config { - description = "test config" - and { // rule_condition[0] - property = "storage_class" - operator = "string_equals" - value = "smart" - } - and { // rule_condition[1] - property = "location" - operator = "string_equals" - value = "us-south" - } - } - ``` - - - - ```json - required_config: { - "description": "test config", - "and": [ - { - "property": "storage_class", - "operator": "string_equals", - "value": "smart" - }, - { - "property": "location", - "operator": "string_equals", - "value": "us-south" - } - ] - } - ``` - -
- The above example details a `required_config` that has two `rule_condition`s and it is equivalent to: - ``` - rule_condtion[0] && rule_condition[1] - ``` - - Replace both `and` with `or` in the example above if you want the following logic: - ``` - rule_condition[0] || rule_condition[1] - ``` - - Users can also create nested rules (with a maximum depth of 2 levels). - Example (with a depth of 2): - ```hcl - required_config { - and { - // A - } - and { - or { - // B - } - or { - // C - } - } - ``` - The above example is equivalent to: `A && (B || C)` +* `create` - (Default 60 minutes) Used for creating a scc_rule. +* `update` - (Default 60 minutes) Used for updating a scc_rule. +* `delete` - (Default 20 minutes) Used for deleting a scc_rule. + +## Argument Reference +You can specify the following arguments for this resource. + +* `description` - (Required, String) The details of a rule's response. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. +* `import` - (Optional, List) The collection of import parameters. +Nested schema for **import**: + * `parameters` - (Optional, List) The list of import parameters. + * Constraints: The maximum length is `8` items. The minimum length is `0` items. + Nested schema for **parameters**: + * `description` - (Optional, String) The propery description. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `display_name` - (Optional, String) The display name of the property. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `name` - (Optional, String) The import parameter name. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `type` - (Optional, String) The property type. + * Constraints: Allowable values are: `string`, `numeric`, `general`, `boolean`, `string_list`, `ip_list`, `timestamp`. The maximum length is `11` characters. The minimum length is `6` characters. The value must match regular expression `/[A-Za-z]+/`. +* `labels` - (Optional, List) The list of labels. + * Constraints: The list items must match regular expression `/[A-Za-z0-9]+/`. The maximum length is `32` items. The minimum length is `0` items. +* `required_config` - (Required, List) The required configurations. +Nested schema for **required_config**: + * `and` - (Optional, List) The `AND` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **and**: + * `and` - (Optional, List) The `AND` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **and**: + * `description` - (Optional, String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (Required, String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `property` - (Required, String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (Optional, String) Schema for any JSON type. + * `description` - (Optional, String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (Optional, String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `or` - (Optional, List) The `OR` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **or**: + * `description` - (Optional, String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (Required, String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `property` - (Required, String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (Optional, String) Schema for any JSON type. + * `property` - (Optional, String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (Optional, String) Schema for any JSON type. + * `description` - (Optional, String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (Optional, String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `or` - (Optional, List) The `OR` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **or**: + * `and` - (Optional, List) The `AND` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **and**: + * `description` - (Optional, String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (Required, String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `property` - (Required, String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (Optional, String) Schema for any JSON type. + * `description` - (Optional, String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (Optional, String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `or` - (Optional, List) The `OR` required configurations. + * Constraints: The maximum length is `64` items. The minimum length is `1` item. + Nested schema for **or**: + * `description` - (Optional, String) The required config description. + * Constraints: The maximum length is `512` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (Required, String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. The maximum length is `23` characters. The minimum length is `7` characters. + * `property` - (Required, String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (Optional, String) Schema for any JSON type. + * `property` - (Optional, String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (Optional, String) Schema for any JSON type. + * `property` - (Optional, String) The property. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `value` - (Optional, String) Schema for any JSON type. +* `target` - (Required, List) The rule target. +Nested schema for **target**: + * `additional_target_attributes` - (Optional, List) The list of targets supported properties. + * Constraints: The maximum length is `99999` items. The minimum length is `0` items. + Nested schema for **additional_target_attributes**: + * `name` - (Optional, String) The additional target attribute name. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `operator` - (Optional, String) The operator. + * Constraints: Allowable values are: `string_equals`, `string_not_equals`, `string_match`, `string_not_match`, `string_contains`, `string_not_contains`, `num_equals`, `num_not_equals`, `num_less_than`, `num_less_than_equals`, `num_greater_than`, `num_greater_than_equals`, `is_empty`, `is_not_empty`, `is_true`, `is_false`, `strings_in_list`, `strings_allowed`, `strings_required`, `ips_in_range`, `ips_equals`, `ips_not_equals`, `days_less_than`. + * `value` - (Optional, String) The value. + * Constraints: The maximum length is `256` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `resource_kind` - (Required, String) The target resource kind. + * Constraints: The maximum length is `99999` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `service_display_name` - (Optional, String) The display name of the target service. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. + * `service_name` - (Required, String) The target service name. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. +* `version` - (Optional, String) The version number of a rule. + * Constraints: The maximum length is `10` characters. The minimum length is `5` characters. The value must match regular expression `/^[0-9][0-9.]*$/`. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. - -* `id` - The unique identifier of the ibm_scc_rule. -* `created_by` - (Optional, String) The unique identifier for the user or application that created the resource. -* `creation_date` - (Optional, String) The date the resource was created. -* `enforcement_actions` - (Required, List) The actions that the service must run on your behalf when a request to create or modify the target resource does not comply with your conditions. - * Constraints: The maximum length is `1` items. -Nested scheme for **enforcement_actions**: - * `action` - (Required, String) To block a request from completing, use `disallow`. - * Constraints: Allowable values are: `disallow`. -* `modification_date` - (Optional, String) The date the resource was last modified. -* `modified_by` - (Optional, String) The unique identifier for the user or application that last modified the resource. -* `version` - Version of the ibm_scc_rule. -* `rule_type` - (Optional, String) The type of rule. Rules that you create are `user_defined`. - * Constraints: Allowable values are: `user_defined`. +After your resource is created, you can read values from the listed arguments and the following attributes. + +* `id` - The unique identifier of the scc_rule. +* `account_id` - (String) The account ID. + * Constraints: The maximum length is `32` characters. The minimum length is `3` characters. The value must match regular expression `/[A-Za-z0-9]+/`. +* `created_by` - (String) The user who created the rule. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. +* `created_on` - (String) The date when the rule was created. +* `type` - (String) The rule type (allowable values are `user_defined` or `system_defined`). + * Constraints: Allowable values are: `user_defined`, `system_defined`. The maximum length is `14` characters. The minimum length is `12` characters. The value must match regular expression `/[A-Za-z]+_[A-Za-z]+/`. +* `updated_by` - (String) The user who modified the rule. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[A-Za-z0-9]+/`. +* `updated_on` - (String) The date when the rule was modified. + ## Import -You can import the `ibm_scc_rule` resource by using `rule_id`. The UUID that uniquely identifies the rule. +You can import the `ibm_scc_rule` resource by using `id`. The rule ID. # Syntax ``` -$ terraform import ibm_scc_rule.scc_rule -``` - -# Example -``` -$ terraform import ibm_scc_rule.scc_rule rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf +$ terraform import ibm_scc_rule.scc_rule ``` diff --git a/website/docs/r/scc_rule_attachment.html.markdown b/website/docs/r/scc_rule_attachment.html.markdown deleted file mode 100644 index b2c020042b..0000000000 --- a/website/docs/r/scc_rule_attachment.html.markdown +++ /dev/null @@ -1,91 +0,0 @@ ---- -layout: "ibm" -page_title: "IBM : ibm_scc_rule_attachment" -description: |- - Manages scc_rule_attachment. -subcategory: "Security and Compliance Center" ---- - -# ibm_scc_rule_attachment - -Provides a resource for ibm_scc_rule_attachment. This allows ibm_scc_rule_attachment to be created, updated and deleted. For more information about Security and Compliance Center rule attachments, see [Applying Rules](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-rules-apply&interface=ui). - -~> **NOTE**: This resource depends on a `ibm_scc_rule` to be created before creating this resource. The object `ibm_scc_rule_attachment` must attach to an exiting rule. - -## Example Usage - -```hcl -resource "ibm_scc_rule" scc_rule_instance { - // example of a ibm_scc_rule that needs to be used in conjunction with ibm_scc_rule_attachment -} - -resource "ibm_scc_rule_attachment" "scc_rule_attachment_instance" { - account_id = "thisIsAFake32CharacterAccountID" - included_scope { - note = "This is a note to reference my account" - scope_id = "thisIsAFake32CharacterAccountID" // value determined by scope type - scope_type = "account" - } - excluded_scopes { - note = "This is a note to exclude a specific resource group" - scope_id = "" // value determined by scope type - scope_type = "account.resource_group" - } - rule_id = ibm_scc_rule.scc_rule_instance.id // from the resource ibm_scc_rule - depends_on = [ - ibm_scc_rule.scc_rule_instance // ensures that the rule is created first - ] -} -``` - -## Argument Reference - -Review the argument reference that you can specify for your resource. - -* `account_id` - (Required, String) Your IBM Cloud account ID. -* `included_scope` - (Required, List) The extent at which the rule can be attached across your accounts. -Nested scheme for **included_scope**: - * `note` - (Optional, String) A short description or alias to assign to the scope. - * `scope_id` - (Required, String) The ID of the scope, such as an enterprise, account, or account group, that you want to evaluate. - * `scope_type` - (Required, String) The type of scope that you want to evaluate. - * Constraints: Allowable values are: - * `enterprise`, - * `enterprise.account_group`, - * `enterprise.account`, - * `account`, - * `account.resource_group`. - * `Constraints`: Only one `included_scope` item is allowed -* `rule_id` - (Required, Forces new resource, String) The UUID that uniquely identifies the rule. -* `excluded_scopes` - (Optional, List) The extent at which the rule can be excluded from the included scope. -Nested scheme for **excluded_scopes**: - * `note` - (Optional, String) A short description or alias to assign to the scope. - * `scope_id` - (Required, String) The ID of the scope, such as an enterprise, account, or account group, that you want to evaluate. - * `scope_type` - (Required, String) The type of scope that you want to evaluate. - * Constraints: Allowable values are: - * `enterprise`, - * `enterprise.account_group`, - * `enterprise.account`, - * `account`, - * `account.resource_group`. -## Attribute Reference - -In addition to all argument references listed, you can access the following attribute references after your resource is created. - -* `attachment_id` - (Required, String) The UUID that uniquely identifies the attachment -* `version` - Version of the ibm_scc_rule_attachment. - -## Import - -You can import the `ibm_scc_rule_attachment` resource by using `attachment_id`. -The `attachment_id` property can be formed from `rule_id`, and `attachment_id` in the following format: - -``` -/ -``` -* `rule_id`: A string. The UUID that uniquely identifies the rule. -* `attachment_id`: A string. The UUID that uniquely identifies the attachment. - -# Syntax -``` -$ terraform import ibm_scc_rule_attachment.scc_rule_attachment / -``` diff --git a/website/docs/r/scc_si_note.html.markdown b/website/docs/r/scc_si_note.html.markdown deleted file mode 100644 index c246f5b379..0000000000 --- a/website/docs/r/scc_si_note.html.markdown +++ /dev/null @@ -1,198 +0,0 @@ ---- -layout: "ibm" -subcategory: "Security and Compliance Center" -page_title: "IBM : ibm_scc_si_note" -description: |- - Manages scc_si_note. ---- - -# DEPRECATED -Security and Compliance Center - Security Insights has now deprecated, backend services are no longer available. The docs will be removed in next release. - -# ibm_scc_si_note - -Provides a resource for scc_si_note. This allows scc_si_note to be created, updated and deleted. - -## Example usage - -#### FINDING - -```terraform -resource "ibm_scc_si_note" "finding" { - provider_id = "scc" - short_description = "Security Threat" - long_description = "Security Threat found in your account" - kind = "FINDING" - note_id = "finding" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - finding { - severity = "LOW" - next_steps { - title = "Security Threat" - url = "https://cloud.ibm.com/security-compliance/findings" - } - } -} -``` - -#### KPI - -```terraform -resource "ibm_scc_si_note" "kpi" { - provider_id = "scc" - short_description = "Security Threat" - long_description = "Security Threat found in your account" - kind = "KPI" - note_id = "kpi" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - kpi { - aggregation_type = var.kpi.aggregation_type - } -} -``` - -#### CARD - -```terraform -resource "ibm_scc_si_note" "ts-card-finding" { - provider_id = "scc" - short_description = "Security Threat" - long_description = "Security Threat found in your account" - kind = "CARD" - note_id = "ts-card-finding" - reported_by { - id = "scc-si-terraform" - title = "SCC SI Terraform" - url = "https://cloud.ibm.com" - } - card { - section = "Security" - title = "Threats" - subtitle = "Summary of Security Threats" - finding_note_names = ["providers/scc/notes/finding"] - elements { - kind = "TIME_SERIES" - text = "count" - default_time_range = "3d" - value_types { - text = "count" - finding_note_names = ["providers/scc/notes/finding"] - kind = "FINDING_COUNT" - } - } - } -} -``` - -## Argument reference - -Review the argument reference that you can specify for your resource. - -* `card` - (Optional, List) Card provides details about a card kind of note. -Nested scheme for **card**: - * `section` - (Required, String) The section this card belongs to. - * Constraints: The maximum length is `30` characters. - * `title` - (Required, String) The title of this card. - * Constraints: The maximum length is `28` characters. - * `subtitle` - (Required, String) The subtitle of this card. - * Constraints: The maximum length is `30` characters. - * `order` - (Optional, Integer) The order of the card in which it will appear on SA dashboard in the mentioned section. - * Constraints: Allowable values are: 1, 2, 3, 4, 5, 6 - * `finding_note_names` - (Required, List) The finding note names associated to this card. - * `requires_configuration` - (Optional, Boolean) - * Constraints: The default value is `false`. - * `badge_text` - (Optional, String) The text associated to the card's badge. - * `badge_image` - (Optional, String) The base64 content of the image associated to the card's badge. - * `elements` - (Required, List) The elements of this card. - Nested scheme for **elements**: - * `text` - (Optional, String) The text of this card element. - * Constraints: The maximum length is `60` characters. - * `kind` - (Optional, String) Kind of element- NUMERIC: Single numeric value- BREAKDOWN: Breakdown of numeric values- TIME_SERIES: Time-series of numeric values. - * Constraints: The default value is `NUMERIC`. Allowable values are: NUMERIC, BREAKDOWN, TIME_SERIES - * `default_time_range` - (Optional, String) The default time range of this card element. - * Constraints: The default value is `4d`. Allowable values are: 1d, 2d, 3d, 4d - * `value_type` - (Optional, List) - Nested scheme for **value_type**: - * `kind` - (Optional, String) Kind of element- KPI: Kind of value derived from a KPI occurrence. - * Constraints: Allowable values are: KPI - * `kpi_note_name` - (Optional, String) The name of the kpi note associated to the occurrence with the value for this card element value type. - * `text` - (Optional, String) The text of this element type. - * Constraints: The default value is `label`. The maximum length is `22` characters. - * `finding_note_names` - (Optional, List) the names of the finding note associated that act as filters for counting the occurrences. - * `value_types` - (Optional, List) the value types associated to this card element. - Nested scheme for **value_types**: - * `kind` - (Optional, String) Kind of element- KPI: Kind of value derived from a KPI occurrence. - * Constraints: Allowable values are: KPI - * `kpi_note_name` - (Optional, String) The name of the kpi note associated to the occurrence with the value for this card element value type. - * `text` - (Optional, String) The text of this element type. - * Constraints: The default value is `label`. The maximum length is `22` characters. - * `finding_note_names` - (Optional, List) the names of the finding note associated that act as filters for counting the occurrences. - * `default_interval` - (Optional, String) The default interval of the time series. - * Constraints: The default value is `d`. -* `finding` - (Optional, List) FindingType provides details about a finding note. -Nested scheme for **finding**: - * `severity` - (Required, String) Note provider-assigned severity/impact ranking- LOW: Low Impact- MEDIUM: Medium Impact- HIGH: High Impact- CRITICAL: Critical Impact. - * Constraints: Allowable values are: LOW, MEDIUM, HIGH, CRITICAL - * `next_steps` - (Optional, List) Common remediation steps for the finding of this type. - Nested scheme for **next_steps**: - * `title` - (Optional, String) Title of this next step. - * `url` - (Optional, String) The URL associated to this next steps. -* `kind` - (Required, String) The type of note. Use this field to filter notes and occurences by kind. - FINDING: The note and occurrence represent a finding. - KPI: The note and occurrence represent a KPI value. - CARD: The note represents a card showing findings and related metric values. - CARD_CONFIGURED: The note represents a card configured for a user account. - SECTION: The note represents a section in a dashboard. - * Constraints: Allowable values are: FINDING, KPI, CARD, CARD_CONFIGURED, SECTION -* `kpi` - (Optional, List) KpiType provides details about a KPI note. -Nested scheme for **kpi**: - * `aggregation_type` - (Required, String) The aggregation type of the KPI values. - SUM: A single-value metrics aggregation type that sums up numeric values that are extracted from KPI occurrences. - * Constraints: The default value is `SUM`. Allowable values are: SUM -* `long_description` - (Required, String) A more detailed description of your note. -* `account_id` - (Optional, Forces new resource, String) Account ID is optional, if not provided value will be inferred from the token retrieved from the IBM Cloud API key. -* `note_id` - (Required, Forces new resource, String) The ID of the note. -* `provider_id` - (Required, Forces new resource, String) Part of the parent. This field contains the provider ID. For example: providers/{provider_id}. -* `related_url` - (Optional, List) -Nested scheme for **related_url**: - * `label` - (Required, String) Label to describe usage of the URL. - * `url` - (Required, String) The URL that you want to associate with the note. -* `reported_by` - (Required, List) The entity reporting a note. -Nested scheme for **reported_by**: - * `id` - (Required, String) The id of this reporter. - * `title` - (Required, String) The title of this reporter. - * `url` - (Optional, String) The url of this reporter. -* `section` - (Optional, List) Card provides details about a card kind of note. -Nested scheme for **section**: - * `title` - (Required, String) The title of this section. - * `image` - (Required, String) The image of this section. -* `shared` - (Optional, Boolean) True if this note can be shared by multiple accounts. - * Constraints: The default value is `true`. -* `short_description` - (Required, String) A one sentence description of your note. - -## Attribute reference - -In addition to all argument references listed, you can access the following attribute references after your resource is created. - -* `id` - The unique identifier of the scc_si_note. -* `create_time` - (Optional, String) Output only. The time this note was created. This field can be used as a filter in list requests. -* `update_time` - (Optional, String) Output only. The time this note was last updated. This field can be used as a filter in list requests. - -## Import - -You can import the `ibm_scc_si_note` resource by using `note_id`. -The `note_id` property can be formed from `account_id`, `provider_id`, and `note_id` in the following format: - -``` -// -``` -* `account_id` - A string. AccountID from the resource has to be imported. -* `provider_id`: A string. Part of the parent. This field contains the provider ID. For example: providers/{provider_id}. -* `note_id`: A string. Second part of note `name`: providers/{provider_id}/notes/{note_id}. - -# Syntax -``` -$ terraform import ibm_scc_si_note.scc_si_note // -``` diff --git a/website/docs/r/scc_si_occurrence.html.markdown b/website/docs/r/scc_si_occurrence.html.markdown deleted file mode 100644 index c211cbb86d..0000000000 --- a/website/docs/r/scc_si_occurrence.html.markdown +++ /dev/null @@ -1,142 +0,0 @@ ---- -layout: "ibm" -subcategory: "Security and Compliance Center" -page_title: "IBM : ibm_scc_si_occurrence" -description: |- - Manages Security and Compliance Center occurrence. ---- - -# DEPRECATED -Security and Compliance Center - Security Insights has now deprecated, backend services are no longer available. The docs will be removed in next release. - -# ibm_scc_si_occurrence - -Create, update, or delete for a Security and Compliance Center occurrence. For more information, about Security and Compliance Center, see [getting started with Security and Compliance Center](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-getting-started). - -## Example usage - -#### FINDING - -```terraform -resource "ibm_scc_si_occurrence" "finding-occurrence" { - provider_id = var.provider_id - note_name = var.note_name - kind = "FINDING" - occurrence_id = "finding-occ" - resource_url = "https://cloud.ibm.com" - remediation = "Limit the cluster access" - finding { - severity = "LOW" - certainty = "LOW" - next_steps { - title = "Security Threat" - url = "https://cloud.ibm.com/security-compliance/findings" - } - } -} -``` - -#### KPI - -```terraform -resource "ibm_scc_si_occurrence" "kpi-occurrence" { - provider_id = var.provider_id - note_name = var.note_name - kind = "KPI" - occurrence_id = "kpi-occ" - resource_url = "https://cloud.ibm.com" - remediation = "Limit the cluster access" - kpi { - value = 40 - total = 100 - } -} -``` - -## Argument reference - -Review the argument reference that you can specify for your resource. - -- `context` - (Optional, List) - - Nested scheme for **context**: - - `component_name` - (Optional, String) The name of the component the occurrence applies to. - - `environment_name` - (Optional, String) The name of the environment the occurrence applies to. - - `region` - (Optional, String) The IBM Cloud region. - - `resource_crn` - (Optional, String) The resource CRN (e.g. certificate CRN, image CRN). - - `resource_id` - (Optional, String) The resource ID, in case the CRN is not available. - - `resource_name` - (Optional, String) The user-friendly resource name. - - `resource_type` - (Optional, String) The resource type name (e.g. Pod, Cluster, Certificate, Image). - - `service_crn` - (Optional, String) The service CRN (e.g. CertMgr Instance CRN). - - `service_name` - (Optional, String) The service name (e.g. CertMgr). - - `toolchain_id` - (Optional, String) The id of the toolchain the occurrence applies to. -- `finding` - (Optional, List) Finding provides details about a finding occurrence. - - Nested scheme for **finding**: - - `certainty` - (Optional, String) Note provider-assigned confidence on the validity of an occurrence- LOW: Low Certainty- MEDIUM: Medium Certainty- HIGH: High Certainty. - - Constraints: Allowable values are: `LOW`, `MEDIUM`, `HIGH`. - - `data_transferred` - (Optional, List) It provides details about data transferred between clients and servers. - - Nested scheme for **data_transferred**: - - `client_bytes` - (Optional, Integer) The number of client bytes transferred. - - `client_packets` - (Optional, Integer) The number of client packets transferred. - - `server_bytes` - (Optional, Integer) The number of server bytes transferred. - - `server_packets` - (Optional, Integer) The number of server packets transferred. - - `network_connection` - (Optional, List) It provides details about a network connection. - - Nested scheme for **network_connection**: - * `client` - (Optional, List) It provides details about a socket address. - Nested scheme for **client**: - * `address` - (Required, String) The IP address of this socket address. - * `port` - (Optional, Integer) The port number of this socket address. - * `direction` - (Optional, String) The direction of this network connection. - * `protocol` - (Optional, String) The protocol of this network connection. - * `server` - (Optional, List) It provides details about a socket address. - Nested scheme for **server**: - * `address` - (Required, String) The IP address of this socket address. - * `port` - (Optional, Integer) The port number of this socket address. - * `next_steps` - (Optional, List) Remediation steps for the issues reported in this finding. They override the note's next steps. - Nested scheme for **next_steps**: - * `title` - (Optional, String) Title of this next step. - * `url` - (Optional, String) The URL associated to this next steps. - * `severity` - (Optional, String) Note provider-assigned severity/impact ranking- LOW: Low Impact- MEDIUM: Medium Impact- HIGH: High Impact- CRITICAL: Critical Impact. - * Constraints: Allowable values are: `LOW`, `MEDIUM`, `HIGH`, `CRITICAL`. -* `kind` - (Required, String) The type of note. Use this field to filter notes and occurrences by kind. - FINDING: The note and occurrence represent a finding. - KPI: The note and occurrence represent a KPI value. - CARD: The note represents a card showing findings and related metric values. - CARD_CONFIGURED: The note represents a card configured for a user account. - SECTION: The note represents a section in a dashboard. - * Constraints: Allowable values are: `FINDING`, `KPI`, `CARD`, `CARD_CONFIGURED`, `SECTION`. -* `kpi` - (Optional, List) Kpi provides details about a KPI occurrence. -Nested scheme for **kpi**: - * `total` - (Optional, Float) The total value of this KPI. - * `value` - (Required, Float) The value of this KPI. -* `note_name` - (Required, String) An analysis note associated with this image, in the form "{account_id}/providers/{provider_id}/notes/{note_id}" This field can be used as a filter in list requests. -* `account_id` - (Optional, Forces new resource, String) Account ID is optional, if not provided value will be inferred from the token retrieved from the IBM Cloud API key. -* `occurrence_id` - (Required, Forces new resource, String) The ID of the occurrence. -* `provider_id` - (Required, Forces new resource, String) Part of the parent. This field contains the provider ID. For example: providers/{provider_id}. -* `remediation` - (Optional, String) A description of actions that can be taken to remedy the `Note`. -* `replace_if_exists` - (Optional, Boolean) When set to true, an existing occurrence is replaced rather than duplicated. -* `resource_url` - (Optional, String) The unique URL of the resource, image or the container, for which the `Occurrence` applies. For example, https://gcr.io/provider/image@sha256:foo. This field can be used as a filter in list requests. - -## Attribute reference - -In addition to all argument references listed, you can access the following attribute references after your resource is created. - -- `id` - The unique identifier of the scc_si_occurrence. -- `create_time` - (Optional, String) Output only. The time this `Occurrence` was created. -- `update_time` - (Optional, String) Output only. The time this `Occurrence` was last updated. - -## Import - -You can import the `ibm_scc_si_occurrence` resource by using `id`. -The `id` property can be formed from `provider_id`, and `occurrence_id` in the following format: - -```sh -// -``` -- `account_id` - A string. AccountID from the resource has to be imported. -- `provider_id`: A string. Part of the parent. This field contains the provider ID. For example: **providers/{provider_id}**. -- `occurrence_id`: A string. Second part of occurrence `name`: **providers/{provider_id}/occurrences/{occurrence_id}**. - -# Syntax - -```sh -$ terraform import ibm_scc_si_occurrence.scc_si_occurrence // -``` diff --git a/website/docs/r/scc_template.html.markdown b/website/docs/r/scc_template.html.markdown deleted file mode 100644 index 3854ee6f86..0000000000 --- a/website/docs/r/scc_template.html.markdown +++ /dev/null @@ -1,85 +0,0 @@ ---- -layout: "ibm" -page_title: "IBM : ibm_scc_template" -description: |- - Manages scc_template. -subcategory: "Security and Compliance Center" ---- - -# ibm_scc_template - -Provides a resource for scc_template. This allows scc_template to be created, updated and deleted. For more information about Security and Compliance Center templates, see [Defining Templates](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-templates-define&interface=ui). - -## Example Usage - -```hcl -resource "ibm_scc_template" "scc_template_tf_example" { - account_id = var.account_id - name = "Terraform template" - description = "COS buckets in us-south should send write data events to Activity Tracker by default" - target { - service_name = "cloud-object-storage" - resource_kind = "bucket" - additional_target_attributes { - name = "location" - value = "us-south" - } - } - customized_defaults { - property = "activity_tracking.write_data_events" - value = "true" - } -} -``` - -In the above example, new COS buckets in `us-south` will send write data events to Activity Tracker by default. - -## Argument Reference - -Review the argument reference that you can specify for your resource. - -* `account_id` - (Required, String) Your IBM Cloud account ID. -* `name` - (Required, String) A human-readable alias to assign to your template. - * Constraints: The maximum length is `32` characters. The minimum length is `1` character. -* `description` - (Required, String) An extended description of your template. - * Constraints: The maximum length is `256` characters. The minimum length is `1` character. -* `target` - (Required, List) The properties that describe the resource that you want to target with the rule or template. - Nested scheme for ** target**: - * `service_name` - (Required, String) The programmatic name of the IBM Cloud service that you want to target with the - rule or template. - * Constraints: The value must match regular expression `/^[a-z-]*$/`. - * `resource_kind` - (Required, String) The type of resource that you want to target. -* `additional_target_attributes` - (Optional, List) An extra qualifier for the resource kind. When you include additional attributes, only the resources that match the definition are included in the rule or template. - * Nested scheme for **additional_target_attributes**: - * `name` - (Required, String) The name of the additional attribute that you want to use to further qualify the target. Options differ depending on the service or resource that you are targeting with a rule or template. For more information, refer to the service documentation. - * `value` - (Required, String) The value that you want to apply to `name` field. Options differ depending on the rule or template that you configure. For more information, refer to the service documentation. -* `customized_defaults` - (Required, List) A list of default property values to apply to your template. - Nested scheme for **customized_defaults**: - * `property` - (Required, String) The name of the resource property that you want to configure. Property options differ depending on the service or resource that you are targeting with a template. To view a list of properties that are compatible with templates, refer to the service documentation. - * `value` - (Required, String) The custom value that you want to apply as the default for the resource property in the `name` field. This value is used to override the default value that is provided by IBM when a resource is created. Value options differ depending on the resource that you are configuring. To learn more about your options, refer to the service documentation. - - -## Attribute Reference - -In addition to all argument references listed, you can access the following attribute references after your resource is created. - -* `id` - The unique identifier of the ibm_scc_template. -* `created_by` - (Optional, String) The unique identifier for the user or application that created the resource. -* `creation_date` - (Optional, String) The date the resource was created. -* `modification_date` - (Optional, String) The date the resource was last modified. -* `modified_by` - (Optional, String) The unique identifier for the user or application that last modified the resource. -* `version` - Version of the ibm_scc_template. - -## Import - -You can import the `ibm_scc_template` resource by using `template_id`. The UUID that uniquely identifies the template. - -# Syntax -``` -$ terraform import ibm_scc_template.scc_template -``` - -# Example -``` -$ terraform import ibm_scc_template.scc_template template-702d1db7-ca4a-414b-8464-2b517a065c14 -``` diff --git a/website/docs/r/scc_template_attachment.html.markdown b/website/docs/r/scc_template_attachment.html.markdown deleted file mode 100644 index 875647e13f..0000000000 --- a/website/docs/r/scc_template_attachment.html.markdown +++ /dev/null @@ -1,92 +0,0 @@ ---- -layout: "ibm" -page_title: "IBM : ibm_scc_template_attachment" -description: |- - Manages scc_template_attachment. -subcategory: "Security and Compliance Center" ---- - -# ibm_scc_template_attachment - -Provides a resource for scc_template_attachment. This allows scc_template_attachment to be created, updated and deleted. For more information about Security and Compliance Center template attachments, see [Applying Templates](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-templates-apply&interface=ui). - -~> **NOTE**: This resource depends on a `ibm_scc_template` to be created before creating this resource. The object `ibm_scc_template_attachment` must attach to an exiting template. - -## Example Usage - -```hcl -resource "ibm_scc_template" scc_template_instance { - // example of a ibm_scc_template that needs to be used in conjunction with ibm_scc_template_attachment -} - -resource "ibm_scc_template_attachment" "scc_template_attachment_instance" { - account_id = "thisIsAFake32CharacterAccountID" - included_scope { - note = "This is a note to reference my account" - scope_id = "thisIsAFake32CharacterAccountID" // value determined by scope type - scope_type = "account" - } - excluded_scopes { - note = "This is a note to exclude a specific resource group" - scope_id = "" // value determined by scope type - scope_type = "account.resource_group" - } - template_id = ibm_scc_template.scc_template_instance.id // from the resource ibm_scc_template - depends_on = [ - ibm_scc_template.scc_template_instance // ensures that the template is created first - ] -} -``` - -## Argument Reference - -Review the argument reference that you can specify for your resource. - -* `account_id` - (Required, String) Your IBM Cloud account ID. -* `included_scope` - (Required, List) The extent at which the template can be attached across your accounts. - Nested scheme for **included_scope**: - * `note` - (Optional, String) A short description or alias to assign to the scope. - * `scope_id` - (Required, String) The ID of the scope, such as an enterprise, account, or account group, that you want to evaluate. - * `scope_type` - (Required, String) The type of scope that you want to evaluate. - * Constraints: Allowable values are: - * `enterprise`, - * `enterprise.account_group`, - * `enterprise.account`, - * `account`, - * `account.resource_group`. - * `Constraints`: Only one `included_scope` item is allowed -* `template_id` - (Required, Forces new resource, String) The UUID that uniquely identifies the template. -* `excluded_scopes` - (Optional, List) The extent at which the template can be excluded from the included scope. - Nested scheme for **excluded_scopes**: - * `note` - (Optional, String) A short description or alias to assign to the scope. - * `scope_id` - (Required, String) The ID of the scope, such as an enterprise, account, or account group, that you want to evaluate. - * `scope_type` - (Required, String) The type of scope that you want to evaluate. - * Constraints: Allowable values are: - * `enterprise`, - * `enterprise.account_group`, - * `enterprise.account`, - * `account`, - * `account.resource_group`. - -## Attribute Reference - -In addition to all argument references listed, you can access the following attribute references after your resource is created. - -* `attachment_id` - (Required, String) The UUID that uniquely identifies the attachment -* `version` - Version of the ibm_scc_template_attachment. - -## Import - -You can import the `ibm_scc_template_attachment` resource by using `attachment_id`. -The `attachment_id` property can be formed from `template_id`, and `attachment_id` in the following format: - -``` -/ -``` -* `template_id`: A string. The UUID that uniquely identifies the template. -* `attachment_id`: A string. The UUID that uniquely identifies the attachment. - -# Syntax -``` -$ terraform import ibm_scc_template_attachment.scc_template_attachment / -``` From bcb1ee8a2aca48b4553360e94de51ada6cd42bd3 Mon Sep 17 00:00:00 2001 From: gmarjoram Date: Thu, 14 Sep 2023 15:04:18 +0100 Subject: [PATCH 2/5] Added retry mechanism and new SDK generator 3.78 (#4776) --- .../data_source_ibm_cd_toolchain.go | 4 +- ..._source_ibm_cd_toolchain_tool_appconfig.go | 8 +-- ...ource_ibm_cd_toolchain_tool_artifactory.go | 6 +- ...urce_ibm_cd_toolchain_tool_bitbucketgit.go | 6 +- ...ata_source_ibm_cd_toolchain_tool_custom.go | 8 +-- ...ce_ibm_cd_toolchain_tool_devopsinsights.go | 8 +-- ...bm_cd_toolchain_tool_eventnotifications.go | 6 +- ...bm_cd_toolchain_tool_githubconsolidated.go | 8 +-- ...ata_source_ibm_cd_toolchain_tool_gitlab.go | 8 +-- ...ce_ibm_cd_toolchain_tool_hashicorpvault.go | 8 +-- ..._source_ibm_cd_toolchain_tool_hostedgit.go | 6 +- ...ta_source_ibm_cd_toolchain_tool_jenkins.go | 8 +-- .../data_source_ibm_cd_toolchain_tool_jira.go | 8 +-- ...source_ibm_cd_toolchain_tool_keyprotect.go | 8 +-- ...data_source_ibm_cd_toolchain_tool_nexus.go | 8 +-- ..._source_ibm_cd_toolchain_tool_pagerduty.go | 6 +- ...a_source_ibm_cd_toolchain_tool_pipeline.go | 8 +-- ...rce_ibm_cd_toolchain_tool_privateworker.go | 8 +-- ..._source_ibm_cd_toolchain_tool_saucelabs.go | 8 +-- ...ce_ibm_cd_toolchain_tool_secretsmanager.go | 6 +- ...bm_cd_toolchain_tool_securitycompliance.go | 14 ++-- ...data_source_ibm_cd_toolchain_tool_slack.go | 8 +-- ..._source_ibm_cd_toolchain_tool_sonarqube.go | 8 +-- .../cdtoolchain/resource_ibm_cd_toolchain.go | 65 ++++++++++++------- ...esource_ibm_cd_toolchain_tool_appconfig.go | 51 ++++++++++----- ...ource_ibm_cd_toolchain_tool_artifactory.go | 49 +++++++++----- ...urce_ibm_cd_toolchain_tool_bitbucketgit.go | 49 +++++++++----- .../resource_ibm_cd_toolchain_tool_custom.go | 51 ++++++++++----- ...ce_ibm_cd_toolchain_tool_devopsinsights.go | 27 ++++++-- ...bm_cd_toolchain_tool_eventnotifications.go | 49 +++++++++----- ...bm_cd_toolchain_tool_githubconsolidated.go | 53 ++++++++++----- .../resource_ibm_cd_toolchain_tool_gitlab.go | 53 ++++++++++----- ...ce_ibm_cd_toolchain_tool_hashicorpvault.go | 51 ++++++++++----- ...esource_ibm_cd_toolchain_tool_hostedgit.go | 49 +++++++++----- .../resource_ibm_cd_toolchain_tool_jenkins.go | 51 ++++++++++----- .../resource_ibm_cd_toolchain_tool_jira.go | 51 ++++++++++----- ...source_ibm_cd_toolchain_tool_keyprotect.go | 51 ++++++++++----- .../resource_ibm_cd_toolchain_tool_nexus.go | 51 ++++++++++----- ...esource_ibm_cd_toolchain_tool_pagerduty.go | 49 +++++++++----- ...resource_ibm_cd_toolchain_tool_pipeline.go | 51 ++++++++++----- ...rce_ibm_cd_toolchain_tool_privateworker.go | 51 ++++++++++----- ...esource_ibm_cd_toolchain_tool_saucelabs.go | 51 ++++++++++----- ...ce_ibm_cd_toolchain_tool_secretsmanager.go | 49 +++++++++----- ...bm_cd_toolchain_tool_securitycompliance.go | 57 ++++++++++------ .../resource_ibm_cd_toolchain_tool_slack.go | 51 ++++++++++----- ...esource_ibm_cd_toolchain_tool_sonarqube.go | 51 ++++++++++----- website/docs/d/cd_toolchain.html.markdown | 15 +++-- .../cd_toolchain_tool_appconfig.html.markdown | 13 ++-- ...d_toolchain_tool_artifactory.html.markdown | 13 ++-- ..._toolchain_tool_bitbucketgit.html.markdown | 13 ++-- .../d/cd_toolchain_tool_custom.html.markdown | 13 ++-- ...oolchain_tool_devopsinsights.html.markdown | 11 ++-- ...hain_tool_eventnotifications.html.markdown | 13 ++-- ...hain_tool_githubconsolidated.html.markdown | 15 +++-- .../d/cd_toolchain_tool_gitlab.html.markdown | 15 +++-- ...oolchain_tool_hashicorpvault.html.markdown | 13 ++-- .../cd_toolchain_tool_hostedgit.html.markdown | 13 ++-- .../d/cd_toolchain_tool_jenkins.html.markdown | 13 ++-- .../d/cd_toolchain_tool_jira.html.markdown | 13 ++-- ...cd_toolchain_tool_keyprotect.html.markdown | 13 ++-- .../d/cd_toolchain_tool_nexus.html.markdown | 13 ++-- .../cd_toolchain_tool_pagerduty.html.markdown | 13 ++-- .../cd_toolchain_tool_pipeline.html.markdown | 13 ++-- ...toolchain_tool_privateworker.html.markdown | 13 ++-- .../cd_toolchain_tool_saucelabs.html.markdown | 13 ++-- ...oolchain_tool_secretsmanager.html.markdown | 13 ++-- ...hain_tool_securitycompliance.html.markdown | 13 ++-- .../d/cd_toolchain_tool_slack.html.markdown | 13 ++-- .../cd_toolchain_tool_sonarqube.html.markdown | 13 ++-- website/docs/r/cd_toolchain.html.markdown | 57 ++-------------- .../cd_toolchain_tool_appconfig.html.markdown | 59 ++--------------- ...d_toolchain_tool_artifactory.html.markdown | 59 ++--------------- ..._toolchain_tool_bitbucketgit.html.markdown | 61 ++--------------- .../r/cd_toolchain_tool_custom.html.markdown | 59 ++--------------- ...oolchain_tool_devopsinsights.html.markdown | 57 ++-------------- ...hain_tool_eventnotifications.html.markdown | 59 ++--------------- ...hain_tool_githubconsolidated.html.markdown | 65 +++---------------- .../r/cd_toolchain_tool_gitlab.html.markdown | 65 +++---------------- ...oolchain_tool_hashicorpvault.html.markdown | 59 ++--------------- .../cd_toolchain_tool_hostedgit.html.markdown | 61 ++--------------- .../r/cd_toolchain_tool_jenkins.html.markdown | 59 ++--------------- .../r/cd_toolchain_tool_jira.html.markdown | 59 ++--------------- ...cd_toolchain_tool_keyprotect.html.markdown | 59 ++--------------- .../r/cd_toolchain_tool_nexus.html.markdown | 59 ++--------------- .../cd_toolchain_tool_pagerduty.html.markdown | 59 ++--------------- .../cd_toolchain_tool_pipeline.html.markdown | 59 ++--------------- ...toolchain_tool_privateworker.html.markdown | 59 ++--------------- .../cd_toolchain_tool_saucelabs.html.markdown | 59 ++--------------- ...oolchain_tool_secretsmanager.html.markdown | 59 ++--------------- ...hain_tool_securitycompliance.html.markdown | 59 ++--------------- .../r/cd_toolchain_tool_slack.html.markdown | 59 ++--------------- .../cd_toolchain_tool_sonarqube.html.markdown | 59 ++--------------- 92 files changed, 1168 insertions(+), 1839 deletions(-) diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain.go index e185e7ec9d..de645c2281 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022, 2023 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -34,7 +34,7 @@ func DataSourceIBMCdToolchain() *schema.Resource { "description": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Toolchain description.", + Description: "Describes the toolchain.", }, "account_id": &schema.Schema{ Type: schema.TypeString, diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_appconfig.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_appconfig.go index 0ce44d7b79..a81fae9566 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_appconfig.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_appconfig.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolAppconfig() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -213,10 +213,10 @@ func dataSourceIBMCdToolchainToolAppconfigRead(context context.Context, d *schem func dataSourceIBMCdToolchainToolAppconfigToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_artifactory.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_artifactory.go index 636cd10275..c609083334 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_artifactory.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_artifactory.go @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolArtifactory() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -227,10 +227,10 @@ func dataSourceIBMCdToolchainToolArtifactoryRead(context context.Context, d *sch func dataSourceIBMCdToolchainToolArtifactoryToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_bitbucketgit.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_bitbucketgit.go index 431cc69911..2e28460177 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_bitbucketgit.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_bitbucketgit.go @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolBitbucketgit() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -249,10 +249,10 @@ func dataSourceIBMCdToolchainToolBitbucketgitRead(context context.Context, d *sc func dataSourceIBMCdToolchainToolBitbucketgitToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_custom.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_custom.go index 2dd5c36f73..4c56ad78b3 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_custom.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_custom.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolCustom() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -222,10 +222,10 @@ func dataSourceIBMCdToolchainToolCustomRead(context context.Context, d *schema.R func dataSourceIBMCdToolchainToolCustomToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_devopsinsights.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_devopsinsights.go index c7c3f6ab58..cd50ae9ce5 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_devopsinsights.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_devopsinsights.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolDevopsinsights() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -158,10 +158,10 @@ func dataSourceIBMCdToolchainToolDevopsinsightsRead(context context.Context, d * func dataSourceIBMCdToolchainToolDevopsinsightsToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_eventnotifications.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_eventnotifications.go index e89cf39edb..ba29ba3412 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_eventnotifications.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_eventnotifications.go @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolEventnotifications() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -189,10 +189,10 @@ func dataSourceIBMCdToolchainToolEventnotificationsRead(context context.Context, func dataSourceIBMCdToolchainToolEventnotificationsToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_githubconsolidated.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_githubconsolidated.go index 2f23cfc68e..f21cb21807 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_githubconsolidated.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_githubconsolidated.go @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolGithubconsolidated() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -89,7 +89,7 @@ func DataSourceIBMCdToolchainToolGithubconsolidated() *schema.Resource { "git_id": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Set this value to 'github' for github.com, the GUID of an existing custom GitHub Enterprise server, or 'githubcustom'.", + Description: "Set this value to 'github' for github.com, or 'githubcustom' for a custom GitHub Enterprise server.", }, "title": &schema.Schema{ Type: schema.TypeString, @@ -280,10 +280,10 @@ func dataSourceIBMCdToolchainToolGithubconsolidatedRead(context context.Context, func dataSourceIBMCdToolchainToolGithubconsolidatedToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_gitlab.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_gitlab.go index 67e0ca7a00..7aad0fff87 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_gitlab.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_gitlab.go @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolGitlab() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -89,7 +89,7 @@ func DataSourceIBMCdToolchainToolGitlab() *schema.Resource { "git_id": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Set this value to 'gitlab' for gitlab.com, the GUID of an existing custom GitLab server, or 'gitlabcustom'.", + Description: "Set this value to 'gitlab' for gitlab.com, or 'gitlabcustom' for a custom GitLab server.", }, "title": &schema.Schema{ Type: schema.TypeString, @@ -275,10 +275,10 @@ func dataSourceIBMCdToolchainToolGitlabRead(context context.Context, d *schema.R func dataSourceIBMCdToolchainToolGitlabToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_hashicorpvault.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_hashicorpvault.go index edfae65128..6cf328855d 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_hashicorpvault.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_hashicorpvault.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolHashicorpvault() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -240,10 +240,10 @@ func dataSourceIBMCdToolchainToolHashicorpvaultRead(context context.Context, d * func dataSourceIBMCdToolchainToolHashicorpvaultToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_hostedgit.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_hostedgit.go index ace5962367..84039dcb01 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_hostedgit.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_hostedgit.go @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolHostedgit() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -260,10 +260,10 @@ func dataSourceIBMCdToolchainToolHostedgitRead(context context.Context, d *schem func dataSourceIBMCdToolchainToolHostedgitToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_jenkins.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_jenkins.go index 684d19610f..7a837981c4 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_jenkins.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_jenkins.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolJenkins() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -203,10 +203,10 @@ func dataSourceIBMCdToolchainToolJenkinsRead(context context.Context, d *schema. func dataSourceIBMCdToolchainToolJenkinsToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_jira.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_jira.go index 5af13ce6a9..fedaef3747 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_jira.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_jira.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolJira() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -205,10 +205,10 @@ func dataSourceIBMCdToolchainToolJiraRead(context context.Context, d *schema.Res func dataSourceIBMCdToolchainToolJiraToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_keyprotect.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_keyprotect.go index 9423a839f7..4af45e235e 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_keyprotect.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_keyprotect.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolKeyprotect() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -201,10 +201,10 @@ func dataSourceIBMCdToolchainToolKeyprotectRead(context context.Context, d *sche func dataSourceIBMCdToolchainToolKeyprotectToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_nexus.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_nexus.go index c83dd662a3..08df1878fc 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_nexus.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_nexus.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolNexus() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -220,10 +220,10 @@ func dataSourceIBMCdToolchainToolNexusRead(context context.Context, d *schema.Re func dataSourceIBMCdToolchainToolNexusToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_pagerduty.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_pagerduty.go index bbd4da5232..e5e3d4de6f 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_pagerduty.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_pagerduty.go @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolPagerduty() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -192,10 +192,10 @@ func dataSourceIBMCdToolchainToolPagerdutyRead(context context.Context, d *schem func dataSourceIBMCdToolchainToolPagerdutyToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_pipeline.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_pipeline.go index 8b03685402..f07191281c 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_pipeline.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_pipeline.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolPipeline() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -181,10 +181,10 @@ func dataSourceIBMCdToolchainToolPipelineRead(context context.Context, d *schema func dataSourceIBMCdToolchainToolPipelineToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_privateworker.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_privateworker.go index 5d4e851cb5..8c368c9680 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_privateworker.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_privateworker.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolPrivateworker() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -196,10 +196,10 @@ func dataSourceIBMCdToolchainToolPrivateworkerRead(context context.Context, d *s func dataSourceIBMCdToolchainToolPrivateworkerToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_saucelabs.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_saucelabs.go index 338b0688aa..1efc107b77 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_saucelabs.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_saucelabs.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolSaucelabs() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -190,10 +190,10 @@ func dataSourceIBMCdToolchainToolSaucelabsRead(context context.Context, d *schem func dataSourceIBMCdToolchainToolSaucelabsToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_secretsmanager.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_secretsmanager.go index 130894f822..fc3954fc98 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_secretsmanager.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_secretsmanager.go @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolSecretsmanager() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -213,10 +213,10 @@ func dataSourceIBMCdToolchainToolSecretsmanagerRead(context context.Context, d * func dataSourceIBMCdToolchainToolSecretsmanagerToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_securitycompliance.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_securitycompliance.go index 8d76143a84..11cf10dc7d 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_securitycompliance.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_securitycompliance.go @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolSecuritycompliance() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -99,26 +99,26 @@ func DataSourceIBMCdToolchainToolSecuritycompliance() *schema.Resource { "trigger_scan": &schema.Schema{ Type: schema.TypeString, Computed: true, - Deprecated: "This argument is deprecated and will be removed in a future release. Refer to the provider documentation for details.", + Deprecated: "This argument is deprecated and may be removed in a future release", Description: "Set to `enabled` to indicate that a DevSecOps pipeline task should trigger a Security and Compliance Center run of a Hybrid cloud validation scan. Note, each scan may incur charges. When enabled, other parameters become relevant that are needed to trigger that scan; `api_key`, `scope`, `profile`. Hybrid cloud scans are deprecated and are planned to be removed. This option will stop working at that time. For more information see the [Security and Compliance Center Release Notes](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-release-notes#security-compliance-march312023).", }, "api_key": &schema.Schema{ Type: schema.TypeString, Computed: true, Sensitive: true, - Deprecated: "This argument is deprecated and will be removed in a future release. Refer to the provider documentation for details.", + Deprecated: "This argument is deprecated and may be removed in a future release", Description: "The IBM Cloud API key used to access the Security and Compliance Center API. This parameter is only relevant when the `trigger_scan` parameter is `enabled`. For information about the deprecation see the `trigger_scan` parameter. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials).", }, "scope": &schema.Schema{ Type: schema.TypeString, Computed: true, - Deprecated: "This argument is deprecated and will be removed in a future release. Refer to the provider documentation for details.", + Deprecated: "This argument is deprecated and may be removed in a future release", Description: "The name of a Security and Compliance Center scope, which has previously been created in that service. When the `trigger_scan` parameter is set to `enabled`, then the Validation scan will scan all the resources in that scope. Select a scope that contains this toolchain, so that the scan will find the evidence that has been recently updated by the DevSecOps pipeline-run. This parameter is only relevant when the `trigger_scan` parameter is `enabled`. For information about the deprecation see the `trigger_scan` parameter.", }, "profile": &schema.Schema{ Type: schema.TypeString, Computed: true, - Deprecated: "This argument is deprecated and will be removed in a future release. Refer to the provider documentation for details.", + Deprecated: "This argument is deprecated and may be removed in a future release", Description: "The name of a Security and Compliance Center, Hybrid cloud profile. Usually, use the predefined profile \"IBM Cloud Security Best Practices v1.0.0\", which contains the DevSecOps toolchain goals. Or use a user-authored customized profile that has been configured to contain those goals. When the `trigger_scan` parameter is set to `enabled`, then the Validation scan will use the controls and goals in the configured profile. If configured with a profile that does not check the DevSecOps toolchain goals, it might incorrectly indicate that the toolchain status is passed even though some of the DevSecOps scans had actually failed. This parameter is only relevant when the `trigger_scan` parameter is `enabled`. For information about the deprecation see the `trigger_scan` parameter.", }, "use_profile_attachment": &schema.Schema{ @@ -251,10 +251,10 @@ func dataSourceIBMCdToolchainToolSecuritycomplianceRead(context context.Context, func dataSourceIBMCdToolchainToolSecuritycomplianceToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_slack.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_slack.go index 7389206bf2..0cee76624d 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_slack.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_slack.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolSlack() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -221,10 +221,10 @@ func dataSourceIBMCdToolchainToolSlackRead(context context.Context, d *schema.Re func dataSourceIBMCdToolchainToolSlackToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_sonarqube.go b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_sonarqube.go index 92bf778555..d867f8c1be 100644 --- a/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_sonarqube.go +++ b/ibm/service/cdtoolchain/data_source_ibm_cd_toolchain_tool_sonarqube.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -73,7 +73,7 @@ func DataSourceIBMCdToolchainToolSonarqube() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Tool name.", + Description: "Name of the tool.", }, "updated_at": &schema.Schema{ Type: schema.TypeString, @@ -205,10 +205,10 @@ func dataSourceIBMCdToolchainToolSonarqubeRead(context context.Context, d *schem func dataSourceIBMCdToolchainToolSonarqubeToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.UIHref != nil { - modelMap["ui_href"] = *model.UIHref + modelMap["ui_href"] = model.UIHref } if model.APIHref != nil { - modelMap["api_href"] = *model.APIHref + modelMap["api_href"] = model.APIHref } return modelMap, nil } diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain.go index 64f7ebfd07..253c45ab53 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022, 2023 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -8,15 +8,18 @@ import ( "fmt" "log" "os" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchain() *schema.Resource { @@ -39,19 +42,19 @@ func ResourceIBMCdToolchain() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain", "name"), Description: "Toolchain name.", }, - "resource_group_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain", "resource_group_id"), - Description: "Resource group where toolchain will be created.", - }, "description": &schema.Schema{ Type: schema.TypeString, Optional: true, ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain", "description"), Description: "Describes the toolchain.", }, + "resource_group_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain", "resource_group_id"), + Description: "Resource group where the toolchain is located.", + }, "account_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -117,15 +120,6 @@ func ResourceIBMCdToolchainValidator() *validate.ResourceValidator { MinValueLength: 0, MaxValueLength: 128, }, - validate.ValidateSchema{ - Identifier: "resource_group_id", - ValidateFunctionIdentifier: validate.ValidateRegexpLen, - Type: validate.TypeString, - Required: true, - Regexp: `^[0-9a-f]{32}$`, - MinValueLength: 32, - MaxValueLength: 32, - }, validate.ValidateSchema{ Identifier: "description", ValidateFunctionIdentifier: validate.ValidateRegexpLen, @@ -135,6 +129,15 @@ func ResourceIBMCdToolchainValidator() *validate.ResourceValidator { MinValueLength: 0, MaxValueLength: 500, }, + validate.ValidateSchema{ + Identifier: "resource_group_id", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^[0-9a-f]{32}$`, + MinValueLength: 32, + MaxValueLength: 32, + }, validate.ValidateSchema{ Identifier: "tags", ValidateFunctionIdentifier: validate.ValidateCloudData, @@ -193,7 +196,21 @@ func resourceIBMCdToolchainRead(context context.Context, d *schema.ResourceData, getToolchainByIDOptions.SetToolchainID(d.Id()) - toolchain, response, err := cdToolchainClient.GetToolchainByIDWithContext(context, getToolchainByIDOptions) + var toolchain *cdtoolchainv2.Toolchain + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchain, response, err = cdToolchainClient.GetToolchainByIDWithContext(context, getToolchainByIDOptions) + if err != nil || toolchain == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchain, response, err = cdToolchainClient.GetToolchainByIDWithContext(context, getToolchainByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -213,12 +230,14 @@ func resourceIBMCdToolchainRead(context context.Context, d *schema.ResourceData, if err = d.Set("name", toolchain.Name); err != nil { return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) } + if !core.IsNil(toolchain.Description) { + if err = d.Set("description", toolchain.Description); err != nil { + return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + } + } if err = d.Set("resource_group_id", toolchain.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } - if err = d.Set("description", toolchain.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) - } if err = d.Set("account_id", toolchain.AccountID); err != nil { return diag.FromErr(fmt.Errorf("Error setting account_id: %s", err)) } @@ -260,10 +279,6 @@ func resourceIBMCdToolchainUpdate(context context.Context, d *schema.ResourceDat hasChange := false patchVals := &cdtoolchainv2.ToolchainPrototypePatch{} - if d.HasChange("resource_group_id") { - return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ - " The resource must be re-created to update this property.", "resource_group_id")) - } if d.HasChange("name") { newName := d.Get("name").(string) patchVals.Name = &newName diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_appconfig.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_appconfig.go index 00379c619e..a6452227e4 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_appconfig.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_appconfig.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolAppconfig() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolAppconfig() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_appconfig", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_appconfig", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -74,12 +83,6 @@ func ResourceIBMCdToolchainToolAppconfig() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_appconfig", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -215,7 +218,21 @@ func resourceIBMCdToolchainToolAppconfigRead(context context.Context, d *schema. getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -228,6 +245,11 @@ func resourceIBMCdToolchainToolAppconfigRead(context context.Context, d *schema. if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "location": "region", "resource_group_name": "resource-group", @@ -239,9 +261,6 @@ func resourceIBMCdToolchainToolAppconfigRead(context context.Context, d *schema. if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -297,6 +316,11 @@ func resourceIBMCdToolchainToolAppconfigUpdate(context context.Context, d *schem return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "location": "region", @@ -309,11 +333,6 @@ func resourceIBMCdToolchainToolAppconfigUpdate(context context.Context, d *schem patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_artifactory.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_artifactory.go index b88606d904..a9beeaa50d 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_artifactory.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_artifactory.go @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolArtifactory() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolArtifactory() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_artifactory", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_artifactory", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -96,12 +105,6 @@ func ResourceIBMCdToolchainToolArtifactory() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_artifactory", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -230,7 +233,21 @@ func resourceIBMCdToolchainToolArtifactoryRead(context context.Context, d *schem getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -243,13 +260,15 @@ func resourceIBMCdToolchainToolArtifactoryRead(context context.Context, d *schem if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } parametersMap := GetParametersFromRead(toolchainTool.Parameters, ResourceIBMCdToolchainToolArtifactory(), nil) if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -305,16 +324,16 @@ func resourceIBMCdToolchainToolArtifactoryUpdate(context context.Context, d *sch return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } - if d.HasChange("parameters") { - parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolArtifactory(), nil) - patchVals.Parameters = parameters - hasChange = true - } if d.HasChange("name") { newName := d.Get("name").(string) patchVals.Name = &newName hasChange = true } + if d.HasChange("parameters") { + parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolArtifactory(), nil) + patchVals.Parameters = parameters + hasChange = true + } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_bitbucketgit.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_bitbucketgit.go index 89876bb8c5..f38c385f43 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_bitbucketgit.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_bitbucketgit.go @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolBitbucketgit() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolBitbucketgit() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_bitbucketgit", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_bitbucketgit", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -170,12 +179,6 @@ func ResourceIBMCdToolchainToolBitbucketgit() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_bitbucketgit", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -307,7 +310,21 @@ func resourceIBMCdToolchainToolBitbucketgitRead(context context.Context, d *sche getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -320,6 +337,11 @@ func resourceIBMCdToolchainToolBitbucketgitRead(context context.Context, d *sche if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "toolchain_issues_enabled": "has_issues", } @@ -327,9 +349,6 @@ func resourceIBMCdToolchainToolBitbucketgitRead(context context.Context, d *sche if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -385,6 +404,11 @@ func resourceIBMCdToolchainToolBitbucketgitUpdate(context context.Context, d *sc return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "toolchain_issues_enabled": "has_issues", @@ -393,11 +417,6 @@ func resourceIBMCdToolchainToolBitbucketgitUpdate(context context.Context, d *sc patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_custom.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_custom.go index a210349f49..96edf773c4 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_custom.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_custom.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolCustom() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolCustom() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_custom", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_custom", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -84,12 +93,6 @@ func ResourceIBMCdToolchainToolCustom() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_custom", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -224,7 +227,21 @@ func resourceIBMCdToolchainToolCustomRead(context context.Context, d *schema.Res getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -237,6 +254,11 @@ func resourceIBMCdToolchainToolCustomRead(context context.Context, d *schema.Res if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "lifecycle_phase": "lifecyclePhase", "image_url": "imageUrl", @@ -247,9 +269,6 @@ func resourceIBMCdToolchainToolCustomRead(context context.Context, d *schema.Res if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -305,6 +324,11 @@ func resourceIBMCdToolchainToolCustomUpdate(context context.Context, d *schema.R return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "lifecycle_phase": "lifecyclePhase", @@ -316,11 +340,6 @@ func resourceIBMCdToolchainToolCustomUpdate(context context.Context, d *schema.R patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_devopsinsights.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_devopsinsights.go index 96a1452b1a..383e4d1461 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_devopsinsights.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_devopsinsights.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolDevopsinsights() *schema.Resource { @@ -165,7 +168,21 @@ func resourceIBMCdToolchainToolDevopsinsightsRead(context context.Context, d *sc getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -178,8 +195,10 @@ func resourceIBMCdToolchainToolDevopsinsightsRead(context context.Context, d *sc if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_eventnotifications.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_eventnotifications.go index 725d058b30..b85619a8d8 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_eventnotifications.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_eventnotifications.go @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolEventnotifications() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolEventnotifications() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_eventnotifications", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_eventnotifications", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -54,12 +63,6 @@ func ResourceIBMCdToolchainToolEventnotifications() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_eventnotifications", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -191,7 +194,21 @@ func resourceIBMCdToolchainToolEventnotificationsRead(context context.Context, d getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -204,6 +221,11 @@ func resourceIBMCdToolchainToolEventnotificationsRead(context context.Context, d if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "instance_crn": "instance-crn", } @@ -211,9 +233,6 @@ func resourceIBMCdToolchainToolEventnotificationsRead(context context.Context, d if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -269,6 +288,11 @@ func resourceIBMCdToolchainToolEventnotificationsUpdate(context context.Context, return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "instance_crn": "instance-crn", @@ -277,11 +301,6 @@ func resourceIBMCdToolchainToolEventnotificationsUpdate(context context.Context, patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_githubconsolidated.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_githubconsolidated.go index c41a73649d..3621c57b3a 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_githubconsolidated.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_githubconsolidated.go @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolGithubconsolidated() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolGithubconsolidated() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_githubconsolidated", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_githubconsolidated", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -44,7 +53,7 @@ func ResourceIBMCdToolchainToolGithubconsolidated() *schema.Resource { "git_id": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Set this value to 'github' for github.com, the GUID of an existing custom GitHub Enterprise server, or 'githubcustom'.", + Description: "Set this value to 'github' for github.com, or 'githubcustom' for a custom GitHub Enterprise server.", }, "title": &schema.Schema{ Type: schema.TypeString, @@ -160,7 +169,7 @@ func ResourceIBMCdToolchainToolGithubconsolidated() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Description: "Set this value to 'github' for github.com, the GUID of an existing custom GitHub Enterprise server, or 'githubcustom'.", + Description: "Set this value to 'github' for github.com, or 'githubcustom' for a custom GitHub Enterprise server.", }, "title": &schema.Schema{ Type: schema.TypeString, @@ -228,12 +237,6 @@ func ResourceIBMCdToolchainToolGithubconsolidated() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_githubconsolidated", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -365,7 +368,21 @@ func resourceIBMCdToolchainToolGithubconsolidatedRead(context context.Context, d getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -378,6 +395,11 @@ func resourceIBMCdToolchainToolGithubconsolidatedRead(context context.Context, d if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "toolchain_issues_enabled": "has_issues", } @@ -385,9 +407,6 @@ func resourceIBMCdToolchainToolGithubconsolidatedRead(context context.Context, d if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -443,6 +462,11 @@ func resourceIBMCdToolchainToolGithubconsolidatedUpdate(context context.Context, return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "toolchain_issues_enabled": "has_issues", @@ -451,11 +475,6 @@ func resourceIBMCdToolchainToolGithubconsolidatedUpdate(context context.Context, patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_gitlab.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_gitlab.go index 9f0a1b9ce3..74248b2437 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_gitlab.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_gitlab.go @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolGitlab() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolGitlab() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_gitlab", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_gitlab", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -44,7 +53,7 @@ func ResourceIBMCdToolchainToolGitlab() *schema.Resource { "git_id": &schema.Schema{ Type: schema.TypeString, Computed: true, - Description: "Set this value to 'gitlab' for gitlab.com, the GUID of an existing custom GitLab server, or 'gitlabcustom'.", + Description: "Set this value to 'gitlab' for gitlab.com, or 'gitlabcustom' for a custom GitLab server.", }, "title": &schema.Schema{ Type: schema.TypeString, @@ -155,7 +164,7 @@ func ResourceIBMCdToolchainToolGitlab() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Description: "Set this value to 'gitlab' for gitlab.com, the GUID of an existing custom GitLab server, or 'gitlabcustom'.", + Description: "Set this value to 'gitlab' for gitlab.com, or 'gitlabcustom' for a custom GitLab server.", }, "title": &schema.Schema{ Type: schema.TypeString, @@ -216,12 +225,6 @@ func ResourceIBMCdToolchainToolGitlab() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_gitlab", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -353,7 +356,21 @@ func resourceIBMCdToolchainToolGitlabRead(context context.Context, d *schema.Res getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -366,6 +383,11 @@ func resourceIBMCdToolchainToolGitlabRead(context context.Context, d *schema.Res if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "toolchain_issues_enabled": "has_issues", } @@ -373,9 +395,6 @@ func resourceIBMCdToolchainToolGitlabRead(context context.Context, d *schema.Res if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -431,6 +450,11 @@ func resourceIBMCdToolchainToolGitlabUpdate(context context.Context, d *schema.R return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "toolchain_issues_enabled": "has_issues", @@ -439,11 +463,6 @@ func resourceIBMCdToolchainToolGitlabUpdate(context context.Context, d *schema.R patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_hashicorpvault.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_hashicorpvault.go index 27aa2246df..fd013d076f 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_hashicorpvault.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_hashicorpvault.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolHashicorpvault() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolHashicorpvault() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_hashicorpvault", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_hashicorpvault", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -112,12 +121,6 @@ func ResourceIBMCdToolchainToolHashicorpvault() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_hashicorpvault", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -246,7 +249,21 @@ func resourceIBMCdToolchainToolHashicorpvaultRead(context context.Context, d *sc getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -259,13 +276,15 @@ func resourceIBMCdToolchainToolHashicorpvaultRead(context context.Context, d *sc if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } parametersMap := GetParametersFromRead(toolchainTool.Parameters, ResourceIBMCdToolchainToolHashicorpvault(), nil) if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -321,16 +340,16 @@ func resourceIBMCdToolchainToolHashicorpvaultUpdate(context context.Context, d * return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } - if d.HasChange("parameters") { - parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolHashicorpvault(), nil) - patchVals.Parameters = parameters - hasChange = true - } if d.HasChange("name") { newName := d.Get("name").(string) patchVals.Name = &newName hasChange = true } + if d.HasChange("parameters") { + parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolHashicorpvault(), nil) + patchVals.Parameters = parameters + hasChange = true + } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_hostedgit.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_hostedgit.go index ce693882ee..093960ac0b 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_hostedgit.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_hostedgit.go @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolHostedgit() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolHostedgit() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_hostedgit", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_hostedgit", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -182,12 +191,6 @@ func ResourceIBMCdToolchainToolHostedgit() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_hostedgit", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -319,7 +322,21 @@ func resourceIBMCdToolchainToolHostedgitRead(context context.Context, d *schema. getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -332,6 +349,11 @@ func resourceIBMCdToolchainToolHostedgitRead(context context.Context, d *schema. if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "toolchain_issues_enabled": "has_issues", } @@ -339,9 +361,6 @@ func resourceIBMCdToolchainToolHostedgitRead(context context.Context, d *schema. if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -397,6 +416,11 @@ func resourceIBMCdToolchainToolHostedgitUpdate(context context.Context, d *schem return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "toolchain_issues_enabled": "has_issues", @@ -405,11 +429,6 @@ func resourceIBMCdToolchainToolHostedgitUpdate(context context.Context, d *schem patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_jenkins.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_jenkins.go index 24669b54db..f5ae0d6540 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_jenkins.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_jenkins.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolJenkins() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolJenkins() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_jenkins", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_jenkins", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -72,12 +81,6 @@ func ResourceIBMCdToolchainToolJenkins() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_jenkins", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -206,7 +209,21 @@ func resourceIBMCdToolchainToolJenkinsRead(context context.Context, d *schema.Re getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -219,13 +236,15 @@ func resourceIBMCdToolchainToolJenkinsRead(context context.Context, d *schema.Re if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } parametersMap := GetParametersFromRead(toolchainTool.Parameters, ResourceIBMCdToolchainToolJenkins(), nil) if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -281,16 +300,16 @@ func resourceIBMCdToolchainToolJenkinsUpdate(context context.Context, d *schema. return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } - if d.HasChange("parameters") { - parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolJenkins(), nil) - patchVals.Parameters = parameters - hasChange = true - } if d.HasChange("name") { newName := d.Get("name").(string) patchVals.Name = &newName hasChange = true } + if d.HasChange("parameters") { + parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolJenkins(), nil) + patchVals.Parameters = parameters + hasChange = true + } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_jira.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_jira.go index e14e1143cd..04719c347e 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_jira.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_jira.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolJira() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolJira() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_jira", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_jira", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -72,12 +81,6 @@ func ResourceIBMCdToolchainToolJira() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_jira", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -210,7 +213,21 @@ func resourceIBMCdToolchainToolJiraRead(context context.Context, d *schema.Resou getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -223,6 +240,11 @@ func resourceIBMCdToolchainToolJiraRead(context context.Context, d *schema.Resou if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "api_token": "password", } @@ -230,9 +252,6 @@ func resourceIBMCdToolchainToolJiraRead(context context.Context, d *schema.Resou if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -288,6 +307,11 @@ func resourceIBMCdToolchainToolJiraUpdate(context context.Context, d *schema.Res return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "api_token": "password", @@ -296,11 +320,6 @@ func resourceIBMCdToolchainToolJiraUpdate(context context.Context, d *schema.Res patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_keyprotect.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_keyprotect.go index 6d566a2077..8bc4cd5f23 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_keyprotect.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_keyprotect.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolKeyprotect() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolKeyprotect() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_keyprotect", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_keyprotect", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -64,12 +73,6 @@ func ResourceIBMCdToolchainToolKeyprotect() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_keyprotect", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -203,7 +206,21 @@ func resourceIBMCdToolchainToolKeyprotectRead(context context.Context, d *schema getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -216,6 +233,11 @@ func resourceIBMCdToolchainToolKeyprotectRead(context context.Context, d *schema if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "location": "region", "resource_group_name": "resource-group", @@ -225,9 +247,6 @@ func resourceIBMCdToolchainToolKeyprotectRead(context context.Context, d *schema if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -283,6 +302,11 @@ func resourceIBMCdToolchainToolKeyprotectUpdate(context context.Context, d *sche return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "location": "region", @@ -293,11 +317,6 @@ func resourceIBMCdToolchainToolKeyprotectUpdate(context context.Context, d *sche patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_nexus.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_nexus.go index 530acffa6d..42fb25e7ac 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_nexus.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_nexus.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolNexus() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolNexus() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_nexus", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_nexus", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -86,12 +95,6 @@ func ResourceIBMCdToolchainToolNexus() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_nexus", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -223,7 +226,21 @@ func resourceIBMCdToolchainToolNexusRead(context context.Context, d *schema.Reso getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -236,6 +253,11 @@ func resourceIBMCdToolchainToolNexusRead(context context.Context, d *schema.Reso if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "server_url": "dashboard_url", } @@ -243,9 +265,6 @@ func resourceIBMCdToolchainToolNexusRead(context context.Context, d *schema.Reso if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -301,6 +320,11 @@ func resourceIBMCdToolchainToolNexusUpdate(context context.Context, d *schema.Re return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "server_url": "dashboard_url", @@ -309,11 +333,6 @@ func resourceIBMCdToolchainToolNexusUpdate(context context.Context, d *schema.Re patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_pagerduty.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_pagerduty.go index 7365caa2d3..79dd00e910 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_pagerduty.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_pagerduty.go @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolPagerduty() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolPagerduty() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_pagerduty", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_pagerduty", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -61,12 +70,6 @@ func ResourceIBMCdToolchainToolPagerduty() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_pagerduty", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -196,7 +199,21 @@ func resourceIBMCdToolchainToolPagerdutyRead(context context.Context, d *schema. getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -209,13 +226,15 @@ func resourceIBMCdToolchainToolPagerdutyRead(context context.Context, d *schema. if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } parametersMap := GetParametersFromRead(toolchainTool.Parameters, ResourceIBMCdToolchainToolPagerduty(), nil) if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -271,16 +290,16 @@ func resourceIBMCdToolchainToolPagerdutyUpdate(context context.Context, d *schem return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } - if d.HasChange("parameters") { - parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolPagerduty(), nil) - patchVals.Parameters = parameters - hasChange = true - } if d.HasChange("name") { newName := d.Get("name").(string) patchVals.Name = &newName hasChange = true } + if d.HasChange("parameters") { + parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolPagerduty(), nil) + patchVals.Parameters = parameters + hasChange = true + } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_pipeline.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_pipeline.go index 577dc49028..7c4f593a28 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_pipeline.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_pipeline.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolPipeline() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolPipeline() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_pipeline", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_pipeline", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -49,12 +58,6 @@ func ResourceIBMCdToolchainToolPipeline() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_pipeline", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -184,7 +187,21 @@ func resourceIBMCdToolchainToolPipelineRead(context context.Context, d *schema.R getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -197,13 +214,15 @@ func resourceIBMCdToolchainToolPipelineRead(context context.Context, d *schema.R if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } parametersMap := GetParametersFromRead(toolchainTool.Parameters, ResourceIBMCdToolchainToolPipeline(), nil) if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -259,16 +278,16 @@ func resourceIBMCdToolchainToolPipelineUpdate(context context.Context, d *schema return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } - if d.HasChange("parameters") { - parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolPipeline(), nil) - patchVals.Parameters = parameters - hasChange = true - } if d.HasChange("name") { newName := d.Get("name").(string) patchVals.Name = &newName hasChange = true } + if d.HasChange("parameters") { + parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolPipeline(), nil) + patchVals.Parameters = parameters + hasChange = true + } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_privateworker.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_privateworker.go index 03fba9f2d0..24ed105a83 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_privateworker.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_privateworker.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolPrivateworker() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolPrivateworker() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_privateworker", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_privateworker", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -61,12 +70,6 @@ func ResourceIBMCdToolchainToolPrivateworker() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_privateworker", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -199,7 +202,21 @@ func resourceIBMCdToolchainToolPrivateworkerRead(context context.Context, d *sch getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -212,6 +229,11 @@ func resourceIBMCdToolchainToolPrivateworkerRead(context context.Context, d *sch if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "worker_queue_credentials": "workerQueueCredentials", "worker_queue_identifier": "workerQueueIdentifier", @@ -220,9 +242,6 @@ func resourceIBMCdToolchainToolPrivateworkerRead(context context.Context, d *sch if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -278,6 +297,11 @@ func resourceIBMCdToolchainToolPrivateworkerUpdate(context context.Context, d *s return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "worker_queue_credentials": "workerQueueCredentials", @@ -287,11 +311,6 @@ func resourceIBMCdToolchainToolPrivateworkerUpdate(context context.Context, d *s patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_saucelabs.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_saucelabs.go index be90aaacbd..dd5317a4de 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_saucelabs.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_saucelabs.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolSaucelabs() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolSaucelabs() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_saucelabs", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_saucelabs", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -56,12 +65,6 @@ func ResourceIBMCdToolchainToolSaucelabs() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_saucelabs", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -193,7 +196,21 @@ func resourceIBMCdToolchainToolSaucelabsRead(context context.Context, d *schema. getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -206,6 +223,11 @@ func resourceIBMCdToolchainToolSaucelabsRead(context context.Context, d *schema. if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "access_key": "key", } @@ -213,9 +235,6 @@ func resourceIBMCdToolchainToolSaucelabsRead(context context.Context, d *schema. if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -271,6 +290,11 @@ func resourceIBMCdToolchainToolSaucelabsUpdate(context context.Context, d *schem return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "access_key": "key", @@ -279,11 +303,6 @@ func resourceIBMCdToolchainToolSaucelabsUpdate(context context.Context, d *schem patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_secretsmanager.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_secretsmanager.go index ce45e84702..1c07ef116d 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_secretsmanager.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_secretsmanager.go @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolSecretsmanager() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolSecretsmanager() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_secretsmanager", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_secretsmanager", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -74,12 +83,6 @@ func ResourceIBMCdToolchainToolSecretsmanager() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_secretsmanager", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -215,7 +218,21 @@ func resourceIBMCdToolchainToolSecretsmanagerRead(context context.Context, d *sc getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -228,6 +245,11 @@ func resourceIBMCdToolchainToolSecretsmanagerRead(context context.Context, d *sc if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "instance_id_type": "instance-id-type", "location": "region", @@ -239,9 +261,6 @@ func resourceIBMCdToolchainToolSecretsmanagerRead(context context.Context, d *sc if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -297,6 +316,11 @@ func resourceIBMCdToolchainToolSecretsmanagerUpdate(context context.Context, d * return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "instance_id_type": "instance-id-type", @@ -309,11 +333,6 @@ func resourceIBMCdToolchainToolSecretsmanagerUpdate(context context.Context, d * patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_securitycompliance.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_securitycompliance.go index 88de6a3137..1da7eaadfe 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_securitycompliance.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_securitycompliance.go @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolSecuritycompliance() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolSecuritycompliance() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_securitycompliance", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_securitycompliance", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -54,7 +63,7 @@ func ResourceIBMCdToolchainToolSecuritycompliance() *schema.Resource { "trigger_scan": &schema.Schema{ Type: schema.TypeString, Optional: true, - Deprecated: "This argument is deprecated and will be removed in a future release. Refer to the provider documentation for details.", + Deprecated: "This argument is deprecated and may be removed in a future release", Description: "Set to `enabled` to indicate that a DevSecOps pipeline task should trigger a Security and Compliance Center run of a Hybrid cloud validation scan. Note, each scan may incur charges. When enabled, other parameters become relevant that are needed to trigger that scan; `api_key`, `scope`, `profile`. Hybrid cloud scans are deprecated and are planned to be removed. This option will stop working at that time. For more information see the [Security and Compliance Center Release Notes](https://cloud.ibm.com/docs/security-compliance?topic=security-compliance-release-notes#security-compliance-march312023).", }, "api_key": &schema.Schema{ @@ -62,19 +71,19 @@ func ResourceIBMCdToolchainToolSecuritycompliance() *schema.Resource { Optional: true, DiffSuppressFunc: flex.SuppressHashedRawSecret, Sensitive: true, - Deprecated: "This argument is deprecated and will be removed in a future release. Refer to the provider documentation for details.", + Deprecated: "This argument is deprecated and may be removed in a future release", Description: "The IBM Cloud API key used to access the Security and Compliance Center API. This parameter is only relevant when the `trigger_scan` parameter is `enabled`. For information about the deprecation see the `trigger_scan` parameter. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials).", }, "scope": &schema.Schema{ Type: schema.TypeString, Optional: true, - Deprecated: "This argument is deprecated and will be removed in a future release. Refer to the provider documentation for details.", + Deprecated: "This argument is deprecated and may be removed in a future release", Description: "The name of a Security and Compliance Center scope, which has previously been created in that service. When the `trigger_scan` parameter is set to `enabled`, then the Validation scan will scan all the resources in that scope. Select a scope that contains this toolchain, so that the scan will find the evidence that has been recently updated by the DevSecOps pipeline-run. This parameter is only relevant when the `trigger_scan` parameter is `enabled`. For information about the deprecation see the `trigger_scan` parameter.", }, "profile": &schema.Schema{ Type: schema.TypeString, Optional: true, - Deprecated: "This argument is deprecated and will be removed in a future release. Refer to the provider documentation for details.", + Deprecated: "This argument is deprecated and may be removed in a future release", Description: "The name of a Security and Compliance Center, Hybrid cloud profile. Usually, use the predefined profile \"IBM Cloud Security Best Practices v1.0.0\", which contains the DevSecOps toolchain goals. Or use a user-authored customized profile that has been configured to contain those goals. When the `trigger_scan` parameter is set to `enabled`, then the Validation scan will use the controls and goals in the configured profile. If configured with a profile that does not check the DevSecOps toolchain goals, it might incorrectly indicate that the toolchain status is passed even though some of the DevSecOps scans had actually failed. This parameter is only relevant when the `trigger_scan` parameter is `enabled`. For information about the deprecation see the `trigger_scan` parameter.", }, "use_profile_attachment": &schema.Schema{ @@ -117,12 +126,6 @@ func ResourceIBMCdToolchainToolSecuritycompliance() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_securitycompliance", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -255,7 +258,21 @@ func resourceIBMCdToolchainToolSecuritycomplianceRead(context context.Context, d getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -268,6 +285,11 @@ func resourceIBMCdToolchainToolSecuritycomplianceRead(context context.Context, d if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "evidence_repo_url": "evidence_repo_name", "api_key": "api-key", @@ -276,9 +298,6 @@ func resourceIBMCdToolchainToolSecuritycomplianceRead(context context.Context, d if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -334,6 +353,11 @@ func resourceIBMCdToolchainToolSecuritycomplianceUpdate(context context.Context, return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "evidence_repo_url": "evidence_repo_name", @@ -343,11 +367,6 @@ func resourceIBMCdToolchainToolSecuritycomplianceUpdate(context context.Context, patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_slack.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_slack.go index 325f22d853..d5093252e2 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_slack.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_slack.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolSlack() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolSlack() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_slack", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_slack", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -91,12 +100,6 @@ func ResourceIBMCdToolchainToolSlack() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_slack", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -229,7 +232,21 @@ func resourceIBMCdToolchainToolSlackRead(context context.Context, d *schema.Reso getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -242,6 +259,11 @@ func resourceIBMCdToolchainToolSlackRead(context context.Context, d *schema.Reso if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "webhook": "api_token", "team_name": "team_url", @@ -250,9 +272,6 @@ func resourceIBMCdToolchainToolSlackRead(context context.Context, d *schema.Reso if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -308,6 +327,11 @@ func resourceIBMCdToolchainToolSlackUpdate(context context.Context, d *schema.Re return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "webhook": "api_token", @@ -317,11 +341,6 @@ func resourceIBMCdToolchainToolSlackUpdate(context context.Context, d *schema.Re patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_sonarqube.go b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_sonarqube.go index 853db892bf..9df98c6abe 100644 --- a/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_sonarqube.go +++ b/ibm/service/cdtoolchain/resource_ibm_cd_toolchain_tool_sonarqube.go @@ -1,4 +1,4 @@ -// Copyright IBM Corp. 2022 All Rights Reserved. +// Copyright IBM Corp. 2023 All Rights Reserved. // Licensed under the Mozilla Public License v2.0 package cdtoolchain @@ -7,14 +7,17 @@ import ( "context" "fmt" "log" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" "github.com/IBM/continuous-delivery-go-sdk/cdtoolchainv2" + "github.com/IBM/go-sdk-core/v5/core" ) func ResourceIBMCdToolchainToolSonarqube() *schema.Resource { @@ -33,6 +36,12 @@ func ResourceIBMCdToolchainToolSonarqube() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_sonarqube", "toolchain_id"), Description: "ID of the toolchain to bind the tool to.", }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_sonarqube", "name"), + Description: "Name of the tool.", + }, "parameters": &schema.Schema{ Type: schema.TypeList, MinItems: 1, @@ -72,12 +81,6 @@ func ResourceIBMCdToolchainToolSonarqube() *schema.Resource { }, }, }, - "name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_sonarqube", "name"), - Description: "Name of the tool.", - }, "resource_group_id": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -209,7 +212,21 @@ func resourceIBMCdToolchainToolSonarqubeRead(context context.Context, d *schema. getToolByIDOptions.SetToolchainID(parts[0]) getToolByIDOptions.SetToolID(parts[1]) - toolchainTool, response, err := cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + var toolchainTool *cdtoolchainv2.ToolchainTool + var response *core.DetailedResponse + err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + if err != nil || toolchainTool == nil { + if response != nil && response.StatusCode == 404 { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions) + } if err != nil { if response != nil && response.StatusCode == 404 { d.SetId("") @@ -222,6 +239,11 @@ func resourceIBMCdToolchainToolSonarqubeRead(context context.Context, d *schema. if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil { return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err)) } + if !core.IsNil(toolchainTool.Name) { + if err = d.Set("name", toolchainTool.Name); err != nil { + return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + } + } remapFields := map[string]string{ "server_url": "dashboard_url", } @@ -229,9 +251,6 @@ func resourceIBMCdToolchainToolSonarqubeRead(context context.Context, d *schema. if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil { return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err)) } - if err = d.Set("name", toolchainTool.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) - } if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil { return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err)) } @@ -287,6 +306,11 @@ func resourceIBMCdToolchainToolSonarqubeUpdate(context context.Context, d *schem return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+ " The resource must be re-created to update this property.", "toolchain_id")) } + if d.HasChange("name") { + newName := d.Get("name").(string) + patchVals.Name = &newName + hasChange = true + } if d.HasChange("parameters") { remapFields := map[string]string{ "server_url": "dashboard_url", @@ -295,11 +319,6 @@ func resourceIBMCdToolchainToolSonarqubeUpdate(context context.Context, d *schem patchVals.Parameters = parameters hasChange = true } - if d.HasChange("name") { - newName := d.Get("name").(string) - patchVals.Name = &newName - hasChange = true - } if hasChange { updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch() diff --git a/website/docs/d/cd_toolchain.html.markdown b/website/docs/d/cd_toolchain.html.markdown index 20d1ac80a8..6315b70c0c 100644 --- a/website/docs/d/cd_toolchain.html.markdown +++ b/website/docs/d/cd_toolchain.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain -Provides a read-only data source for cd_toolchain. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. ## Example Usage @@ -20,14 +20,14 @@ data "ibm_cd_toolchain" "cd_toolchain" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `toolchain_id` - (Required, Forces new resource, String) ID of the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain. * `account_id` - (String) Account ID where toolchain can be found. @@ -38,16 +38,18 @@ In addition to all argument references listed, you can access the following attr * `crn` - (String) Toolchain CRN. -* `description` - (String) Toolchain description. +* `description` - (String) Describes the toolchain. + * Constraints: The maximum length is `500` characters. The minimum length is `0` characters. The value must match regular expression `/^(.*?)$/`. * `href` - (String) URI that can be used to retrieve toolchain. * `location` - (String) Toolchain region. * `name` - (String) Toolchain name. - * Constraints: The maximum length is `128` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. -* `resource_group_id` - (String) Resource group where the toolchain is located. +* `resource_group_id` - (Forces new resource, String) Resource group where the toolchain is located. + * Constraints: The maximum length is `32` characters. The minimum length is `32` characters. The value must match regular expression `/^[0-9a-f]{32}$/`. * `ui_href` - (String) URL of a user-facing user interface for this toolchain. @@ -55,4 +57,3 @@ In addition to all argument references listed, you can access the following attr * `tags` - (Array of Strings) Tags associated with the toolchain. - diff --git a/website/docs/d/cd_toolchain_tool_appconfig.html.markdown b/website/docs/d/cd_toolchain_tool_appconfig.html.markdown index 9f88491e13..0364b1d671 100644 --- a/website/docs/d/cd_toolchain_tool_appconfig.html.markdown +++ b/website/docs/d/cd_toolchain_tool_appconfig.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_appconfig -Provides a read-only data source for cd_toolchain_tool_appconfig. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_appconfig. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-app-configuration) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_appconfig" "cd_toolchain_tool_appconfig" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_appconfig. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `collection_id` - (String) The ID of the App Configuration collection. * Constraints: The value must match regular expression `/\\S/`. * `environment_id` - (String) The ID of the App Configuration environment. @@ -54,7 +55,7 @@ Nested scheme for **parameters**: * `resource_group_name` - (String) The name of the resource group where the App Configuration service instance is located. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_artifactory.html.markdown b/website/docs/d/cd_toolchain_tool_artifactory.html.markdown index aa3fcef0e0..52c3bf5d58 100644 --- a/website/docs/d/cd_toolchain_tool_artifactory.html.markdown +++ b/website/docs/d/cd_toolchain_tool_artifactory.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_artifactory -Provides a read-only data source for cd_toolchain_tool_artifactory. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_artifactory. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-artifactory) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_artifactory" "cd_toolchain_tool_artifactory" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_artifactory. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `dashboard_url` - (String) The URL of the Artifactory server dashboard for this integration. In the graphical UI, this is the dashboard that the browser will navigate to when you click the Artifactory integration tile. * `mirror_url` - (String) The URL for your Artifactory virtual repository, which is a repository that can see your private repositories and a cache of the public repositories. * `name` - (String) The name for this tool integration. @@ -56,7 +57,7 @@ Nested scheme for **parameters**: * `user_id` - (String) The User ID or email for your Artifactory repository. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_bitbucketgit.html.markdown b/website/docs/d/cd_toolchain_tool_bitbucketgit.html.markdown index fa464c0357..4458013bb4 100644 --- a/website/docs/d/cd_toolchain_tool_bitbucketgit.html.markdown +++ b/website/docs/d/cd_toolchain_tool_bitbucketgit.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_bitbucketgit -Provides a read-only data source for cd_toolchain_tool_bitbucketgit. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_bitbucketgit. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-bitbucket) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_bitbucketgit" "cd_toolchain_tool_bitbucketgit" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_bitbucketgit. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_root_url` - (String) The API root URL for the Bitbucket Server. * `default_branch` - (String) The default branch of the git repository. * `enable_traceability` - (Boolean) Set this value to 'true' to track the deployment of code changes by creating tags, labels and comments on commits, pull requests and referenced issues. @@ -63,7 +64,7 @@ Nested scheme for **parameters**: * Constraints: Allowable values are: `new`, `fork`, `clone`, `link`, `new_if_not_exists`, `clone_if_not_exists`, `fork_if_not_exists`. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_custom.html.markdown b/website/docs/d/cd_toolchain_tool_custom.html.markdown index e0ddd276ec..b516aefd55 100644 --- a/website/docs/d/cd_toolchain_tool_custom.html.markdown +++ b/website/docs/d/cd_toolchain_tool_custom.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_custom -Provides a read-only data source for cd_toolchain_tool_custom. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_custom. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-othertool) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_custom" "cd_toolchain_tool_custom" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_custom. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `additional_properties` - (String) Any information that is needed to integrate with other tools in the toolchain. * `dashboard_url` - (String) The URL of the dashboard for this integration. In the graphical UI, this is the dashboard that the browser will navigate to when you click the integration tile. * `description` - (String) A description outlining the function of this tool. @@ -54,7 +55,7 @@ Nested scheme for **parameters**: * `type` - (String) The type of tool that this custom tool is integrating with. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_devopsinsights.html.markdown b/website/docs/d/cd_toolchain_tool_devopsinsights.html.markdown index e36c31ae4c..e16d2efe34 100644 --- a/website/docs/d/cd_toolchain_tool_devopsinsights.html.markdown +++ b/website/docs/d/cd_toolchain_tool_devopsinsights.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_devopsinsights -Provides a read-only data source for cd_toolchain_tool_devopsinsights. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about cd_toolchain_tool_devopsinsights. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-dra) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_devopsinsights" "cd_toolchain_tool_devopsinsights" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_devopsinsights. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_eventnotifications.html.markdown b/website/docs/d/cd_toolchain_tool_eventnotifications.html.markdown index cb14dd70e5..6bf0ec322b 100644 --- a/website/docs/d/cd_toolchain_tool_eventnotifications.html.markdown +++ b/website/docs/d/cd_toolchain_tool_eventnotifications.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_eventnotifications -Provides a read-only data source for cd_toolchain_tool_eventnotifications. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about cd_toolchain_tool_eventnotifications. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-event-notifications-integration) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_eventnotifications" "cd_toolchain_tool_eventnotifica ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,23 +32,24 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_eventnotifications. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `instance_crn` - (String) The CRN of the Event Notifications service instance. * Constraints: The value must match regular expression `/\\S/`. * `name` - (String) The name used to identify this tool integration. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_githubconsolidated.html.markdown b/website/docs/d/cd_toolchain_tool_githubconsolidated.html.markdown index a1608a4829..3372cd1f8a 100644 --- a/website/docs/d/cd_toolchain_tool_githubconsolidated.html.markdown +++ b/website/docs/d/cd_toolchain_tool_githubconsolidated.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_githubconsolidated -Provides a read-only data source for cd_toolchain_tool_githubconsolidated. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_githubconsolidated. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-github) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_githubconsolidated" "cd_toolchain_tool_githubconsoli ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_githubconsolidated. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_root_url` - (String) The API root URL for the GitHub server. * `api_token` - (String) Personal Access Token. Required if ‘auth_type’ is set to ‘pat’, ignored otherwise. * `auth_type` - (String) Select the method of authentication that will be used to access the git provider. The default value is 'oauth'. @@ -54,7 +55,7 @@ Nested scheme for **parameters**: * `default_branch` - (String) The default branch of the git repository. * `enable_traceability` - (Boolean) Set this value to 'true' to track the deployment of code changes by creating tags, labels and comments on commits, pull requests and referenced issues. * Constraints: The default value is `false`. - * `git_id` - (String) Set this value to 'github' for github.com, the GUID of an existing custom GitHub Enterprise server, or 'githubcustom'. + * `git_id` - (String) Set this value to 'github' for github.com, or 'githubcustom' for a custom GitHub Enterprise server. * `integration_owner` - (String) Select the user which git operations will be performed as. * `owner_id` - (String) The GitHub user or organization that owns the repository. This parameter is required when creating a new repository, cloning, or forking a repository. The value will be computed when linking to an existing repository. * `private_repo` - (Boolean) Set this value to 'true' to make the repository private when creating a new repository or when cloning or forking a repository. This parameter is not used when linking to an existing repository. @@ -72,7 +73,7 @@ Nested scheme for **parameters**: * Constraints: Allowable values are: `new`, `fork`, `clone`, `link`, `new_if_not_exists`, `clone_if_not_exists`, `fork_if_not_exists`. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_gitlab.html.markdown b/website/docs/d/cd_toolchain_tool_gitlab.html.markdown index 044112853d..a5943ff0b9 100644 --- a/website/docs/d/cd_toolchain_tool_gitlab.html.markdown +++ b/website/docs/d/cd_toolchain_tool_gitlab.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_gitlab -Provides a read-only data source for cd_toolchain_tool_gitlab. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_gitlab. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-gitlab) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_gitlab" "cd_toolchain_tool_gitlab" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_gitlab. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_root_url` - (String) The API root URL for the GitLab Server. * `api_token` - (String) Personal Access Token. Required if ‘auth_type’ is set to ‘pat’, ignored otherwise. * `auth_type` - (String) Select the method of authentication that will be used to access the git provider. The default value is 'oauth'. @@ -52,7 +53,7 @@ Nested scheme for **parameters**: * `default_branch` - (String) The default branch of the git repository. * `enable_traceability` - (Boolean) Set this value to 'true' to track the deployment of code changes by creating tags, labels and comments on commits, pull requests and referenced issues. * Constraints: The default value is `false`. - * `git_id` - (String) Set this value to 'gitlab' for gitlab.com, the GUID of an existing custom GitLab server, or 'gitlabcustom'. + * `git_id` - (String) Set this value to 'gitlab' for gitlab.com, or 'gitlabcustom' for a custom GitLab server. * `integration_owner` - (String) Select the user which git operations will be performed as. * `owner_id` - (String) The GitLab user or group that owns the repository. This parameter is required when creating a new repository, cloning, or forking a repository. The value will be computed when linking to an existing repository. * `private_repo` - (Boolean) Set this value to 'true' to make the repository private when creating a new repository or when cloning or forking a repository. This parameter is not used when linking to an existing repository. @@ -70,7 +71,7 @@ Nested scheme for **parameters**: * Constraints: Allowable values are: `new`, `fork`, `clone`, `link`, `new_if_not_exists`, `clone_if_not_exists`, `fork_if_not_exists`. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_hashicorpvault.html.markdown b/website/docs/d/cd_toolchain_tool_hashicorpvault.html.markdown index 85f82afc53..50af3158c5 100644 --- a/website/docs/d/cd_toolchain_tool_hashicorpvault.html.markdown +++ b/website/docs/d/cd_toolchain_tool_hashicorpvault.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_hashicorpvault -Provides a read-only data source for cd_toolchain_tool_hashicorpvault. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_hashicorpvault. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-hashicorpvault) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_hashicorpvault" "cd_toolchain_tool_hashicorpvault" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_hashicorpvault. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `authentication_method` - (String) The authentication method for your HashiCorp Vault instance. * Constraints: Allowable values are: `token`, `approle`, `userpass`, `github`. * `dashboard_url` - (String) The URL of the HashiCorp Vault server dashboard for this integration. In the graphical UI, this is the dashboard that the browser will navigate to when you click the HashiCorp Vault integration tile. @@ -58,7 +59,7 @@ Nested scheme for **parameters**: * `username` - (String) The authentication username for your HashiCorp Vault instance when using the 'userpass' authentication method. This parameter is ignored for other authentication methods. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_hostedgit.html.markdown b/website/docs/d/cd_toolchain_tool_hostedgit.html.markdown index 94f4cada63..dabec3841d 100644 --- a/website/docs/d/cd_toolchain_tool_hostedgit.html.markdown +++ b/website/docs/d/cd_toolchain_tool_hostedgit.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_hostedgit -Provides a read-only data source for cd_toolchain_tool_hostedgit. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_hostedgit. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-grit) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_hostedgit" "cd_toolchain_tool_hostedgit" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_hostedgit. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_root_url` - (String) The API root URL for the GitLab server. * `api_token` - (String) Personal Access Token. Required if 'auth_type' is set to 'pat', ignored otherwise. * `auth_type` - (String) Select the method of authentication that will be used to access the git provider. The default value is 'oauth'. @@ -66,7 +67,7 @@ Nested scheme for **parameters**: * Constraints: Allowable values are: `new`, `fork`, `clone`, `link`, `new_if_not_exists`, `clone_if_not_exists`, `fork_if_not_exists`. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_jenkins.html.markdown b/website/docs/d/cd_toolchain_tool_jenkins.html.markdown index fa9d529953..2634d84972 100644 --- a/website/docs/d/cd_toolchain_tool_jenkins.html.markdown +++ b/website/docs/d/cd_toolchain_tool_jenkins.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_jenkins -Provides a read-only data source for cd_toolchain_tool_jenkins. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about cd_toolchain_tool_jenkins. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-jenkins) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_jenkins" "cd_toolchain_tool_jenkins" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_jenkins. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_token` - (String) The API token to use for Jenkins REST API calls so that DevOps Insights can collect data from Jenkins. You can find the API token on the configuration page of your Jenkins instance. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `api_user_name` - (String) The user name to use with the Jenkins server's API token, which is required so that DevOps Insights can collect data from Jenkins. You can find your API user name on the configuration page of your Jenkins instance. * `dashboard_url` - (String) The URL of the Jenkins server dashboard for this integration. In the graphical UI, this is the dashboard that the browser will navigate to when you click the Jenkins integration tile. @@ -50,7 +51,7 @@ Nested scheme for **parameters**: * `webhook_url` - (String) The webhook to use in your Jenkins jobs to send notifications to other tools in your toolchain. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_jira.html.markdown b/website/docs/d/cd_toolchain_tool_jira.html.markdown index 747f8ece14..2b48ce25a0 100644 --- a/website/docs/d/cd_toolchain_tool_jira.html.markdown +++ b/website/docs/d/cd_toolchain_tool_jira.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_jira -Provides a read-only data source for cd_toolchain_tool_jira. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_jira. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-jira) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_jira" "cd_toolchain_tool_jira" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_jira. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_token` - (String) The api token for your JIRA account. Optional for public projects. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `api_url` - (String) The base API URL for your JIRA instance. * `enable_traceability` - (Boolean) Track the deployment of code changes by creating tags, labels and comments on commits, pull requests and referenced issues. @@ -51,7 +52,7 @@ Nested scheme for **parameters**: * `username` - (String) The user name for your JIRA account. Optional for public projects. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_keyprotect.html.markdown b/website/docs/d/cd_toolchain_tool_keyprotect.html.markdown index 8939511c11..68dc5e4b7e 100644 --- a/website/docs/d/cd_toolchain_tool_keyprotect.html.markdown +++ b/website/docs/d/cd_toolchain_tool_keyprotect.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_keyprotect -Provides a read-only data source for cd_toolchain_tool_keyprotect. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_keyprotect. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-keyprotect) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_keyprotect" "cd_toolchain_tool_keyprotect" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_keyprotect. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `instance_name` - (String) The name of the Key Protect service instance. * Constraints: The value must match regular expression `/\\S/`. * `location` - (String) The IBM Cloud location where the Key Protect service instance is located. @@ -50,7 +51,7 @@ Nested scheme for **parameters**: * `resource_group_name` - (String) The name of the resource group where the Key Protect service instance is located. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_nexus.html.markdown b/website/docs/d/cd_toolchain_tool_nexus.html.markdown index 075b73bb54..dc12e31d0e 100644 --- a/website/docs/d/cd_toolchain_tool_nexus.html.markdown +++ b/website/docs/d/cd_toolchain_tool_nexus.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_nexus -Provides a read-only data source for cd_toolchain_tool_nexus. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about cd_toolchain_tool_nexus. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-nexus) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_nexus" "cd_toolchain_tool_nexus" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_nexus. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `mirror_url` - (String) The URL of the Nexus virtual repository, which is a repository that can see your private repositories and is a cache of the public repositories. * `name` - (String) The name for this tool integration. * `release_url` - (String) The URL of the Nexus release repository. @@ -54,7 +55,7 @@ Nested scheme for **parameters**: * `user_id` - (String) The user id or email for authenticating to the Nexus repository. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_pagerduty.html.markdown b/website/docs/d/cd_toolchain_tool_pagerduty.html.markdown index b5ce37af95..7f3eb52547 100644 --- a/website/docs/d/cd_toolchain_tool_pagerduty.html.markdown +++ b/website/docs/d/cd_toolchain_tool_pagerduty.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_pagerduty -Provides a read-only data source for cd_toolchain_tool_pagerduty. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_pagerduty. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-pagerduty) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_pagerduty" "cd_toolchain_tool_pagerduty" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,23 +32,24 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_pagerduty. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `service_id` - (String) The service ID of the PagerDuty service. * `service_key` - (String) The PagerDuty service integration key. You can find or create this key in the Integrations section of the PagerDuty service page. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `service_url` - (String) The URL of the PagerDuty service to post alerts to. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_pipeline.html.markdown b/website/docs/d/cd_toolchain_tool_pipeline.html.markdown index abc010cef7..6f36e89986 100644 --- a/website/docs/d/cd_toolchain_tool_pipeline.html.markdown +++ b/website/docs/d/cd_toolchain_tool_pipeline.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_pipeline -Provides a read-only data source for cd_toolchain_tool_pipeline. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_pipeline. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-deliverypipeline) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_pipeline" "cd_toolchain_tool_pipeline" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,21 +32,22 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_pipeline. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `name` - (String) The name used for this tool integration. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_privateworker.html.markdown b/website/docs/d/cd_toolchain_tool_privateworker.html.markdown index 13a1a0e0da..fa1d525b47 100644 --- a/website/docs/d/cd_toolchain_tool_privateworker.html.markdown +++ b/website/docs/d/cd_toolchain_tool_privateworker.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_privateworker -Provides a read-only data source for cd_toolchain_tool_privateworker. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_privateworker. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-privateworker) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_privateworker" "cd_toolchain_tool_privateworker" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,23 +32,24 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_privateworker. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `name` - (String) The name used for this tool integration. * `worker_queue_credentials` - (String) The service ID API key that is used by the private worker to authenticate access to the work queue. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `worker_queue_identifier` - (String) The service ID which identifies this private workers run request queue. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_saucelabs.html.markdown b/website/docs/d/cd_toolchain_tool_saucelabs.html.markdown index e938107ce4..39e18b3fcf 100644 --- a/website/docs/d/cd_toolchain_tool_saucelabs.html.markdown +++ b/website/docs/d/cd_toolchain_tool_saucelabs.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_saucelabs -Provides a read-only data source for cd_toolchain_tool_saucelabs. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about cd_toolchain_tool_saucelabs. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-saucelabs) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_saucelabs" "cd_toolchain_tool_saucelabs" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,22 +32,23 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_saucelabs. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `access_key` - (String) The access key for the Sauce Labs account. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `username` - (String) The user name for the Sauce Labs account. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_secretsmanager.html.markdown b/website/docs/d/cd_toolchain_tool_secretsmanager.html.markdown index 0d87f9b77e..e952a7b624 100644 --- a/website/docs/d/cd_toolchain_tool_secretsmanager.html.markdown +++ b/website/docs/d/cd_toolchain_tool_secretsmanager.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_secretsmanager -Provides a read-only data source for cd_toolchain_tool_secretsmanager. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_secretsmanager. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-secretsmanager) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_secretsmanager" "cd_toolchain_tool_secretsmanager" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_secretsmanager. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `instance_crn` - (String) The Secrets Manager service instance CRN (Cloud Resource Name), only relevant when using `instance-crn` as the `instance_id_type`. * Constraints: The value must match regular expression `/^crn:v1:(?:bluemix|staging):public:secrets-manager:[a-zA-Z0-9-]*\\b:a\/[0-9a-fA-F]*\\b:[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}\\b::$/`. * `instance_id_type` - (String) The type of service instance identifier. When absent defaults to `instance-name`. @@ -54,7 +55,7 @@ Nested scheme for **parameters**: * `resource_group_name` - (String) The name of the resource group where the Secrets Manager service instance is located, only relevant when using `instance-name` as the `instance_id_type`. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_securitycompliance.html.markdown b/website/docs/d/cd_toolchain_tool_securitycompliance.html.markdown index 4f73328bd4..81fdc56c58 100644 --- a/website/docs/d/cd_toolchain_tool_securitycompliance.html.markdown +++ b/website/docs/d/cd_toolchain_tool_securitycompliance.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_securitycompliance -Provides a read-only data source for cd_toolchain_tool_securitycompliance. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_securitycompliance. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-scc) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_securitycompliance" "cd_toolchain_tool_securitycompl ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_securitycompliance. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_key` - (Deprecated, String) The IBM Cloud API key used to access the Security and Compliance Center API. This parameter is only relevant when the `trigger_scan` parameter is `enabled`. For information about the deprecation see the `trigger_scan` parameter. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * Constraints: The value must match regular expression `/\\S/`. * `attachment_id` - (String) An attachment ID. An attachment is configured under a profile to define how a scan will be run. To find the attachment ID, in the browser, in the attachments list, click on the attachment link, and a panel appears with a button to copy the attachment ID. This parameter is only relevant when the `use_profile_attachment` parameter is `enabled`. @@ -64,7 +65,7 @@ Nested scheme for **parameters**: * Constraints: Allowable values are: `disabled`, `enabled`. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_slack.html.markdown b/website/docs/d/cd_toolchain_tool_slack.html.markdown index 8b297d7482..d55d76da9c 100644 --- a/website/docs/d/cd_toolchain_tool_slack.html.markdown +++ b/website/docs/d/cd_toolchain_tool_slack.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_slack -Provides a read-only data source for cd_toolchain_tool_slack. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_slack. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-slack) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_slack" "cd_toolchain_tool_slack" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_slack. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `channel_name` - (String) The Slack channel that notifications will be posted to. * `pipeline_fail` - (Boolean) Generate `pipeline failed` notifications. * Constraints: The default value is `true`. @@ -58,7 +59,7 @@ Nested scheme for **parameters**: * `webhook` - (String) The incoming webhook used by Slack to receive events. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/d/cd_toolchain_tool_sonarqube.html.markdown b/website/docs/d/cd_toolchain_tool_sonarqube.html.markdown index ae5c7581b2..c5b592de92 100644 --- a/website/docs/d/cd_toolchain_tool_sonarqube.html.markdown +++ b/website/docs/d/cd_toolchain_tool_sonarqube.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_sonarqube -Provides a read-only data source for cd_toolchain_tool_sonarqube. You can then reference the fields of the data source in other resources within the same configuration using interpolation syntax. +Provides a read-only data source to retrieve information about a cd_toolchain_tool_sonarqube. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-sonarqube) page for more information. @@ -23,7 +23,7 @@ data "ibm_cd_toolchain_tool_sonarqube" "cd_toolchain_tool_sonarqube" { ## Argument Reference -Review the argument reference that you can specify for your data source. +You can specify the following arguments for this data source. * `tool_id` - (Required, Forces new resource, String) ID of the tool bound to the toolchain. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. @@ -32,17 +32,18 @@ Review the argument reference that you can specify for your data source. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your data source is created. +After your data source is created, you can read values from the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_sonarqube. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. -* `name` - (String) Tool name. +* `name` - (String) Name of the tool. + * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `blind_connection` - (Boolean) When set to true, instructs IBM Cloud Continuous Delivery to not validate the configuration of this integration. Set this to true if the SonarQube server is not addressable on the public internet. * Constraints: The default value is `false`. * `name` - (String) The name for this tool integration. @@ -51,7 +52,7 @@ Nested scheme for **parameters**: * `user_password` - (String) The password or token for authenticating to the SonarQube server. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. diff --git a/website/docs/r/cd_toolchain.html.markdown b/website/docs/r/cd_toolchain.html.markdown index 3bc8a43d09..92a9354ca1 100644 --- a/website/docs/r/cd_toolchain.html.markdown +++ b/website/docs/r/cd_toolchain.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain -Provides a resource for cd_toolchain. This allows cd_toolchain to be created, updated and deleted. +Create, update, and delete cd_toolchains with this resource. ## Example Usage @@ -23,20 +23,20 @@ resource "ibm_cd_toolchain" "cd_toolchain_instance" { ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `description` - (Optional, String) Describes the toolchain. * Constraints: The maximum length is `500` characters. The minimum length is `0` characters. The value must match regular expression `/^(.*?)$/`. * `name` - (Required, String) Toolchain name. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. -* `resource_group_id` - (Required, Forces new resource, String) Resource group where toolchain will be created. +* `resource_group_id` - (Required, Forces new resource, String) Resource group where the toolchain is located. * Constraints: The maximum length is `32` characters. The minimum length is `32` characters. The value must match regular expression `/^[0-9a-f]{32}$/`. * `tags` - (Optional, Array of Strings) Tags associated with the toolchain. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain. * `account_id` - (String) Account ID where toolchain can be found. @@ -48,55 +48,6 @@ In addition to all argument references listed, you can access the following attr * `ui_href` - (String) URL of a user-facing user interface for this toolchain. * `updated_at` - (String) Latest toolchain update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_appconfig.html.markdown b/website/docs/r/cd_toolchain_tool_appconfig.html.markdown index 7917c1303a..273f8212eb 100644 --- a/website/docs/r/cd_toolchain_tool_appconfig.html.markdown +++ b/website/docs/r/cd_toolchain_tool_appconfig.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_appconfig -Provides a resource for cd_toolchain_tool_appconfig. This allows cd_toolchain_tool_appconfig to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_appconfigs with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-app-configuration) page for more information. @@ -30,12 +30,12 @@ resource "ibm_cd_toolchain_tool_appconfig" "cd_toolchain_tool_appconfig_instance ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `collection_id` - (Required, String) The ID of the App Configuration collection. * Constraints: The value must match regular expression `/\\S/`. * `environment_id` - (Required, String) The ID of the App Configuration environment. @@ -50,13 +50,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_appconfig. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -67,55 +67,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_artifactory.html.markdown b/website/docs/r/cd_toolchain_tool_artifactory.html.markdown index 0a3f1ae0f7..d536c0241c 100644 --- a/website/docs/r/cd_toolchain_tool_artifactory.html.markdown +++ b/website/docs/r/cd_toolchain_tool_artifactory.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_artifactory -Provides a resource for cd_toolchain_tool_artifactory. This allows cd_toolchain_tool_artifactory to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_artifactorys with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-artifactory) page for more information. @@ -31,12 +31,12 @@ resource "ibm_cd_toolchain_tool_artifactory" "cd_toolchain_tool_artifactory_inst ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `dashboard_url` - (Optional, String) The URL of the Artifactory server dashboard for this integration. In the graphical UI, this is the dashboard that the browser will navigate to when you click the Artifactory integration tile. * `mirror_url` - (Optional, String) The URL for your Artifactory virtual repository, which is a repository that can see your private repositories and a cache of the public repositories. * `name` - (Required, String) The name for this tool integration. @@ -53,13 +53,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_artifactory. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -70,55 +70,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_bitbucketgit.html.markdown b/website/docs/r/cd_toolchain_tool_bitbucketgit.html.markdown index 51a9ffb1e4..9dcf0669d2 100644 --- a/website/docs/r/cd_toolchain_tool_bitbucketgit.html.markdown +++ b/website/docs/r/cd_toolchain_tool_bitbucketgit.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_bitbucketgit -Provides a resource for cd_toolchain_tool_bitbucketgit. This allows cd_toolchain_tool_bitbucketgit to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_bitbucketgits with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-bitbucket) page for more information. @@ -35,10 +35,10 @@ resource "ibm_cd_toolchain_tool_bitbucketgit" "cd_toolchain_tool_bitbucketgit_in ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `initialization` - (Required, List) -Nested scheme for **initialization**: +Nested schema for **initialization**: * `git_id` - (Optional, Forces new resource, String) Set this value to 'bitbucketgit' for bitbucket.org, or to the GUID of a custom Bitbucket server. * `owner_id` - (Optional, Forces new resource, String) The Bitbucket user or group that owns the repository. This parameter is required when creating a new repository, cloning, or forking a repository. The value will be computed when linking to an existing repository. * `private_repo` - (Optional, Forces new resource, Boolean) Set this value to 'true' to make the repository private when creating a new repository or when cloning or forking a repository. This parameter is not used when linking to an existing repository. @@ -51,7 +51,7 @@ Nested scheme for **initialization**: * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_root_url` - (Computed, String) The API root URL for the Bitbucket Server. * `default_branch` - (Computed, String) The default branch of the git repository. * `enable_traceability` - (Optional, Boolean) Set this value to 'true' to track the deployment of code changes by creating tags, labels and comments on commits, pull requests and referenced issues. @@ -75,13 +75,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_bitbucketgit. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -92,55 +92,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_custom.html.markdown b/website/docs/r/cd_toolchain_tool_custom.html.markdown index c7321a0efe..2641e1cff3 100644 --- a/website/docs/r/cd_toolchain_tool_custom.html.markdown +++ b/website/docs/r/cd_toolchain_tool_custom.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_custom -Provides a resource for cd_toolchain_tool_custom. This allows cd_toolchain_tool_custom to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_customs with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-othertool) page for more information. @@ -28,12 +28,12 @@ resource "ibm_cd_toolchain_tool_custom" "cd_toolchain_tool_custom_instance" { ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `additional_properties` - (Optional, String) Any information that is needed to integrate with other tools in the toolchain. * `dashboard_url` - (Required, String) The URL of the dashboard for this integration. In the graphical UI, this is the dashboard that the browser will navigate to when you click the integration tile. * `description` - (Optional, String) A description outlining the function of this tool. @@ -48,13 +48,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_custom. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -65,55 +65,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_devopsinsights.html.markdown b/website/docs/r/cd_toolchain_tool_devopsinsights.html.markdown index 24e1ff527c..620e5a0ba1 100644 --- a/website/docs/r/cd_toolchain_tool_devopsinsights.html.markdown +++ b/website/docs/r/cd_toolchain_tool_devopsinsights.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_devopsinsights -Provides a resource for cd_toolchain_tool_devopsinsights. This allows cd_toolchain_tool_devopsinsights to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_devopsinsightss with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-dra) page for more information. @@ -22,7 +22,7 @@ resource "ibm_cd_toolchain_tool_devopsinsights" "cd_toolchain_tool_devopsinsight ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. @@ -31,13 +31,13 @@ Review the argument reference that you can specify for your resource. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_devopsinsights. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -48,55 +48,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_eventnotifications.html.markdown b/website/docs/r/cd_toolchain_tool_eventnotifications.html.markdown index eaa957631b..9ebe556c7e 100644 --- a/website/docs/r/cd_toolchain_tool_eventnotifications.html.markdown +++ b/website/docs/r/cd_toolchain_tool_eventnotifications.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_eventnotifications -Provides a resource for cd_toolchain_tool_eventnotifications. This allows cd_toolchain_tool_eventnotifications to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_eventnotificationss with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-event-notifications-integration) page for more information. @@ -26,12 +26,12 @@ resource "ibm_cd_toolchain_tool_eventnotifications" "cd_toolchain_tool_eventnoti ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `instance_crn` - (Required, String) The CRN of the Event Notifications service instance. * Constraints: The value must match regular expression `/\\S/`. * `name` - (Required, String) The name used to identify this tool integration. @@ -40,13 +40,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_eventnotifications. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -57,55 +57,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_githubconsolidated.html.markdown b/website/docs/r/cd_toolchain_tool_githubconsolidated.html.markdown index a76fe42049..b745117dda 100644 --- a/website/docs/r/cd_toolchain_tool_githubconsolidated.html.markdown +++ b/website/docs/r/cd_toolchain_tool_githubconsolidated.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_githubconsolidated -Provides a resource for cd_toolchain_tool_githubconsolidated. This allows cd_toolchain_tool_githubconsolidated to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_githubconsolidateds with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-github) page for more information. @@ -36,15 +36,15 @@ resource "ibm_cd_toolchain_tool_githubconsolidated" "cd_toolchain_tool_githubcon ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `initialization` - (Required, List) -Nested scheme for **initialization**: +Nested schema for **initialization**: * `auto_init` - (Optional, Forces new resource, Boolean) Setting this value to true will initialize this repository with a README. This parameter is only used when creating a new repository. * Constraints: The default value is `false`. * `blind_connection` - (Optional, Forces new resource, Boolean) Setting this value to true means the server is not addressable on the public internet. IBM Cloud will not be able to validate the connection details you provide. Certain functionality that requires API access to the git server will be disabled. Delivery pipeline will only work using a private worker that has network access to the git server. * Constraints: The default value is `false`. - * `git_id` - (Optional, Forces new resource, String) Set this value to 'github' for github.com, the GUID of an existing custom GitHub Enterprise server, or 'githubcustom'. + * `git_id` - (Optional, Forces new resource, String) Set this value to 'github' for github.com, or 'githubcustom' for a custom GitHub Enterprise server. * `owner_id` - (Optional, Forces new resource, String) The GitHub user or organization that owns the repository. This parameter is required when creating a new repository, cloning, or forking a repository. The value will be computed when linking to an existing repository. * `private_repo` - (Optional, Forces new resource, Boolean) Set this value to 'true' to make the repository private when creating a new repository or when cloning or forking a repository. This parameter is not used when linking to an existing repository. * Constraints: The default value is `false`. @@ -58,7 +58,7 @@ Nested scheme for **initialization**: * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_root_url` - (Computed, String) The API root URL for the GitHub server. * `api_token` - (Optional, String) Personal Access Token. Required if ‘auth_type’ is set to ‘pat’, ignored otherwise. * `auth_type` - (Optional, String) Select the method of authentication that will be used to access the git provider. The default value is 'oauth'. @@ -70,7 +70,7 @@ Nested scheme for **parameters**: * `default_branch` - (Computed, String) The default branch of the git repository. * `enable_traceability` - (Optional, Boolean) Set this value to 'true' to track the deployment of code changes by creating tags, labels and comments on commits, pull requests and referenced issues. * Constraints: The default value is `false`. - * `git_id` - (Computed, String) Set this value to 'github' for github.com, the GUID of an existing custom GitHub Enterprise server, or 'githubcustom'. + * `git_id` - (Computed, String) Set this value to 'github' for github.com, or 'githubcustom' for a custom GitHub Enterprise server. * `integration_owner` - (Optional, String) Select the user which git operations will be performed as. * `owner_id` - (Computed, String) The GitHub user or organization that owns the repository. This parameter is required when creating a new repository, cloning, or forking a repository. The value will be computed when linking to an existing repository. * `private_repo` - (Computed, Boolean) Set this value to 'true' to make the repository private when creating a new repository or when cloning or forking a repository. This parameter is not used when linking to an existing repository. @@ -91,13 +91,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_githubconsolidated. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -108,55 +108,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_gitlab.html.markdown b/website/docs/r/cd_toolchain_tool_gitlab.html.markdown index eb0eb724dd..d2a6003f1e 100644 --- a/website/docs/r/cd_toolchain_tool_gitlab.html.markdown +++ b/website/docs/r/cd_toolchain_tool_gitlab.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_gitlab -Provides a resource for cd_toolchain_tool_gitlab. This allows cd_toolchain_tool_gitlab to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_gitlabs with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-gitlab) page for more information. @@ -36,13 +36,13 @@ resource "ibm_cd_toolchain_tool_gitlab" "cd_toolchain_tool_gitlab_instance" { ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `initialization` - (Required, List) -Nested scheme for **initialization**: +Nested schema for **initialization**: * `blind_connection` - (Optional, Forces new resource, Boolean) Setting this value to true means the server is not addressable on the public internet. IBM Cloud will not be able to validate the connection details you provide. Certain functionality that requires API access to the git server will be disabled. Delivery pipeline will only work using a private worker that has network access to the git server. * Constraints: The default value is `false`. - * `git_id` - (Optional, Forces new resource, String) Set this value to 'gitlab' for gitlab.com, the GUID of an existing custom GitLab server, or 'gitlabcustom'. + * `git_id` - (Optional, Forces new resource, String) Set this value to 'gitlab' for gitlab.com, or 'gitlabcustom' for a custom GitLab server. * `owner_id` - (Optional, Forces new resource, String) The GitLab user or group that owns the repository. This parameter is required when creating a new repository, cloning, or forking a repository. The value will be computed when linking to an existing repository. * `private_repo` - (Optional, Forces new resource, Boolean) Set this value to 'true' to make the repository private when creating a new repository or when cloning or forking a repository. This parameter is not used when linking to an existing repository. * Constraints: The default value is `true`. @@ -56,7 +56,7 @@ Nested scheme for **initialization**: * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_root_url` - (Computed, String) The API root URL for the GitLab Server. * `api_token` - (Optional, String) Personal Access Token. Required if ‘auth_type’ is set to ‘pat’, ignored otherwise. * `auth_type` - (Optional, String) Select the method of authentication that will be used to access the git provider. The default value is 'oauth'. @@ -66,7 +66,7 @@ Nested scheme for **parameters**: * `default_branch` - (Computed, String) The default branch of the git repository. * `enable_traceability` - (Optional, Boolean) Set this value to 'true' to track the deployment of code changes by creating tags, labels and comments on commits, pull requests and referenced issues. * Constraints: The default value is `false`. - * `git_id` - (Computed, String) Set this value to 'gitlab' for gitlab.com, the GUID of an existing custom GitLab server, or 'gitlabcustom'. + * `git_id` - (Computed, String) Set this value to 'gitlab' for gitlab.com, or 'gitlabcustom' for a custom GitLab server. * `integration_owner` - (Optional, String) Select the user which git operations will be performed as. * `owner_id` - (Computed, String) The GitLab user or group that owns the repository. This parameter is required when creating a new repository, cloning, or forking a repository. The value will be computed when linking to an existing repository. * `private_repo` - (Computed, Boolean) Set this value to 'true' to make the repository private when creating a new repository or when cloning or forking a repository. This parameter is not used when linking to an existing repository. @@ -87,13 +87,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_gitlab. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -104,55 +104,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_hashicorpvault.html.markdown b/website/docs/r/cd_toolchain_tool_hashicorpvault.html.markdown index 18a8da04ea..7b5e59478c 100644 --- a/website/docs/r/cd_toolchain_tool_hashicorpvault.html.markdown +++ b/website/docs/r/cd_toolchain_tool_hashicorpvault.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_hashicorpvault -Provides a resource for cd_toolchain_tool_hashicorpvault. This allows cd_toolchain_tool_hashicorpvault to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_hashicorpvaults with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-hashicorpvault) page for more information. @@ -31,12 +31,12 @@ resource "ibm_cd_toolchain_tool_hashicorpvault" "cd_toolchain_tool_hashicorpvaul ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `authentication_method` - (Required, String) The authentication method for your HashiCorp Vault instance. * Constraints: Allowable values are: `token`, `approle`, `userpass`, `github`. * `dashboard_url` - (Required, String) The URL of the HashiCorp Vault server dashboard for this integration. In the graphical UI, this is the dashboard that the browser will navigate to when you click the HashiCorp Vault integration tile. @@ -55,13 +55,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_hashicorpvault. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -72,55 +72,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_hostedgit.html.markdown b/website/docs/r/cd_toolchain_tool_hostedgit.html.markdown index 98c0d63bac..2cbc9813c3 100644 --- a/website/docs/r/cd_toolchain_tool_hostedgit.html.markdown +++ b/website/docs/r/cd_toolchain_tool_hostedgit.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_hostedgit -Provides a resource for cd_toolchain_tool_hostedgit. This allows cd_toolchain_tool_hostedgit to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_hostedgits with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-grit) page for more information. @@ -37,10 +37,10 @@ resource "ibm_cd_toolchain_tool_hostedgit" "cd_toolchain_tool_hostedgit_instance ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `initialization` - (Required, List) -Nested scheme for **initialization**: +Nested schema for **initialization**: * `git_id` - (Optional, Forces new resource, String) Set this value to 'hostedgit' to target Git Repos and Issue Tracking. * `owner_id` - (Optional, Forces new resource, String) The GitLab user or group that owns the repository. This parameter is required when creating a new repository, cloning, or forking a repository. The value will be computed when linking to an existing repository. * `private_repo` - (Optional, Forces new resource, Boolean) Set this value to 'true' to make the repository private when creating a new repository or when cloning or forking a repository. This parameter is not used when linking to an existing repository. @@ -53,7 +53,7 @@ Nested scheme for **initialization**: * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_root_url` - (Computed, String) The API root URL for the GitLab server. * `api_token` - (Optional, String) Personal Access Token. Required if 'auth_type' is set to 'pat', ignored otherwise. * `auth_type` - (Optional, String) Select the method of authentication that will be used to access the git provider. The default value is 'oauth'. @@ -80,13 +80,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_hostedgit. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -97,55 +97,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_jenkins.html.markdown b/website/docs/r/cd_toolchain_tool_jenkins.html.markdown index e627cab66c..f89aae2efd 100644 --- a/website/docs/r/cd_toolchain_tool_jenkins.html.markdown +++ b/website/docs/r/cd_toolchain_tool_jenkins.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_jenkins -Provides a resource for cd_toolchain_tool_jenkins. This allows cd_toolchain_tool_jenkins to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_jenkinss with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-jenkins) page for more information. @@ -28,12 +28,12 @@ resource "ibm_cd_toolchain_tool_jenkins" "cd_toolchain_tool_jenkins_instance" { ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_token` - (Optional, String) The API token to use for Jenkins REST API calls so that DevOps Insights can collect data from Jenkins. You can find the API token on the configuration page of your Jenkins instance. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `api_user_name` - (Optional, String) The user name to use with the Jenkins server's API token, which is required so that DevOps Insights can collect data from Jenkins. You can find your API user name on the configuration page of your Jenkins instance. * `dashboard_url` - (Required, String) The URL of the Jenkins server dashboard for this integration. In the graphical UI, this is the dashboard that the browser will navigate to when you click the Jenkins integration tile. @@ -44,13 +44,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_jenkins. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -61,55 +61,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_jira.html.markdown b/website/docs/r/cd_toolchain_tool_jira.html.markdown index c24a4d89ec..f185bcb727 100644 --- a/website/docs/r/cd_toolchain_tool_jira.html.markdown +++ b/website/docs/r/cd_toolchain_tool_jira.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_jira -Provides a resource for cd_toolchain_tool_jira. This allows cd_toolchain_tool_jira to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_jiras with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-jira) page for more information. @@ -29,12 +29,12 @@ resource "ibm_cd_toolchain_tool_jira" "cd_toolchain_tool_jira_instance" { ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_token` - (Optional, String) The api token for your JIRA account. Optional for public projects. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `api_url` - (Required, String) The base API URL for your JIRA instance. * `enable_traceability` - (Optional, Boolean) Track the deployment of code changes by creating tags, labels and comments on commits, pull requests and referenced issues. @@ -46,13 +46,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_jira. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -63,55 +63,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_keyprotect.html.markdown b/website/docs/r/cd_toolchain_tool_keyprotect.html.markdown index 0983d15d09..15cf67cb11 100644 --- a/website/docs/r/cd_toolchain_tool_keyprotect.html.markdown +++ b/website/docs/r/cd_toolchain_tool_keyprotect.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_keyprotect -Provides a resource for cd_toolchain_tool_keyprotect. This allows cd_toolchain_tool_keyprotect to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_keyprotects with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-keyprotect) page for more information. @@ -28,12 +28,12 @@ resource "ibm_cd_toolchain_tool_keyprotect" "cd_toolchain_tool_keyprotect_instan ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `instance_name` - (Required, String) The name of the Key Protect service instance. * Constraints: The value must match regular expression `/\\S/`. * `location` - (Required, String) The IBM Cloud location where the Key Protect service instance is located. @@ -44,13 +44,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_keyprotect. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -61,55 +61,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_nexus.html.markdown b/website/docs/r/cd_toolchain_tool_nexus.html.markdown index e6dd93dd78..46e037fabf 100644 --- a/website/docs/r/cd_toolchain_tool_nexus.html.markdown +++ b/website/docs/r/cd_toolchain_tool_nexus.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_nexus -Provides a resource for cd_toolchain_tool_nexus. This allows cd_toolchain_tool_nexus to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_nexuss with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-nexus) page for more information. @@ -29,12 +29,12 @@ resource "ibm_cd_toolchain_tool_nexus" "cd_toolchain_tool_nexus_instance" { ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `mirror_url` - (Optional, String) The URL of the Nexus virtual repository, which is a repository that can see your private repositories and is a cache of the public repositories. * `name` - (Required, String) The name for this tool integration. * `release_url` - (Optional, String) The URL of the Nexus release repository. @@ -49,13 +49,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_nexus. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -66,55 +66,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_pagerduty.html.markdown b/website/docs/r/cd_toolchain_tool_pagerduty.html.markdown index 491dbc1c1b..fc04b6db91 100644 --- a/website/docs/r/cd_toolchain_tool_pagerduty.html.markdown +++ b/website/docs/r/cd_toolchain_tool_pagerduty.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_pagerduty -Provides a resource for cd_toolchain_tool_pagerduty. This allows cd_toolchain_tool_pagerduty to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_pagerdutys with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-pagerduty) page for more information. @@ -26,12 +26,12 @@ resource "ibm_cd_toolchain_tool_pagerduty" "cd_toolchain_tool_pagerduty_instance ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `service_id` - (Computed, String) The service ID of the PagerDuty service. * `service_key` - (Required, String) The PagerDuty service integration key. You can find or create this key in the Integrations section of the PagerDuty service page. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `service_url` - (Required, String) The URL of the PagerDuty service to post alerts to. @@ -40,13 +40,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_pagerduty. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -57,55 +57,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_pipeline.html.markdown b/website/docs/r/cd_toolchain_tool_pipeline.html.markdown index ecb19b9b9d..d5022a17aa 100644 --- a/website/docs/r/cd_toolchain_tool_pipeline.html.markdown +++ b/website/docs/r/cd_toolchain_tool_pipeline.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_pipeline -Provides a resource for cd_toolchain_tool_pipeline. This allows cd_toolchain_tool_pipeline to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_pipelines with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-deliverypipeline) page for more information. @@ -25,25 +25,25 @@ resource "ibm_cd_toolchain_tool_pipeline" "cd_toolchain_tool_pipeline_instance" ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `name` - (Optional, String) The name used for this tool integration. * `toolchain_id` - (Required, Forces new resource, String) ID of the toolchain to bind the tool to. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_pipeline. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -54,55 +54,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_privateworker.html.markdown b/website/docs/r/cd_toolchain_tool_privateworker.html.markdown index d6e047e5a0..ca5674a051 100644 --- a/website/docs/r/cd_toolchain_tool_privateworker.html.markdown +++ b/website/docs/r/cd_toolchain_tool_privateworker.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_privateworker -Provides a resource for cd_toolchain_tool_privateworker. This allows cd_toolchain_tool_privateworker to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_privateworkers with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-privateworker) page for more information. @@ -26,12 +26,12 @@ resource "ibm_cd_toolchain_tool_privateworker" "cd_toolchain_tool_privateworker_ ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `name` - (Required, String) The name used for this tool integration. * `worker_queue_credentials` - (Required, String) The service ID API key that is used by the private worker to authenticate access to the work queue. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `worker_queue_identifier` - (Computed, String) The service ID which identifies this private workers run request queue. @@ -40,13 +40,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_privateworker. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -57,55 +57,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_saucelabs.html.markdown b/website/docs/r/cd_toolchain_tool_saucelabs.html.markdown index e1c732e567..93a0f8eda7 100644 --- a/website/docs/r/cd_toolchain_tool_saucelabs.html.markdown +++ b/website/docs/r/cd_toolchain_tool_saucelabs.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_saucelabs -Provides a resource for cd_toolchain_tool_saucelabs. This allows cd_toolchain_tool_saucelabs to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_saucelabss with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-saucelabs) page for more information. @@ -26,12 +26,12 @@ resource "ibm_cd_toolchain_tool_saucelabs" "cd_toolchain_tool_saucelabs_instance ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `access_key` - (Required, String) The access key for the Sauce Labs account. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * `username` - (Required, String) The user name for the Sauce Labs account. * `toolchain_id` - (Required, Forces new resource, String) ID of the toolchain to bind the tool to. @@ -39,13 +39,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_saucelabs. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -56,55 +56,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_secretsmanager.html.markdown b/website/docs/r/cd_toolchain_tool_secretsmanager.html.markdown index 38a560f031..04b54274d1 100644 --- a/website/docs/r/cd_toolchain_tool_secretsmanager.html.markdown +++ b/website/docs/r/cd_toolchain_tool_secretsmanager.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_secretsmanager -Provides a resource for cd_toolchain_tool_secretsmanager. This allows cd_toolchain_tool_secretsmanager to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_secretsmanagers with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-secretsmanager) page for more information. @@ -27,12 +27,12 @@ resource "ibm_cd_toolchain_tool_secretsmanager" "cd_toolchain_tool_secretsmanage ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `instance_crn` - (Optional, String) The Secrets Manager service instance CRN (Cloud Resource Name), only relevant when using `instance-crn` as the `instance_id_type`. * Constraints: The value must match regular expression `/^crn:v1:(?:bluemix|staging):public:secrets-manager:[a-zA-Z0-9-]*\\b:a\/[0-9a-fA-F]*\\b:[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}\\b::$/`. * `instance_id_type` - (Optional, String) The type of service instance identifier. When absent defaults to `instance-name`. @@ -47,13 +47,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_secretsmanager. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -64,55 +64,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_securitycompliance.html.markdown b/website/docs/r/cd_toolchain_tool_securitycompliance.html.markdown index 096a32b756..477862aeb4 100644 --- a/website/docs/r/cd_toolchain_tool_securitycompliance.html.markdown +++ b/website/docs/r/cd_toolchain_tool_securitycompliance.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_securitycompliance -Provides a resource for cd_toolchain_tool_securitycompliance. This allows cd_toolchain_tool_securitycompliance to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_securitycompliances with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-scc) page for more information. @@ -27,12 +27,12 @@ resource "ibm_cd_toolchain_tool_securitycompliance" "cd_toolchain_tool_securityc ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `api_key` - (Deprecated, Optional, String) The IBM Cloud API key used to access the Security and Compliance Center API. This parameter is only relevant when the `trigger_scan` parameter is `enabled`. For information about the deprecation see the `trigger_scan` parameter. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials). * Constraints: The value must match regular expression `/\\S/`. * `attachment_id` - (Optional, String) An attachment ID. An attachment is configured under a profile to define how a scan will be run. To find the attachment ID, in the browser, in the attachments list, click on the attachment link, and a panel appears with a button to copy the attachment ID. This parameter is only relevant when the `use_profile_attachment` parameter is `enabled`. @@ -57,13 +57,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_securitycompliance. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -74,55 +74,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_slack.html.markdown b/website/docs/r/cd_toolchain_tool_slack.html.markdown index edee87a2ae..5638f6671e 100644 --- a/website/docs/r/cd_toolchain_tool_slack.html.markdown +++ b/website/docs/r/cd_toolchain_tool_slack.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_slack -Provides a resource for cd_toolchain_tool_slack. This allows cd_toolchain_tool_slack to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_slacks with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-slack) page for more information. @@ -32,12 +32,12 @@ resource "ibm_cd_toolchain_tool_slack" "cd_toolchain_tool_slack_instance" { ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `channel_name` - (Required, String) The Slack channel that notifications will be posted to. * `pipeline_fail` - (Optional, Boolean) Generate `pipeline failed` notifications. * Constraints: The default value is `true`. @@ -56,13 +56,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_slack. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -73,55 +73,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import diff --git a/website/docs/r/cd_toolchain_tool_sonarqube.html.markdown b/website/docs/r/cd_toolchain_tool_sonarqube.html.markdown index 28e452eaca..66e714963b 100644 --- a/website/docs/r/cd_toolchain_tool_sonarqube.html.markdown +++ b/website/docs/r/cd_toolchain_tool_sonarqube.html.markdown @@ -8,7 +8,7 @@ subcategory: "Continuous Delivery" # ibm_cd_toolchain_tool_sonarqube -Provides a resource for cd_toolchain_tool_sonarqube. This allows cd_toolchain_tool_sonarqube to be created, updated and deleted. +Create, update, and delete cd_toolchain_tool_sonarqubes with this resource. See the [tool integration](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-sonarqube) page for more information. @@ -29,12 +29,12 @@ resource "ibm_cd_toolchain_tool_sonarqube" "cd_toolchain_tool_sonarqube_instance ## Argument Reference -Review the argument reference that you can specify for your resource. +You can specify the following arguments for this resource. * `name` - (Optional, String) Name of the tool. * Constraints: The maximum length is `128` characters. The minimum length is `0` characters. The value must match regular expression `/^([^\\x00-\\x7F]|[a-zA-Z0-9-._ ])+$/`. * `parameters` - (Required, List) Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the Configuring tool integrations page. -Nested scheme for **parameters**: +Nested schema for **parameters**: * `blind_connection` - (Optional, Boolean) When set to true, instructs IBM Cloud Continuous Delivery to not validate the configuration of this integration. Set this to true if the SonarQube server is not addressable on the public internet. * Constraints: The default value is `false`. * `name` - (Required, String) The name for this tool integration. @@ -46,13 +46,13 @@ Nested scheme for **parameters**: ## Attribute Reference -In addition to all argument references listed, you can access the following attribute references after your resource is created. +After your resource is created, you can read values from the listed arguments and the following attributes. * `id` - The unique identifier of the cd_toolchain_tool_sonarqube. * `crn` - (String) Tool CRN. * `href` - (String) URI representing the tool. * `referent` - (List) Information on URIs to access this resource through the UI or API. -Nested scheme for **referent**: +Nested schema for **referent**: * `api_href` - (String) URI representing this resource through an API. * `ui_href` - (String) URI representing this resource through the UI. * `resource_group_id` - (String) Resource group where the tool is located. @@ -63,55 +63,6 @@ Nested scheme for **referent**: * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/`. * `updated_at` - (String) Latest tool update timestamp. -## Provider Configuration - -The IBM Cloud provider offers a flexible means of providing credentials for authentication. The following methods are supported, in this order, and explained below: - -- Static credentials -- Environment variables - -To find which credentials are required for this resource, see the service table [here](https://cloud.ibm.com/docs/ibm-cloud-provider-for-terraform?topic=ibm-cloud-provider-for-terraform-provider-reference#required-parameters). - -### Static credentials - -You can provide your static credentials by adding the `ibmcloud_api_key`, `iaas_classic_username`, and `iaas_classic_api_key` arguments in the IBM Cloud provider block. - -Usage: -``` -provider "ibm" { - ibmcloud_api_key = "" - iaas_classic_username = "" - iaas_classic_api_key = "" -} -``` - -### Environment variables - -You can provide your credentials by exporting the `IC_API_KEY`, `IAAS_CLASSIC_USERNAME`, and `IAAS_CLASSIC_API_KEY` environment variables, representing your IBM Cloud platform API key, IBM Cloud Classic Infrastructure (SoftLayer) user name, and IBM Cloud infrastructure API key, respectively. - -``` -provider "ibm" {} -``` - -Usage: -``` -export IC_API_KEY="ibmcloud_api_key" -export IAAS_CLASSIC_USERNAME="iaas_classic_username" -export IAAS_CLASSIC_API_KEY="iaas_classic_api_key" -terraform plan -``` - -Note: - -1. Create or find your `ibmcloud_api_key` and `iaas_classic_api_key` [here](https://cloud.ibm.com/iam/apikeys). - - Select `My IBM Cloud API Keys` option from view dropdown for `ibmcloud_api_key` - - Select `Classic Infrastructure API Keys` option from view dropdown for `iaas_classic_api_key` -2. For iaas_classic_username - - Go to [Users](https://cloud.ibm.com/iam/users) - - Click on user. - - Find user name in the `VPN password` section under `User Details` tab - -For more informaton, see [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs#authentication). ## Import From 1906d3cfca28c46104f46d98bdfdc5c3683e29d2 Mon Sep 17 00:00:00 2001 From: "akocbek@ie.ibm.com" Date: Wed, 13 Sep 2023 10:41:46 +0100 Subject: [PATCH 3/5] feat: add default cluster versions to cluster versions data source --- ...a_source_ibm_container_cluster_versions.go | 20 +++++++++++++++++++ ...rce_ibm_container_cluster_versions_test.go | 2 ++ .../container_cluster_versions.html.markdown | 2 ++ 3 files changed, 24 insertions(+) diff --git a/ibm/service/kubernetes/data_source_ibm_container_cluster_versions.go b/ibm/service/kubernetes/data_source_ibm_container_cluster_versions.go index 348cb791c5..c84ed63526 100644 --- a/ibm/service/kubernetes/data_source_ibm_container_cluster_versions.go +++ b/ibm/service/kubernetes/data_source_ibm_container_cluster_versions.go @@ -57,6 +57,16 @@ func DataSourceIBMContainerClusterVersions() *schema.Resource { Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, + "default_openshift_version": { + Description: "Default openshift-version", + Type: schema.TypeString, + Computed: true, + }, + "default_kube_version": { + Description: "Default kube-version", + Type: schema.TypeString, + Computed: true, + }, }, } } @@ -74,16 +84,26 @@ func dataSourceIBMContainerClusterVersionsRead(d *schema.ResourceData, meta inte availableVersions, _ := verAPI.ListV1(targetEnv) versions := make([]string, len(availableVersions["kubernetes"])) + var defaultKubeVersion string for i, version := range availableVersions["kubernetes"] { versions[i] = fmt.Sprintf("%d%s%d%s%d", version.Major, ".", version.Minor, ".", version.Patch) + if version.Default { + defaultKubeVersion = fmt.Sprintf("%d%s%d%s%d", version.Major, ".", version.Minor, ".", version.Patch) + } } openshiftVersions := make([]string, len(availableVersions["openshift"])) + var defaultOpenshiftVersion string for i, version := range availableVersions["openshift"] { openshiftVersions[i] = fmt.Sprintf("%d%s%d%s%d", version.Major, ".", version.Minor, ".", version.Patch) + if version.Default { + defaultOpenshiftVersion = fmt.Sprintf("%d%s%d%s%d", version.Major, ".", version.Minor, ".", version.Patch) + } } d.SetId(time.Now().UTC().String()) d.Set("valid_kube_versions", versions) d.Set("valid_openshift_versions", openshiftVersions) + d.Set("default_kube_version", defaultKubeVersion) + d.Set("default_openshift_version", defaultOpenshiftVersion) return nil } diff --git a/ibm/service/kubernetes/data_source_ibm_container_cluster_versions_test.go b/ibm/service/kubernetes/data_source_ibm_container_cluster_versions_test.go index cb1906e4fb..820e2033dc 100644 --- a/ibm/service/kubernetes/data_source_ibm_container_cluster_versions_test.go +++ b/ibm/service/kubernetes/data_source_ibm_container_cluster_versions_test.go @@ -22,6 +22,8 @@ func TestAccIBMContainerClusterVersionsDataSource_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("data.ibm_container_cluster_versions.versions", "valid_kube_versions.0"), resource.TestCheckResourceAttrSet("data.ibm_container_cluster_versions.versions", "valid_openshift_versions.0"), + resource.TestCheckResourceAttrSet("data.ibm_container_cluster_versions.versions", "default_kube_version"), + resource.TestCheckResourceAttrSet("data.ibm_container_cluster_versions.versions", "default_openshift_version"), ), }, }, diff --git a/website/docs/d/container_cluster_versions.html.markdown b/website/docs/d/container_cluster_versions.html.markdown index 2b22e68be0..055fbd9d6f 100644 --- a/website/docs/d/container_cluster_versions.html.markdown +++ b/website/docs/d/container_cluster_versions.html.markdown @@ -41,3 +41,5 @@ In addition to all argument reference list, you can access the following attribu - `id` - (String) The unique identifier of the cluster. - `valid_kube_versions` - (String) The supported Kubernetes version in IBM Cloud Kubernetes Service clusters. - `valid_openshift_versions` - (String) The supported OpenShift Container Platform version in Red Hat OpenShift on IBM Cloud clusters. +- `default_kube_version` - (String) The default Kubernetes version in IBM Cloud Kubernetes Service clusters. +- `default_openshift_version` - (String) The default OpenShift Container Platform version in Red Hat OpenShift on IBM Cloud clusters. From 93cc90a09e10d0bd1900088dd4ce25c2ba1c28e9 Mon Sep 17 00:00:00 2001 From: William Siew <38149204+william8siew@users.noreply.github.com> Date: Thu, 14 Sep 2023 09:28:04 -0500 Subject: [PATCH 4/5] Add description for keys and force_delete for deleteKeyRings for IBM KMS (#4767) * updated go sdk to v0.12.2, added description to kms_key, made payload sensitive for kms_key and others, fixed docs where expiration date specified milliseconds which forces perma replacement in terraform, made deprecation for kp_key in docs more visible * fix regex failures of intervalcheck for kms policies * add force_delete flag to key_ring, not enabled yet * Update examples for deprecated resource to highlight it is deprecated * updated key ring docs with force_delete flag * updated docs with status 5 destroyed wording * remove 409 silencing from KeyRingDelete * resolve PR comments * added 2 new tests for force_delete * small bugfix for data source kms keys, redid key ring tests to use generic builder format, added new key ring force delete test cases * addressed pr comments bout readme * addressed PR issues * add space after 5 for destroyed in docs --------- Co-authored-by: wsiew --- examples/ibm-key-protect/README.md | 10 +- go.mod | 2 +- go.sum | 4 +- ibm/service/kms/data_source_ibm_kms_key.go | 9 +- .../kms/data_source_ibm_kms_key_test.go | 42 ++++ ibm/service/kms/data_source_ibm_kms_keys.go | 19 ++ ...resource_ibm_kms_instance_policies_test.go | 3 +- ibm/service/kms/resource_ibm_kms_key.go | 22 +- ibm/service/kms/resource_ibm_kms_key_rings.go | 23 +- .../kms/resource_ibm_kms_key_rings_test.go | 227 ++++++++++++++---- ibm/service/kms/resource_ibm_kms_key_test.go | 26 ++ ...ource_ibm_kms_key_with_policy_overrides.go | 15 +- website/docs/r/kms_key.html.markdown | 2 +- website/docs/r/kms_key_rings.html.markdown | 10 + ...ms_key_with_policy_overrides.html.markdown | 2 +- website/docs/r/kp_key.html.markdown | 5 +- 16 files changed, 351 insertions(+), 70 deletions(-) diff --git a/examples/ibm-key-protect/README.md b/examples/ibm-key-protect/README.md index b3a73a58eb..bd9834fd44 100644 --- a/examples/ibm-key-protect/README.md +++ b/examples/ibm-key-protect/README.md @@ -4,10 +4,6 @@ This example shows how to Create a Key protect instance, generate a key and inte This sample configuration will create the key protect instance, cos-bucket instance, root key, and integrate the key with a cos bucket after creating the bucket. - **Note:** - - `key_protect` attribute to associate a kms_key with a COS bucket has been renamed as `kms_key_crn` , hence it is recommended to all the new users to use `kms_key_crn`.Although the support for older attribute name `key_protect` will be continued for existing custom - To run, configure your IBM Cloud provider These types of resources and datasources are supported: @@ -21,6 +17,12 @@ Terraform 0.12. Pin module version to `~> v1.4.0`. Branch - `master`. Terraform 0.11. Pin module version to `~> v0.25.0`. Branch - `terraform_v0.11.x`. +## Deprecation Notice + + The resource `ibm_kp_key` is deprecated and replaced with `ibm_kms_key`. + + Please refer to [https://github.com/IBM-Cloud/terraform-provider-ibm/tree/master/examples/ibm-kms](examples/ibm-kms) for examples. + ## Usage To run this example you need to execute: diff --git a/go.mod b/go.mod index bcb8f5c6b4..70e172e82e 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/IBM/ibm-cos-sdk-go-config v1.2.0 github.com/IBM/ibm-hpcs-tke-sdk v0.0.0-20211109141421-a4b61b05f7d1 github.com/IBM/ibm-hpcs-uko-sdk v0.0.20-beta - github.com/IBM/keyprotect-go-client v0.10.0 + github.com/IBM/keyprotect-go-client v0.12.2 github.com/IBM/networking-go-sdk v0.42.2 github.com/IBM/project-go-sdk v0.0.10 github.com/IBM/platform-services-go-sdk v0.48.1 diff --git a/go.sum b/go.sum index 4586083320..8e159afc6c 100644 --- a/go.sum +++ b/go.sum @@ -149,8 +149,8 @@ github.com/IBM/ibm-hpcs-tke-sdk v0.0.0-20211109141421-a4b61b05f7d1/go.mod h1:M2J github.com/IBM/ibm-hpcs-uko-sdk v0.0.20-beta h1:P1fdIfKsD9xvJQ5MHIEztPS9yfNf9x+VDTamaYcmqcs= github.com/IBM/ibm-hpcs-uko-sdk v0.0.20-beta/go.mod h1:MLVNHMYoKsvovJZ4v1gQCpIYtRDHTtoIHK6XztDZGsU= github.com/IBM/keyprotect-go-client v0.5.1/go.mod h1:5TwDM/4FRJq1ZOlwQL1xFahLWQ3TveR88VmL1u3njyI= -github.com/IBM/keyprotect-go-client v0.10.0 h1:UdVOwJfyVNmL4O3Aw2eGluiEr5FpV5h8EaNVJKCtLvY= -github.com/IBM/keyprotect-go-client v0.10.0/go.mod h1:yr8h2noNgU8vcbs+vhqoXp3Lmv73PI0zAc6VMgFvWwM= +github.com/IBM/keyprotect-go-client v0.12.2 h1:Cjxcqin9Pl0xz3MnxdiVd4v/eIa79xL3hQpSbwOr/DQ= +github.com/IBM/keyprotect-go-client v0.12.2/go.mod h1:yr8h2noNgU8vcbs+vhqoXp3Lmv73PI0zAc6VMgFvWwM= github.com/IBM/networking-go-sdk v0.42.2 h1:caqjx4jyFHi10Vlf3skHvlL6K3YJRVstsmCBmvdyqkA= github.com/IBM/networking-go-sdk v0.42.2/go.mod h1:lTUZwtUkMANMnrLHFIgRhHrkBfwASY/Iho1fabaPHxo= github.com/IBM/platform-services-go-sdk v0.48.1 h1:TT+v28xaaFDolswhFLc+2ut6KXukoNyJGhlhuJupV7g= diff --git a/ibm/service/kms/data_source_ibm_kms_key.go b/ibm/service/kms/data_source_ibm_kms_key.go index cc2132dfd0..e5cf44c585 100644 --- a/ibm/service/kms/data_source_ibm_kms_key.go +++ b/ibm/service/kms/data_source_ibm_kms_key.go @@ -80,6 +80,10 @@ func DataSourceIBMKMSkey() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "description": { + Type: schema.TypeString, + Computed: true, + }, "standard_key": { Type: schema.TypeBool, Computed: true, @@ -232,7 +236,7 @@ func dataSourceIBMKMSKeyRead(d *schema.ResourceData, meta interface{}) error { } if len(totalKeys) == 0 { - return fmt.Errorf("[ERROR] No keys in instance %s", instanceID) + return fmt.Errorf("[ERROR] No keys in instance %s", instanceID) } var keyName string var matchKeys []kp.Key @@ -260,6 +264,7 @@ func dataSourceIBMKMSKeyRead(d *schema.ResourceData, meta interface{}) error { keyInstance["standard_key"] = key.Extractable keyInstance["aliases"] = key.Aliases keyInstance["key_ring_id"] = key.KeyRingID + keyInstance["description"] = key.Description policies, err := api.GetPolicies(context.Background(), key.ID) if err != nil { return fmt.Errorf("[ERROR] Failed to read policies: %s", err) @@ -286,6 +291,7 @@ func dataSourceIBMKMSKeyRead(d *schema.ResourceData, meta interface{}) error { keyInstance["name"] = key.Name keyInstance["crn"] = key.CRN keyInstance["standard_key"] = key.Extractable + keyInstance["description"] = key.Description keyInstance["aliases"] = key.Aliases keyInstance["key_ring_id"] = key.KeyRingID policies, err := api.GetPolicies(context.Background(), key.ID) @@ -314,6 +320,7 @@ func dataSourceIBMKMSKeyRead(d *schema.ResourceData, meta interface{}) error { keyInstance["name"] = key.Name keyInstance["crn"] = key.CRN keyInstance["standard_key"] = key.Extractable + keyInstance["description"] = key.Description keyInstance["aliases"] = key.Aliases keyInstance["key_ring_id"] = key.KeyRingID policies, err := api.GetPolicies(context.Background(), key.ID) diff --git a/ibm/service/kms/data_source_ibm_kms_key_test.go b/ibm/service/kms/data_source_ibm_kms_key_test.go index 3405cc5d42..b60097ff60 100644 --- a/ibm/service/kms/data_source_ibm_kms_key_test.go +++ b/ibm/service/kms/data_source_ibm_kms_key_test.go @@ -32,6 +32,26 @@ func TestAccIBMKMSKeyDataSource_basic(t *testing.T) { }) } +func TestAccIBMKMSKeyDataSource_description(t *testing.T) { + instanceName := fmt.Sprintf("kms_%d", acctest.RandIntRange(10, 100)) + keyName := fmt.Sprintf("key_%d", acctest.RandIntRange(10, 100)) + customDescription := "I am a custom description for the key" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMKmsKeyDataSourceConfigAndDescription(instanceName, keyName, customDescription), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("ibm_kms_key.test", "key_name", keyName), + resource.TestCheckResourceAttr("ibm_kms_key.test", "description", customDescription), + ), + }, + }, + }) +} + func TestAccIBMKMSKeyDataSource_Key(t *testing.T) { instanceName := fmt.Sprintf("kms_%d", acctest.RandIntRange(10, 100)) // bucketName := fmt.Sprintf("bucket", acctest.RandIntRange(10, 100)) @@ -153,6 +173,28 @@ func testAccCheckIBMKmsKeyDataSourceConfig(instanceName, keyName string) string `, instanceName, keyName) } +func testAccCheckIBMKmsKeyDataSourceConfigAndDescription(instanceName, keyName string, description string) string { + return fmt.Sprintf(` + resource "ibm_resource_instance" "kms_instance" { + name = "%s" + service = "kms" + plan = "tiered-pricing" + location = "us-south" + } + resource "ibm_kms_key" "test" { + instance_id = "${ibm_resource_instance.kms_instance.guid}" + key_name = "%s" + standard_key = true + description = "%s" + force_delete = true + } + data "ibm_kms_key" "test" { + instance_id = "${ibm_kms_key.test.instance_id}" + key_name = "${ibm_kms_key.test.key_name}" + } +`, instanceName, keyName, description) +} + func testAccCheckIBMKmsKeyDataSourceHpcsConfig(hpcsInstanceID string, KeyName string) string { return fmt.Sprintf(` resource "ibm_kms_key" "test" { diff --git a/ibm/service/kms/data_source_ibm_kms_keys.go b/ibm/service/kms/data_source_ibm_kms_keys.go index 6259252552..1d1fa69860 100644 --- a/ibm/service/kms/data_source_ibm_kms_keys.go +++ b/ibm/service/kms/data_source_ibm_kms_keys.go @@ -77,6 +77,10 @@ func DataSourceIBMKMSkeys() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "description": { + Type: schema.TypeString, + Computed: true, + }, "key_ring_id": { Type: schema.TypeString, Computed: true, @@ -199,8 +203,18 @@ func dataSourceIBMKMSKeysRead(d *schema.ResourceData, meta interface{}) error { keyInstance["name"] = key.Name keyInstance["crn"] = key.CRN keyInstance["standard_key"] = key.Extractable + keyInstance["description"] = key.Description keyInstance["aliases"] = key.Aliases keyInstance["key_ring_id"] = key.KeyRingID + policies, err := api.GetPolicies(context.Background(), key.ID) + if err != nil { + return fmt.Errorf("[ERROR] Failed to read policies: %s", err) + } + if len(policies) == 0 { + log.Printf("No Policy Configurations read\n") + } else { + keyInstance["policies"] = flex.FlattenKeyPolicies(policies) + } keyMap = append(keyMap, keyInstance) d.Set("keys", keyMap) @@ -215,6 +229,7 @@ func dataSourceIBMKMSKeysRead(d *schema.ResourceData, meta interface{}) error { keyInstance["name"] = key.Name keyInstance["crn"] = key.CRN keyInstance["standard_key"] = key.Extractable + keyInstance["description"] = key.Description keyInstance["aliases"] = key.Aliases keyInstance["key_ring_id"] = key.KeyRingID policies, err := api.GetPolicies(context.Background(), key.ID) @@ -278,6 +293,9 @@ func dataSourceIBMKMSKeysRead(d *schema.ResourceData, meta interface{}) error { } } } + if len(totalKeys) == 0 { + return fmt.Errorf("[ERROR] No keys in instance %s", instanceID) + } var keyName string var matchKeys []kp.Key if v, ok := d.GetOk("key_name"); ok { @@ -303,6 +321,7 @@ func dataSourceIBMKMSKeysRead(d *schema.ResourceData, meta interface{}) error { keyInstance["name"] = key.Name keyInstance["crn"] = key.CRN keyInstance["standard_key"] = key.Extractable + keyInstance["description"] = key.Description keyInstance["aliases"] = key.Aliases keyInstance["key_ring_id"] = key.KeyRingID keyMap = append(keyMap, keyInstance) diff --git a/ibm/service/kms/resource_ibm_kms_instance_policies_test.go b/ibm/service/kms/resource_ibm_kms_instance_policies_test.go index cce39ef24f..dc3d7e9e1d 100644 --- a/ibm/service/kms/resource_ibm_kms_instance_policies_test.go +++ b/ibm/service/kms/resource_ibm_kms_instance_policies_test.go @@ -165,7 +165,7 @@ func TestAccIBMKMSInstancePolicy_invalid_interval_check(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccCheckIBMKmsInstancePolicyStandardConfigCheck(instanceName, rotation_interval, dual_auth_delete), - ExpectError: regexp.MustCompile("must contain a valid int value should be in range(1, 12)"), + ExpectError: regexp.MustCompile(`.*must contain a valid int value should be in range\(1, 12\).*`), }, }, }) @@ -251,6 +251,7 @@ func testAccCheckIBMKmsInstancePolicyRotationCheck(instanceName string, rotation resource "ibm_kms_instance_policies" "test" { instance_id = ibm_resource_instance.kp_instance.guid rotation { + enabled = true interval_month = %d } } diff --git a/ibm/service/kms/resource_ibm_kms_key.go b/ibm/service/kms/resource_ibm_kms_key.go index 0d2c92749e..16a048c8b3 100644 --- a/ibm/service/kms/resource_ibm_kms_key.go +++ b/ibm/service/kms/resource_ibm_kms_key.go @@ -84,6 +84,12 @@ func ResourceIBMKmskey() *schema.Resource { ValidateFunc: validate.ValidateAllowedStringValues([]string{"public", "private"}), Description: "public or private", }, + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: "description of the key", + }, "standard_key": { Type: schema.TypeBool, Default: false, @@ -92,10 +98,11 @@ func ResourceIBMKmskey() *schema.Resource { Description: "Standard key type", }, "payload": { - Type: schema.TypeString, - Computed: true, - Optional: true, - ForceNew: true, + Type: schema.TypeString, + Sensitive: true, + Computed: true, + Optional: true, + ForceNew: true, }, "encrypted_nonce": { Type: schema.TypeString, @@ -176,7 +183,10 @@ func resourceIBMKmsKeyCreate(d *schema.ResourceData, meta interface{}) error { kpAPI.Config.KeyRing = d.Get("key_ring_id").(string) - key, err := kpAPI.CreateImportedKey(context.Background(), keyData.Name, keyData.Expiration, keyData.Payload, keyData.EncryptedNonce, keyData.IV, keyData.Extractable) + key, err := kpAPI.CreateKeyWithOptions(context.Background(), keyData.Name, keyData.Extractable, + kp.WithExpiration(keyData.Expiration), + kp.WithPayload(keyData.Payload, &keyData.EncryptedNonce, &keyData.IV, false), + kp.WithDescription(keyData.Description)) if err != nil { return fmt.Errorf("[ERROR] Error while creating key: %s", err) } @@ -283,6 +293,7 @@ func setKeyDetails(d *schema.ResourceData, meta interface{}, instanceID string, d.Set("key_id", key.ID) d.Set("standard_key", key.Extractable) d.Set("payload", d.Get("payload")) + d.Set("description", key.Description) d.Set("encrypted_nonce", key.EncryptedNonce) d.Set("iv_value", key.IV) d.Set("key_name", key.Name) @@ -369,6 +380,7 @@ func ExtractAndValidateKeyDataFromSchema(d *schema.ResourceData, meta interface{ Extractable: d.Get("standard_key").(bool), Expiration: expiration, Payload: d.Get("payload").(string), + Description: d.Get("description").(string), EncryptedNonce: d.Get("encrypted_nonce").(string), IV: d.Get("iv_value").(string), } diff --git a/ibm/service/kms/resource_ibm_kms_key_rings.go b/ibm/service/kms/resource_ibm_kms_key_rings.go index e152afbc3c..5f4bc85c70 100644 --- a/ibm/service/kms/resource_ibm_kms_key_rings.go +++ b/ibm/service/kms/resource_ibm_kms_key_rings.go @@ -16,6 +16,7 @@ import ( func ResourceIBMKmskeyRings() *schema.Resource { return &schema.Resource{ Create: resourceIBMKmsKeyRingCreate, + Update: resourceIBMKmsKeyRingUpdate, Delete: resourceIBMKmsKeyRingDelete, Read: resourceIBMKmsKeyRingRead, Importer: &schema.ResourceImporter{}, @@ -35,6 +36,13 @@ func ResourceIBMKmskeyRings() *schema.Resource { Description: "User defined unique ID for the key ring", ValidateFunc: validate.InvokeValidator("ibm_kms_key_rings", "key_ring_id"), }, + "force_delete": { + Type: schema.TypeBool, + Optional: true, + Description: "set to true to force delete this key ring. This allows key ring deletion as long as all keys inside have key state equals to 5 (destroyed). Keys are moved to the default key ring.", + ForceNew: false, + Default: false, + }, "endpoint_type": { Type: schema.TypeString, Optional: true, @@ -94,6 +102,15 @@ func resourceIBMKmsKeyRingCreate(d *schema.ResourceData, meta interface{}) error return resourceIBMKmsKeyRingRead(d, meta) } +func resourceIBMKmsKeyRingUpdate(d *schema.ResourceData, meta interface{}) error { + + if d.HasChange("force_delete") { + d.Set("force_delete", d.Get("force_delete").(bool)) + } + return resourceIBMKmsKeyRingRead(d, meta) + +} + func resourceIBMKmsKeyRingRead(d *schema.ResourceData, meta interface{}) error { id := strings.Split(d.Id(), ":keyRing:") if len(id) < 2 { @@ -131,10 +148,12 @@ func resourceIBMKmsKeyRingDelete(d *schema.ResourceData, meta interface{}) error if err != nil { return err } - err = kpAPI.DeleteKeyRing(context.Background(), id[0]) + force_delete := d.Get("force_delete").(bool) + + err = kpAPI.DeleteKeyRing(context.Background(), id[0], kp.WithForce(force_delete)) if err != nil { kpError := err.(*kp.Error) - if kpError.StatusCode == 404 || kpError.StatusCode == 409 { + if kpError.StatusCode == 404 { return nil } else { return fmt.Errorf(" failed to Destroy key ring with error: %s", err) diff --git a/ibm/service/kms/resource_ibm_kms_key_rings_test.go b/ibm/service/kms/resource_ibm_kms_key_rings_test.go index d871144c4d..bc6cf7f926 100644 --- a/ibm/service/kms/resource_ibm_kms_key_rings_test.go +++ b/ibm/service/kms/resource_ibm_kms_key_rings_test.go @@ -20,7 +20,7 @@ func TestAccIBMKMSResource_Key_Ring_Name(t *testing.T) { Providers: acc.TestAccProviders, Steps: []resource.TestStep{ { - Config: testAccCheckIBMKmsResourceKeyRingConfig(instanceName, keyRing), + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithResourceKMSKeyRing(keyRing, false)), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("ibm_kms_key_rings.test", "key_ring_id", keyRing), ), @@ -39,12 +39,16 @@ func TestAccIBMKMSResource_Key_Ring_Key(t *testing.T) { Providers: acc.TestAccProviders, Steps: []resource.TestStep{ { - Config: testAccCheckIBMKmsResourceKeyRingKeyConfig(instanceName, keyRing, keyName), + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithResourceKMSKeyRing(keyRing, false), WithResourceKMSKey(keyName, "ibm_kms_key_rings.test.key_ring_id")), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("ibm_kms_key.test", "key_name", keyName), resource.TestCheckResourceAttr("ibm_kms_key.test", "key_ring_id", keyRing), ), }, + // Cleanup: Change force_delete to true to allow for cleanup + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithResourceKMSKeyRing(keyRing, true), WithResourceKMSKey(keyName, "ibm_kms_key_rings.test.key_ring_id")), + }, }, }) } @@ -59,64 +63,197 @@ func TestAccIBMKMSResource_Key_Ring_Not_Exist(t *testing.T) { Providers: acc.TestAccProviders, Steps: []resource.TestStep{ { - Config: testAccCheckIBMKmsResourceKeyRingExistConfig(instanceName, keyName, keyRing), + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithResourceKMSKey(keyName, keyRing)), ExpectError: regexp.MustCompile("KEY_RING_NOT_FOUND_ERR:"), }, }, }) } -func testAccCheckIBMKmsResourceKeyRingConfig(instanceName, keyRing string) string { - return fmt.Sprintf(` - resource "ibm_resource_instance" "kms_instance" { - name = "%s" - service = "kms" - plan = "tiered-pricing" - location = "us-south" +func TestAccIBMKMSResource_Key_Ring_ForceDeleteFalse(t *testing.T) { + instanceName := fmt.Sprintf("tf_kms_%d", acctest.RandIntRange(10, 100)) + keyName := fmt.Sprintf("key_%d", acctest.RandIntRange(10, 100)) + keyRing := fmt.Sprintf("keyRing%d", acctest.RandIntRange(10, 100)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + // Create a Key Ring and check force_delete is false + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithResourceKMSKeyRing(keyRing, false), WithResourceKMSKey(keyName, "ibm_kms_key_rings.test.key_ring_id")), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("ibm_kms_key.test", "key_name", keyName), + resource.TestCheckResourceAttr("ibm_kms_key.test", "key_ring_id", keyRing), + resource.TestCheckResourceAttr("ibm_kms_key_rings.test", "force_delete", "false"), + ), + }, + // Developer note: We cannot move key rings to default key ring as we have not implemented that PATCH endpoint in terraform. Therefore we must depend on the force_delete flag to clean up test cases + // Attempt to delete the key ring and key + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithDataKMSKeys()), + ExpectError: regexp.MustCompile("KEY_RING_NOT_EMPTY_ERR:"), + }, + // Update key ring to force_delete for cleanup + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithResourceKMSKeyRing(keyRing, true)), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("ibm_kms_key_rings.test", "force_delete", "true"), + ), + }, + // Delete Key Ring + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithDataKMSKeys()), + ExpectError: regexp.MustCompile(`\[ERROR\] No keys in instance`), + }, + // Developer note: There is no support for listing keys under a certain key state so we cannot verify deleted key is now in default key ring + }, + }) +} + +func TestAccIBMKMSResource_Key_Ring_ForceDeleteTrue(t *testing.T) { + instanceName := fmt.Sprintf("tf_kms_%d", acctest.RandIntRange(10, 100)) + keyName := fmt.Sprintf("key_%d", acctest.RandIntRange(10, 100)) + keyRing := fmt.Sprintf("keyRing%d", acctest.RandIntRange(10, 100)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + // Create a Key Ring and check force_delete is true + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithResourceKMSKeyRing(keyRing, true), WithResourceKMSKey(keyName, "ibm_kms_key_rings.test.key_ring_id")), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("ibm_kms_key.test", "key_name", keyName), + resource.TestCheckResourceAttr("ibm_kms_key.test", "key_ring_id", keyRing), + resource.TestCheckResourceAttr("ibm_kms_key_rings.test", "force_delete", "true"), + ), + }, + // Attempt to delete the key ring and key + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName)), + Check: resource.ComposeTestCheckFunc(), + }, + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithDataKMSKeys()), + ExpectError: regexp.MustCompile(`\[ERROR\] No keys in instance`), + }, + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithDataKMSKeyRings()), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("data.ibm_kms_key_rings.test_key_rings", "key_rings.0.id", "default"), + ), + }, + }, + }) +} + +func TestAccIBMKMSResource_Key_Ring_ForceDeleteTrueContainsActiveKeys(t *testing.T) { + instanceName := fmt.Sprintf("tf_kms_%d", acctest.RandIntRange(10, 100)) + keyName := fmt.Sprintf("key_%d", acctest.RandIntRange(10, 100)) + keyRing := fmt.Sprintf("keyRing%d", acctest.RandIntRange(10, 100)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + // Create a Key Ring and check force_delete is true + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithResourceKMSKeyRing(keyRing, true), WithResourceKMSKey(keyName, "ibm_kms_key_rings.test.key_ring_id")), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("ibm_kms_key.test", "key_name", keyName), + resource.TestCheckResourceAttr("ibm_kms_key.test", "key_ring_id", keyRing), + resource.TestCheckResourceAttr("ibm_kms_key_rings.test", "force_delete", "true"), + ), + }, + // Attempt to delete the key ring while active key exists + // We must specify key ring ID and not reference here as the resource is removed + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithResourceKMSKey(keyName, keyRing)), + ExpectError: regexp.MustCompile("KEY_RING_KEYS_NOT_DELETED_ERR:"), + }, + // Attempt to delete keys + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithResourceKMSKeyRing(keyRing, true)), + }, + // Attempt to delete key ring and check no more keys + { + Config: buildResourceSet(WithResourceKMSInstance(instanceName), WithDataKMSKeys()), + ExpectError: regexp.MustCompile(`\[ERROR\] No keys in instance`), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("data.ibm_kms_key_rings.test_key_rings", "key_rings.0.id", "default"), + ), + }, + }, + }) +} + +type CreateResourceOption func(resourceText *string) + +func buildResourceSet(options ...CreateResourceOption) string { + var fullResourceSet *string + emptyString := "" + fullResourceSet = &emptyString + for _, opt := range options { + opt(fullResourceSet) + *fullResourceSet += "\n" } - resource "ibm_kms_key_rings" "test" { - instance_id = ibm_resource_instance.kms_instance.guid - key_ring_id = "%s" + return *fullResourceSet +} + +func WithResourceKMSInstance(instanceName string) CreateResourceOption { + return func(resources *string) { + *resources += fmt.Sprintf(` + resource "ibm_resource_instance" "kms_instance" { + name = "%s" + service = "kms" + plan = "tiered-pricing" + location = "us-south" + }`, instanceName) } -`, instanceName, keyRing) } -func testAccCheckIBMKmsResourceKeyRingKeyConfig(instanceName, keyRing, keyName string) string { - return fmt.Sprintf(` - resource "ibm_resource_instance" "kms_instance" { - name = "%s" - service = "kms" - plan = "tiered-pricing" - location = "us-south" +func WithResourceKMSKeyRing(keyRing string, forceDelete bool) CreateResourceOption { + return func(resources *string) { + *resources += fmt.Sprintf(` + resource "ibm_kms_key_rings" "test" { + instance_id = ibm_resource_instance.kms_instance.guid + key_ring_id = "%s" + force_delete = %t + }`, keyRing, forceDelete) } - resource "ibm_kms_key_rings" "key_ring" { - instance_id = ibm_resource_instance.kms_instance.guid - key_ring_id = "%s" +} + +func WithResourceKMSKey(keyName string, keyRing string) CreateResourceOption { + if keyRing != "ibm_kms_key_rings.test.key_ring_id" { + keyRing = `"` + keyRing + `"` } - resource "ibm_kms_key" "test" { - instance_id = ibm_resource_instance.kms_instance.guid - key_name = "%s" - key_ring_id = ibm_kms_key_rings.key_ring.key_ring_id - standard_key = true - force_delete = true + return func(resources *string) { + *resources += fmt.Sprintf(` + resource "ibm_kms_key" "test" { + instance_id = ibm_resource_instance.kms_instance.guid + key_name = "%s" + key_ring_id = %s + standard_key = true + force_delete = true + }`, keyName, keyRing) } -`, instanceName, keyRing, keyName) } -func testAccCheckIBMKmsResourceKeyRingExistConfig(instanceName, keyName, keyRing string) string { - return fmt.Sprintf(` - resource "ibm_resource_instance" "kms_instance" { - name = "%s" - service = "kms" - plan = "tiered-pricing" - location = "us-south" +func WithDataKMSKeys() CreateResourceOption { + return func(resources *string) { + *resources += ` + data "ibm_kms_keys" "test_keys" { + instance_id = "${ibm_resource_instance.kms_instance.guid}" + }` } - resource "ibm_kms_key" "test" { - instance_id = ibm_resource_instance.kms_instance.guid - key_name = "%s" - key_ring_id = "%s" - standard_key = true - force_delete = true +} + +func WithDataKMSKeyRings() CreateResourceOption { + return func(resources *string) { + *resources += ` + data "ibm_kms_key_rings" "test_key_rings" { + instance_id = "${ibm_resource_instance.kms_instance.guid}" + }` } -`, instanceName, keyRing, keyName) } diff --git a/ibm/service/kms/resource_ibm_kms_key_test.go b/ibm/service/kms/resource_ibm_kms_key_test.go index 1b3d5cb20a..8775c1b800 100644 --- a/ibm/service/kms/resource_ibm_kms_key_test.go +++ b/ibm/service/kms/resource_ibm_kms_key_test.go @@ -24,6 +24,7 @@ func TestAccIBMKMSResource_basic(t *testing.T) { payload := "LqMWNtSi3Snr4gFNO0PsFFLFRNs57mSXCQE7O2oE+g0=" resourceName := "ibm_kms_key" standard_key := true + customDescription := "i am a custom description" resource.Test(t, resource.TestCase{ PreCheck: func() { acc.TestAccPreCheck(t) }, @@ -63,6 +64,13 @@ func TestAccIBMKMSResource_basic(t *testing.T) { resource.TestCheckResourceAttr("ibm_kms_key.test", "key_name", keyName), ), }, + { + // Test Description in Root Key + Config: testAccCheckIBMKmsResourceConfigDescription(instanceName, resourceName, keyName, !standard_key, customDescription), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("ibm_kms_key.test", "description", customDescription), + ), + }, }, }) } @@ -163,6 +171,24 @@ func testAccCheckIBMKmsResourceConfig(instanceName, resource, KeyName string, st `, instanceName, resource, KeyName, standard_key) } +func testAccCheckIBMKmsResourceConfigDescription(instanceName, resource, KeyName string, standard_key bool, description string) string { + return fmt.Sprintf(` + resource "ibm_resource_instance" "kms_instance" { + name = "%s" + service = "kms" + plan = "tiered-pricing" + location = "us-south" + } + resource "%s" "test" { + instance_id = "${ibm_resource_instance.kms_instance.guid}" + key_name = "%s" + standard_key = %t + description = "%s" + force_delete = true + } +`, instanceName, resource, KeyName, standard_key, description) +} + func testAccCheckIBMKmsResourceImportConfig(instanceName, resource, KeyName string, standard_key bool, payload string) string { return fmt.Sprintf(` resource "ibm_resource_instance" "kms_instance" { diff --git a/ibm/service/kms/resource_ibm_kms_key_with_policy_overrides.go b/ibm/service/kms/resource_ibm_kms_key_with_policy_overrides.go index 369190caea..5907a92545 100644 --- a/ibm/service/kms/resource_ibm_kms_key_with_policy_overrides.go +++ b/ibm/service/kms/resource_ibm_kms_key_with_policy_overrides.go @@ -35,6 +35,12 @@ func ResourceIBMKmsKeyWithPolicyOverrides() *schema.Resource { Description: "Key protect or HPCS instance GUID or CRN", DiffSuppressFunc: suppressKMSInstanceIDDiff, }, + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: "description of the key", + }, "key_ring_id": { Type: schema.TypeString, Optional: true, @@ -74,10 +80,11 @@ func ResourceIBMKmsKeyWithPolicyOverrides() *schema.Resource { Description: "Standard key type", }, "payload": { - Type: schema.TypeString, - Computed: true, - Optional: true, - ForceNew: true, + Type: schema.TypeString, + Sensitive: true, + Computed: true, + Optional: true, + ForceNew: true, }, "encrypted_nonce": { Type: schema.TypeString, diff --git a/website/docs/r/kms_key.html.markdown b/website/docs/r/kms_key.html.markdown index a1a497b41c..bb063fcdb4 100644 --- a/website/docs/r/kms_key.html.markdown +++ b/website/docs/r/kms_key.html.markdown @@ -100,7 +100,7 @@ Review the argument references that you can specify for your resource. - `endpoint_type` - (Optional, String) The type of the public or private endpoint to be used for creating keys. - `encrypted_nonce` - (Optional, Forces new resource, String) The encrypted nonce value that verifies your request to import a key to Key Protect. This value must be encrypted by using the key that you want to import to the service. To retrieve a nonce, use the `ibmcloud kp import-token get` command. Then, encrypt the value by running `ibmcloud kp import-token encrypt-nonce`. Only for imported root key. -- `expiration_date` - (Optional, Forces new resource, String) Expiry date of the key material. The date format follows with RFC 3339. You can set an expiration date on any key on its creation. A key moves into the deactivated state within one hour past its expiration date, if one is assigned. If you create a key without specifying an expiration date, the key does not expire. For example, `2018-12-01T23:20:50.52Z`. +- `expiration_date` - (Optional, Forces new resource, String) Expiry date of the key material. The date format follows with RFC 3339. You can set an expiration date on any key on its creation. A key moves into the deactivated state within one hour past its expiration date, if one is assigned. If you create a key without specifying an expiration date, the key does not expire. For example, `2018-12-01T23:20:50Z`. - `force_delete` - (Optional, Bool) If set to **true**, Key Protect forces the deletion of a root or standard key, even if this key is still in use, such as to protect an IBM Cloud Object Storage bucket. Note that the key cannot be deleted if the protected cloud resource is set up with a retention policy. Successful deletion includes the removal of any registrations that are associated with the key. Default value is **false**. **Note** Before Terraform destroy if `force_delete` flag is introduced after provisioning keys, a Terraform apply must be done before Terraform destroy for `force_delete` flag to take effect. - `instance_id` - (Required, Forces new resource, String) The HPCS or key-protect instance ID. - `iv_value` - (Optional, Forces new resource, String) Used with import tokens. The initialization vector (IV) that is generated when you encrypt a nonce. The IV value is required to decrypt the encrypted nonce value that you provide when you make a key import request to the service. To generate an IV, encrypt the nonce by running `ibmcloud kp import-token encrypt-nonce`. Only for imported root key. diff --git a/website/docs/r/kms_key_rings.html.markdown b/website/docs/r/kms_key_rings.html.markdown index c79b7b5679..a7cb8ccb9a 100644 --- a/website/docs/r/kms_key_rings.html.markdown +++ b/website/docs/r/kms_key_rings.html.markdown @@ -33,6 +33,16 @@ resource "ibm_kms_key" "key" { } ``` +Sample example of deleting a key ring where all keys inside have key state equals to 5 (destroyed). Keys are moved to the default key ring. + +``` +resource "ibm_kms_key_rings" "key_ring" { + instance_id = ibm_resource_instance.kms_instance.guid + key_ring_id = "key-ring-id" + force_delete = true +} +``` + ## Argument reference Review the argument references that you can specify for your resource. diff --git a/website/docs/r/kms_key_with_policy_overrides.html.markdown b/website/docs/r/kms_key_with_policy_overrides.html.markdown index 3d65c34651..8fd7964b46 100644 --- a/website/docs/r/kms_key_with_policy_overrides.html.markdown +++ b/website/docs/r/kms_key_with_policy_overrides.html.markdown @@ -102,7 +102,7 @@ Review the argument references that you can specify for your resource. - `endpoint_type` - (Optional, Forces new resource, String) The type of the public or private endpoint to be used for creating keys. - `encrypted_nonce` - (Optional, Forces new resource, String) The encrypted nonce value that verifies your request to import a key to Key Protect. This value must be encrypted by using the key that you want to import to the service. To retrieve a nonce, use the `ibmcloud kp import-token get` command. Then, encrypt the value by running `ibmcloud kp import-token encrypt-nonce`. Only for imported root key. -- `expiration_date` - (Optional, Forces new resource, String) Expiry date of the key material. The date format follows with RFC 3339. You can set an expiration date on any key on its creation. A key moves into the deactivated state within one hour past its expiration date, if one is assigned. If you create a key without specifying an expiration date, the key does not expire. For example, `2018-12-01T23:20:50.52Z`. +- `expiration_date` - (Optional, Forces new resource, String) Expiry date of the key material. The date format follows with RFC 3339. You can set an expiration date on any key on its creation. A key moves into the deactivated state within one hour past its expiration date, if one is assigned. If you create a key without specifying an expiration date, the key does not expire. For example, `2018-12-01T23:20:50Z`. - `force_delete` - (Optional, Bool) If set to **true**, Key Protect forces the deletion of a root or standard key, even if this key is still in use, such as to protect an IBM Cloud Object Storage bucket. Note that the key cannot be deleted if the protected cloud resource is set up with a retention policy. Successful deletion includes the removal of any registrations that are associated with the key. Default value is **false**. **Note** Before Terraform destroy if `force_delete` flag is introduced after provisioning keys, a Terraform apply must be done before Terraform destroy for `force_delete` flag to take effect. - `instance_id` - (Required, Forces new resource, String) The HPCS or key-protect instance ID. - `iv_value` - (Optional, Forces new resource, String) Used with import tokens. The initialization vector (IV) that is generated when you encrypt a nonce. The IV value is required to decrypt the encrypted nonce value that you provide when you make a key import request to the service. To generate an IV, encrypt the nonce by running `ibmcloud kp import-token encrypt-nonce`. Only for imported root key. diff --git a/website/docs/r/kp_key.html.markdown b/website/docs/r/kp_key.html.markdown index f23343cd11..9297e25f19 100644 --- a/website/docs/r/kp_key.html.markdown +++ b/website/docs/r/kp_key.html.markdown @@ -11,9 +11,8 @@ description: |- Create, or delete a Key Protect standard or root key. To use the `ibm_kp_key` resource, the region parameter in the `provider.tf` file must be set to the same region that your Key Protect service instance. If region parameter is not specified, `us-south` is used as default. If the region in the `provider.tf` file is different from the Key Protect instance, the instance cannot be retrieved by Terraform and the Terraform action fails. -**Note** - -The `ibm_kp_key` resource will be deprecated shortly, as a replacement, you can use `ibm_kms_key` resource. +~>**Deprecated:** +The `ibm_kp_key` resource is deprecated, as a replacement, you can use `ibm_kms_key` resource. ## Example usage From a2c05168291be5bf8e0643295cd76085702f1c3b Mon Sep 17 00:00:00 2001 From: Ranganath Achari Date: Thu, 14 Sep 2023 19:59:58 +0530 Subject: [PATCH 5/5] Retry cloud connection create/update when vpc is unavailable (#4766) * Retry cloud connection create/update when vpc is unavailable * review comment code changes * review comment code changes * review comment code changes * review comment code changes --- go.mod | 2 +- go.sum | 2 + .../power/resource_ibm_pi_cloud_connection.go | 43 +++++++++++++++++-- 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 70e172e82e..d60f2a3b44 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.18 require ( github.com/IBM-Cloud/bluemix-go v0.0.0-20230601050310-eecebfbff63e github.com/IBM-Cloud/container-services-go-sdk v0.0.0-20230118060037-101bda076037 - github.com/IBM-Cloud/power-go-client v1.2.2 + github.com/IBM-Cloud/power-go-client v1.2.4 github.com/IBM/apigateway-go-sdk v0.0.0-20210714141226-a5d5d49caaca github.com/IBM/appconfiguration-go-admin-sdk v0.3.0 github.com/IBM/appid-management-go-sdk v0.0.0-20210908164609-dd0e0eaf732f diff --git a/go.sum b/go.sum index 8e159afc6c..5f051d8e9c 100644 --- a/go.sum +++ b/go.sum @@ -105,6 +105,8 @@ github.com/IBM-Cloud/container-services-go-sdk v0.0.0-20230118060037-101bda07603 github.com/IBM-Cloud/ibm-cloud-cli-sdk v0.5.3/go.mod h1:RiUvKuHKTBmBApDMUQzBL14pQUGKcx/IioKQPIcRQjs= github.com/IBM-Cloud/power-go-client v1.2.2 h1:VNlzizoG2x06c3nL1ZBILF701QcvXcu6nEH3hmEKCkw= github.com/IBM-Cloud/power-go-client v1.2.2/go.mod h1:Qfx0fNi+9hms+xu9Z6Euhu9088ByW6C/TCMLECTRWNE= +github.com/IBM-Cloud/power-go-client v1.2.4 h1:4y/ubiOXpMg3xyBryfgfsa8hae/9Dn5WLdvphoxvgsQ= +github.com/IBM-Cloud/power-go-client v1.2.4/go.mod h1:0YVWoIQN5I5IvyhO/m4yxgPJqCh9QjceN2FNlVpYlOQ= github.com/IBM-Cloud/softlayer-go v1.0.5-tf h1:koUAyF9b6X78lLLruGYPSOmrfY2YcGYKOj/Ug9nbKNw= github.com/IBM-Cloud/softlayer-go v1.0.5-tf/go.mod h1:6HepcfAXROz0Rf63krk5hPZyHT6qyx2MNvYyHof7ik4= github.com/IBM/apigateway-go-sdk v0.0.0-20210714141226-a5d5d49caaca h1:crniVcf+YcmgF03NmmfonXwSQ73oJF+IohFYBwknMxs= diff --git a/ibm/service/power/resource_ibm_pi_cloud_connection.go b/ibm/service/power/resource_ibm_pi_cloud_connection.go index eecf623625..a8a1771891 100644 --- a/ibm/service/power/resource_ibm_pi_cloud_connection.go +++ b/ibm/service/power/resource_ibm_pi_cloud_connection.go @@ -7,6 +7,7 @@ import ( "context" "fmt" "log" + "regexp" "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -22,6 +23,15 @@ import ( "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" ) +var ( + vpcUnavailable = regexp.MustCompile("pcloudCloudconnectionsPostServiceUnavailable|pcloudCloudconnectionsPutServiceUnavailable") +) + +const ( + vpcRetryCount = 2 + vpcRetryDuration = time.Minute +) + func ResourceIBMPICloudConnection() *schema.Resource { return &schema.Resource{ CreateContext: resourceIBMPICloudConnectionCreate, @@ -226,8 +236,16 @@ func resourceIBMPICloudConnectionCreate(ctx context.Context, d *schema.ResourceD client := st.NewIBMPICloudConnectionClient(ctx, sess, cloudInstanceID) cloudConnection, cloudConnectionJob, err := client.Create(body) if err != nil { - log.Printf("[DEBUG] create cloud connection failed %v", err) - return diag.FromErr(err) + if vpcUnavailable.Match([]byte(err.Error())) { + err = retryCloudConnectionsVPC(func() (err error) { + cloudConnection, cloudConnectionJob, err = client.Create(body) + return + }, "create", err) + } + if err != nil { + log.Printf("[DEBUG] create cloud connection failed %v", err) + return diag.FromErr(err) + } } if cloudConnection != nil { @@ -333,7 +351,16 @@ func resourceIBMPICloudConnectionUpdate(ctx context.Context, d *schema.ResourceD _, cloudConnectionJob, err := client.Update(cloudConnectionID, body) if err != nil { - return diag.FromErr(err) + if vpcUnavailable.Match([]byte(err.Error())) { + err = retryCloudConnectionsVPC(func() (err error) { + _, cloudConnectionJob, err = client.Update(cloudConnectionID, body) + return + }, "update", err) + } + if err != nil { + log.Printf("[DEBUG] update cloud connection failed %v", err) + return diag.FromErr(err) + } } if cloudConnectionJob != nil { _, err = waitForIBMPIJobCompleted(ctx, jobClient, *cloudConnectionJob.ID, d.Timeout(schema.TimeoutCreate)) @@ -497,3 +524,13 @@ func resourceIBMPICloudConnectionDelete(ctx context.Context, d *schema.ResourceD d.SetId("") return nil } + +func retryCloudConnectionsVPC(ccVPCRetry func() error, operation string, errMsg error) error { + for count := 0; count < vpcRetryCount && errMsg != nil; count++ { + log.Printf("[DEBUG] unable to get vpc details for cloud connection: %v", errMsg) + time.Sleep(vpcRetryDuration) + log.Printf("[DEBUG] retrying cloud connection %s, retry #%v", operation, count+1) + errMsg = ccVPCRetry() + } + return errMsg +}