From 75778f9aa7ae7dca615b749d768bfe60614ed5fe Mon Sep 17 00:00:00 2001 From: danischm Date: Mon, 30 Oct 2023 15:38:51 +0100 Subject: [PATCH] Initial commit --- .github/dependabot.yml | 12 + .github/workflows/release.yml | 42 ++ .github/workflows/test.yml | 66 +++ .gitignore | 35 ++ .goreleaser.yml | 60 ++ .vscode/launch.json | 16 + CHANGELOG.md | 3 + CODE_OF_CONDUCT.md | 76 +++ CONTRIBUTING.md | 76 +++ GNUmakefile | 6 + LICENSE | 373 ++++++++++++ README.md | 68 +++ SECURITY.md | 38 ++ docs/data-sources/area.md | 31 + docs/data-sources/building.md | 35 ++ docs/data-sources/credentials_cli.md | 33 ++ docs/data-sources/credentials_https_read.md | 33 ++ docs/data-sources/credentials_https_write.md | 33 ++ docs/data-sources/credentials_snmpv2_read.md | 31 + docs/data-sources/credentials_snmpv2_write.md | 31 + docs/data-sources/credentials_snmpv3.md | 36 ++ docs/data-sources/floor.md | 35 ++ docs/data-sources/ip_pool.md | 36 ++ docs/data-sources/ip_pool_reservation.md | 50 ++ docs/guides/changelog.md | 13 + docs/index.md | 38 ++ docs/resources/area.md | 43 ++ docs/resources/building.md | 48 ++ docs/resources/credentials_cli.md | 46 ++ docs/resources/credentials_https_read.md | 48 ++ docs/resources/credentials_https_write.md | 48 ++ docs/resources/credentials_snmpv2_read.md | 40 ++ docs/resources/credentials_snmpv2_write.md | 40 ++ docs/resources/credentials_snmpv3.md | 56 ++ docs/resources/floor.md | 49 ++ docs/resources/ip_pool.md | 57 ++ docs/resources/ip_pool_reservation.md | 73 +++ examples/README.md | 9 + .../catalystcenter_area/data-source.tf | 3 + .../catalystcenter_building/data-source.tf | 3 + .../data-source.tf | 3 + .../data-source.tf | 3 + .../data-source.tf | 3 + .../data-source.tf | 3 + .../data-source.tf | 3 + .../data-source.tf | 3 + .../catalystcenter_floor/data-source.tf | 3 + .../catalystcenter_ip_pool/data-source.tf | 3 + .../data-source.tf | 3 + examples/provider/provider.tf | 5 + .../resources/catalystcenter_area/import.sh | 1 + .../resources/catalystcenter_area/resource.tf | 4 + .../catalystcenter_building/import.sh | 1 + .../catalystcenter_building/resource.tf | 8 + .../catalystcenter_credentials_cli/import.sh | 1 + .../resource.tf | 5 + .../import.sh | 1 + .../resource.tf | 6 + .../import.sh | 1 + .../resource.tf | 6 + .../import.sh | 1 + .../resource.tf | 4 + .../import.sh | 1 + .../resource.tf | 4 + .../import.sh | 1 + .../resource.tf | 9 + .../resources/catalystcenter_floor/import.sh | 1 + .../catalystcenter_floor/resource.tf | 8 + .../catalystcenter_ip_pool/import.sh | 1 + .../catalystcenter_ip_pool/resource.tf | 9 + .../import.sh | 1 + .../resource.tf | 13 + gen/definitions/area.yaml | 24 + gen/definitions/building.yaml | 53 ++ gen/definitions/credentials_cli.yaml | 36 ++ gen/definitions/credentials_https_read.yaml | 37 ++ gen/definitions/credentials_https_write.yaml | 37 ++ gen/definitions/credentials_snmpv2_read.yaml | 24 + gen/definitions/credentials_snmpv2_write.yaml | 24 + gen/definitions/credentials_snmpv3.yaml | 59 ++ gen/definitions/floor.yaml | 64 ++ gen/definitions/ip_pool.yaml | 59 ++ gen/definitions/ip_pool_reservation.yaml | 152 +++++ gen/doc_category.go | 104 ++++ gen/generator.go | 445 ++++++++++++++ gen/schema/schema.yaml | 59 ++ gen/templates/changelog.md.tmpl | 10 + gen/templates/data-source.tf | 8 + gen/templates/data_source.go | 233 ++++++++ gen/templates/data_source_test.go | 229 +++++++ gen/templates/import.sh | 1 + gen/templates/model.go | 549 +++++++++++++++++ gen/templates/provider.go | 266 +++++++++ gen/templates/resource.go | 557 ++++++++++++++++++ gen/templates/resource.tf | 43 ++ gen/templates/resource_test.go | 318 ++++++++++ go.mod | 82 +++ go.sum | 284 +++++++++ .../data_source_catalystcenter_area.go | 116 ++++ .../data_source_catalystcenter_area_test.go | 67 +++ .../data_source_catalystcenter_building.go | 132 +++++ ...ata_source_catalystcenter_building_test.go | 75 +++ ...a_source_catalystcenter_credentials_cli.go | 124 ++++ ...rce_catalystcenter_credentials_cli_test.go | 69 +++ ...e_catalystcenter_credentials_https_read.go | 124 ++++ ...alystcenter_credentials_https_read_test.go | 71 +++ ..._catalystcenter_credentials_https_write.go | 124 ++++ ...lystcenter_credentials_https_write_test.go | 71 +++ ..._catalystcenter_credentials_snmpv2_read.go | 116 ++++ ...lystcenter_credentials_snmpv2_read_test.go | 67 +++ ...catalystcenter_credentials_snmpv2_write.go | 116 ++++ ...ystcenter_credentials_snmpv2_write_test.go | 67 +++ ...ource_catalystcenter_credentials_snmpv3.go | 136 +++++ ..._catalystcenter_credentials_snmpv3_test.go | 76 +++ .../data_source_catalystcenter_floor.go | 132 +++++ .../data_source_catalystcenter_floor_test.go | 86 +++ .../data_source_catalystcenter_ip_pool.go | 139 +++++ ...urce_catalystcenter_ip_pool_reservation.go | 197 +++++++ ...catalystcenter_ip_pool_reservation_test.go | 91 +++ ...data_source_catalystcenter_ip_pool_test.go | 76 +++ .../provider/helpers/description_builder.go | 60 ++ internal/provider/helpers/utils.go | 41 ++ .../provider/model_catalystcenter_area.go | 84 +++ .../provider/model_catalystcenter_building.go | 140 +++++ .../model_catalystcenter_credentials_cli.go | 104 ++++ ...l_catalystcenter_credentials_https_read.go | 114 ++++ ..._catalystcenter_credentials_https_write.go | 114 ++++ ..._catalystcenter_credentials_snmpv2_read.go | 86 +++ ...catalystcenter_credentials_snmpv2_write.go | 86 +++ ...model_catalystcenter_credentials_snmpv3.go | 146 +++++ .../provider/model_catalystcenter_floor.go | 130 ++++ .../provider/model_catalystcenter_ip_pool.go | 151 +++++ ...odel_catalystcenter_ip_pool_reservation.go | 164 ++++++ internal/provider/provider.go | 281 +++++++++ internal/provider/provider_test.go | 49 ++ .../provider/resource_catalystcenter_area.go | 226 +++++++ .../resource_catalystcenter_area_test.go | 83 +++ .../resource_catalystcenter_building.go | 242 ++++++++ .../resource_catalystcenter_building_test.go | 96 +++ ...resource_catalystcenter_credentials_cli.go | 243 ++++++++ ...rce_catalystcenter_credentials_cli_test.go | 87 +++ ...e_catalystcenter_credentials_https_read.go | 246 ++++++++ ...alystcenter_credentials_https_read_test.go | 83 +++ ..._catalystcenter_credentials_https_write.go | 246 ++++++++ ...lystcenter_credentials_https_write_test.go | 83 +++ ..._catalystcenter_credentials_snmpv2_read.go | 235 ++++++++ ...lystcenter_credentials_snmpv2_read_test.go | 84 +++ ...catalystcenter_credentials_snmpv2_write.go | 235 ++++++++ ...ystcenter_credentials_snmpv2_write_test.go | 84 +++ ...ource_catalystcenter_credentials_snmpv3.go | 266 +++++++++ ..._catalystcenter_credentials_snmpv3_test.go | 88 +++ .../provider/resource_catalystcenter_floor.go | 247 ++++++++ .../resource_catalystcenter_floor_test.go | 107 ++++ .../resource_catalystcenter_ip_pool.go | 270 +++++++++ ...urce_catalystcenter_ip_pool_reservation.go | 327 ++++++++++ ...catalystcenter_ip_pool_reservation_test.go | 108 ++++ .../resource_catalystcenter_ip_pool_test.go | 93 +++ main.go | 66 +++ templates/guides/changelog.md.tmpl | 13 + templates/index.md.tmpl | 23 + terraform-registry-manifest.json | 6 + tools/tools.go | 28 + 162 files changed, 13682 insertions(+) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 .goreleaser.yml create mode 100644 .vscode/launch.json create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 GNUmakefile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 docs/data-sources/area.md create mode 100644 docs/data-sources/building.md create mode 100644 docs/data-sources/credentials_cli.md create mode 100644 docs/data-sources/credentials_https_read.md create mode 100644 docs/data-sources/credentials_https_write.md create mode 100644 docs/data-sources/credentials_snmpv2_read.md create mode 100644 docs/data-sources/credentials_snmpv2_write.md create mode 100644 docs/data-sources/credentials_snmpv3.md create mode 100644 docs/data-sources/floor.md create mode 100644 docs/data-sources/ip_pool.md create mode 100644 docs/data-sources/ip_pool_reservation.md create mode 100644 docs/guides/changelog.md create mode 100644 docs/index.md create mode 100644 docs/resources/area.md create mode 100644 docs/resources/building.md create mode 100644 docs/resources/credentials_cli.md create mode 100644 docs/resources/credentials_https_read.md create mode 100644 docs/resources/credentials_https_write.md create mode 100644 docs/resources/credentials_snmpv2_read.md create mode 100644 docs/resources/credentials_snmpv2_write.md create mode 100644 docs/resources/credentials_snmpv3.md create mode 100644 docs/resources/floor.md create mode 100644 docs/resources/ip_pool.md create mode 100644 docs/resources/ip_pool_reservation.md create mode 100644 examples/README.md create mode 100644 examples/data-sources/catalystcenter_area/data-source.tf create mode 100644 examples/data-sources/catalystcenter_building/data-source.tf create mode 100644 examples/data-sources/catalystcenter_credentials_cli/data-source.tf create mode 100644 examples/data-sources/catalystcenter_credentials_https_read/data-source.tf create mode 100644 examples/data-sources/catalystcenter_credentials_https_write/data-source.tf create mode 100644 examples/data-sources/catalystcenter_credentials_snmpv2_read/data-source.tf create mode 100644 examples/data-sources/catalystcenter_credentials_snmpv2_write/data-source.tf create mode 100644 examples/data-sources/catalystcenter_credentials_snmpv3/data-source.tf create mode 100644 examples/data-sources/catalystcenter_floor/data-source.tf create mode 100644 examples/data-sources/catalystcenter_ip_pool/data-source.tf create mode 100644 examples/data-sources/catalystcenter_ip_pool_reservation/data-source.tf create mode 100644 examples/provider/provider.tf create mode 100644 examples/resources/catalystcenter_area/import.sh create mode 100644 examples/resources/catalystcenter_area/resource.tf create mode 100644 examples/resources/catalystcenter_building/import.sh create mode 100644 examples/resources/catalystcenter_building/resource.tf create mode 100644 examples/resources/catalystcenter_credentials_cli/import.sh create mode 100644 examples/resources/catalystcenter_credentials_cli/resource.tf create mode 100644 examples/resources/catalystcenter_credentials_https_read/import.sh create mode 100644 examples/resources/catalystcenter_credentials_https_read/resource.tf create mode 100644 examples/resources/catalystcenter_credentials_https_write/import.sh create mode 100644 examples/resources/catalystcenter_credentials_https_write/resource.tf create mode 100644 examples/resources/catalystcenter_credentials_snmpv2_read/import.sh create mode 100644 examples/resources/catalystcenter_credentials_snmpv2_read/resource.tf create mode 100644 examples/resources/catalystcenter_credentials_snmpv2_write/import.sh create mode 100644 examples/resources/catalystcenter_credentials_snmpv2_write/resource.tf create mode 100644 examples/resources/catalystcenter_credentials_snmpv3/import.sh create mode 100644 examples/resources/catalystcenter_credentials_snmpv3/resource.tf create mode 100644 examples/resources/catalystcenter_floor/import.sh create mode 100644 examples/resources/catalystcenter_floor/resource.tf create mode 100644 examples/resources/catalystcenter_ip_pool/import.sh create mode 100644 examples/resources/catalystcenter_ip_pool/resource.tf create mode 100644 examples/resources/catalystcenter_ip_pool_reservation/import.sh create mode 100644 examples/resources/catalystcenter_ip_pool_reservation/resource.tf create mode 100644 gen/definitions/area.yaml create mode 100644 gen/definitions/building.yaml create mode 100644 gen/definitions/credentials_cli.yaml create mode 100644 gen/definitions/credentials_https_read.yaml create mode 100644 gen/definitions/credentials_https_write.yaml create mode 100644 gen/definitions/credentials_snmpv2_read.yaml create mode 100644 gen/definitions/credentials_snmpv2_write.yaml create mode 100644 gen/definitions/credentials_snmpv3.yaml create mode 100644 gen/definitions/floor.yaml create mode 100644 gen/definitions/ip_pool.yaml create mode 100644 gen/definitions/ip_pool_reservation.yaml create mode 100644 gen/doc_category.go create mode 100644 gen/generator.go create mode 100644 gen/schema/schema.yaml create mode 100644 gen/templates/changelog.md.tmpl create mode 100644 gen/templates/data-source.tf create mode 100644 gen/templates/data_source.go create mode 100644 gen/templates/data_source_test.go create mode 100644 gen/templates/import.sh create mode 100644 gen/templates/model.go create mode 100644 gen/templates/provider.go create mode 100644 gen/templates/resource.go create mode 100644 gen/templates/resource.tf create mode 100644 gen/templates/resource_test.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/provider/data_source_catalystcenter_area.go create mode 100644 internal/provider/data_source_catalystcenter_area_test.go create mode 100644 internal/provider/data_source_catalystcenter_building.go create mode 100644 internal/provider/data_source_catalystcenter_building_test.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_cli.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_cli_test.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_https_read.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_https_read_test.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_https_write.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_https_write_test.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_snmpv2_read.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_snmpv2_read_test.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_snmpv2_write.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_snmpv2_write_test.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_snmpv3.go create mode 100644 internal/provider/data_source_catalystcenter_credentials_snmpv3_test.go create mode 100644 internal/provider/data_source_catalystcenter_floor.go create mode 100644 internal/provider/data_source_catalystcenter_floor_test.go create mode 100644 internal/provider/data_source_catalystcenter_ip_pool.go create mode 100644 internal/provider/data_source_catalystcenter_ip_pool_reservation.go create mode 100644 internal/provider/data_source_catalystcenter_ip_pool_reservation_test.go create mode 100644 internal/provider/data_source_catalystcenter_ip_pool_test.go create mode 100644 internal/provider/helpers/description_builder.go create mode 100644 internal/provider/helpers/utils.go create mode 100644 internal/provider/model_catalystcenter_area.go create mode 100644 internal/provider/model_catalystcenter_building.go create mode 100644 internal/provider/model_catalystcenter_credentials_cli.go create mode 100644 internal/provider/model_catalystcenter_credentials_https_read.go create mode 100644 internal/provider/model_catalystcenter_credentials_https_write.go create mode 100644 internal/provider/model_catalystcenter_credentials_snmpv2_read.go create mode 100644 internal/provider/model_catalystcenter_credentials_snmpv2_write.go create mode 100644 internal/provider/model_catalystcenter_credentials_snmpv3.go create mode 100644 internal/provider/model_catalystcenter_floor.go create mode 100644 internal/provider/model_catalystcenter_ip_pool.go create mode 100644 internal/provider/model_catalystcenter_ip_pool_reservation.go create mode 100644 internal/provider/provider.go create mode 100644 internal/provider/provider_test.go create mode 100644 internal/provider/resource_catalystcenter_area.go create mode 100644 internal/provider/resource_catalystcenter_area_test.go create mode 100644 internal/provider/resource_catalystcenter_building.go create mode 100644 internal/provider/resource_catalystcenter_building_test.go create mode 100644 internal/provider/resource_catalystcenter_credentials_cli.go create mode 100644 internal/provider/resource_catalystcenter_credentials_cli_test.go create mode 100644 internal/provider/resource_catalystcenter_credentials_https_read.go create mode 100644 internal/provider/resource_catalystcenter_credentials_https_read_test.go create mode 100644 internal/provider/resource_catalystcenter_credentials_https_write.go create mode 100644 internal/provider/resource_catalystcenter_credentials_https_write_test.go create mode 100644 internal/provider/resource_catalystcenter_credentials_snmpv2_read.go create mode 100644 internal/provider/resource_catalystcenter_credentials_snmpv2_read_test.go create mode 100644 internal/provider/resource_catalystcenter_credentials_snmpv2_write.go create mode 100644 internal/provider/resource_catalystcenter_credentials_snmpv2_write_test.go create mode 100644 internal/provider/resource_catalystcenter_credentials_snmpv3.go create mode 100644 internal/provider/resource_catalystcenter_credentials_snmpv3_test.go create mode 100644 internal/provider/resource_catalystcenter_floor.go create mode 100644 internal/provider/resource_catalystcenter_floor_test.go create mode 100644 internal/provider/resource_catalystcenter_ip_pool.go create mode 100644 internal/provider/resource_catalystcenter_ip_pool_reservation.go create mode 100644 internal/provider/resource_catalystcenter_ip_pool_reservation_test.go create mode 100644 internal/provider/resource_catalystcenter_ip_pool_test.go create mode 100644 main.go create mode 100644 templates/guides/changelog.md.tmpl create mode 100644 templates/index.md.tmpl create mode 100644 terraform-registry-manifest.json create mode 100644 tools/tools.go diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..87fdf720 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +# See GitHub's documentation for more information on this file: +# https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "daily" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..f89cf328 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,42 @@ +# Terraform Provider release workflow. +name: Release + +# This GitHub action creates a release when a tag that matches the pattern +# "v*" (e.g. v0.1.0) is created. +on: + push: + tags: + - 'v*' + +# Releases need permissions to read and write the repository contents. +# GitHub considers creating releases and uploading assets as writing contents. +permissions: + contents: write + +jobs: + goreleaser: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + # Allow goreleaser to access older tag information. + fetch-depth: 0 + - uses: actions/setup-go@v4 + with: + go-version-file: 'go.mod' + cache: true + - name: Import GPG key + id: import_gpg + uses: crazy-max/ghaction-import-gpg@v6.0.0 + with: + # These secrets will need to be configured for the repository: + gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }} + passphrase: ${{ secrets.PASSPHRASE }} + - name: Run GoReleaser + uses: goreleaser/goreleaser-action@v5.0.0 + with: + args: release --rm-dist + env: + # GitHub sets the GITHUB_TOKEN secret automatically. + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GPG_FINGERPRINT: ${{ steps.import_gpg.outputs.fingerprint }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..085d5ecd --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,66 @@ +# Terraform Provider testing workflow. +name: Tests + +# This GitHub action runs your tests for each pull request and push. +# Optionally, you can turn it on using a schedule for regular testing. +on: + workflow_dispatch: + pull_request: + paths-ignore: + - "README.md" + push: + paths-ignore: + - "README.md" + +# Testing only needs permissions to read the repository contents. +permissions: + contents: read + +jobs: + # Ensure project builds before running testing matrix + build: + name: Build + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v4 + with: + python-version: "3.10" + - uses: actions/setup-go@v4 + with: + go-version-file: "go.mod" + cache: true + - run: pip install yamale + - run: yamale -s gen/schema/schema.yaml gen/definitions/ + - run: go mod download + - run: go generate + - run: git diff --exit-code + - run: go build -v . + + # Run acceptance tests in a matrix with Terraform CLI versions + test: + name: Terraform Provider Acceptance Tests + needs: [build] # [consecutiveness, build] + runs-on: ubuntu-latest + timeout-minutes: 90 + strategy: + fail-fast: true + max-parallel: 1 + matrix: + # list whatever Terraform versions here you would like to support + terraform: + - "1.0.*" + - "1.5.*" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v4 + with: + go-version-file: "go.mod" + cache: true + - uses: hashicorp/setup-terraform@v2 + with: + terraform_version: ${{ matrix.terraform }} + terraform_wrapper: false + - run: go mod download + diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..fd3ad8e1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +*.dll +*.exe +.DS_Store +example.tf +terraform.tfplan +terraform.tfstate +bin/ +dist/ +modules-dev/ +/pkg/ +website/.vagrant +website/.bundle +website/build +website/node_modules +.vagrant/ +*.backup +./*.tfstate +.terraform/ +*.log +*.bak +*~ +.*.swp +.idea +*.iml +*.test +*.iml + +website/vendor + +# Test exclusions +!command/test-fixtures/**/*.tfstate +!command/test-fixtures/**/.terraform/ + +# Keep windows files with windows line endings +*.winfile eol=crlf diff --git a/.goreleaser.yml b/.goreleaser.yml new file mode 100644 index 00000000..9bb0aa71 --- /dev/null +++ b/.goreleaser.yml @@ -0,0 +1,60 @@ +# Visit https://goreleaser.com for documentation on how to customize this +# behavior. +before: + hooks: + # this is just an example and not a requirement for provider building/publishing + - go mod tidy +builds: +- env: + # goreleaser does not work with CGO, it could also complicate + # usage by users in CI/CD systems like Terraform Cloud where + # they are unable to install libraries. + - CGO_ENABLED=0 + mod_timestamp: '{{ .CommitTimestamp }}' + flags: + - -trimpath + ldflags: + - '-s -w -X main.version={{.Version}} -X main.commit={{.Commit}}' + goos: + - freebsd + - windows + - linux + - darwin + goarch: + - amd64 + - '386' + - arm + - arm64 + ignore: + - goos: darwin + goarch: '386' + binary: '{{ .ProjectName }}_v{{ .Version }}' +archives: +- format: zip + name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}' +checksum: + extra_files: + - glob: 'terraform-registry-manifest.json' + name_template: '{{ .ProjectName }}_{{ .Version }}_manifest.json' + name_template: '{{ .ProjectName }}_{{ .Version }}_SHA256SUMS' + algorithm: sha256 +signs: + - artifacts: checksum + args: + # if you are using this in a GitHub action or some other automated pipeline, you + # need to pass the batch flag to indicate its not interactive. + - "--batch" + - "--local-user" + - "{{ .Env.GPG_FINGERPRINT }}" # set this environment variable for your signing key + - "--output" + - "${signature}" + - "--detach-sign" + - "${artifact}" +release: + extra_files: + - glob: 'terraform-registry-manifest.json' + name_template: '{{ .ProjectName }}_{{ .Version }}_manifest.json' + # If you want to manually examine the release before its live, uncomment this line: + # draft: true +changelog: + skip: true diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..d2e326d8 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,16 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch generator", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "gen/generator.go", + "cwd": "./" + } + ] +} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..d6b1717b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.1.0 (unreleased) + +- Initial Release diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..f5fd27c7 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by sending an email to devnet-github-owners@cisco.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..4f9bdffe --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,76 @@ +# How to Contribute + +Thanks for your interest in contributing to this Terraform provider! Here are a few general guidelines on contributing and +reporting bugs that we ask you to review. Following these guidelines helps to communicate that you respect the time of +the contributors managing and developing this open source project. In return, they should reciprocate that respect in +addressing your issue, assessing changes, and helping you finalize your pull requests. In that spirit of mutual respect, +we endeavor to review incoming issues and pull requests within 10 days, and will close any lingering issues or pull +requests after 60 days of inactivity. + +Please note that all of your interactions in the project are subject to our [Code of Conduct](/CODE_OF_CONDUCT.md). This +includes creation of issues or pull requests, commenting on issues or pull requests, and extends to all interactions in +any real-time space e.g., Slack, Discord, etc. + +## Table Of Contents + +- [Reporting Issues](#reporting-issues) +- [Development](#development) + - [Building the Provider](#building-the-provider) + - [Acceptance Tests](#acceptance-tests) +- [Sending Pull Requests](#sending-pull-requests) +- [Other Ways to Contribute](#other-ways-to-contribute) + +## Reporting Issues + +Before reporting a new issue, please ensure that the issue was not already reported or fixed by searching through our +[issues list](https://github.com/CiscoDevNet/terraform-provider-catalystcenter/issues). + +When creating a new issue, please be sure to include a **title and clear description**, as much relevant information as +possible, and, if possible, a test case. + +**If you discover a security bug, please do not report it through GitHub. Instead, please see security procedures in +[SECURITY.md](/SECURITY.md).** + +## Development + +### Building the Provider + +1. Clone the repository +2. Enter the repository directory +3. Build the provider using the Go `install` command: + +```shell +go install +``` + +### Acceptance Tests + +In order to run the full suite of Acceptance tests, run `make testacc`. Make sure the respective environment variables are set (e.g., `CC_USERNAME`, `CC_PASSWORD`, `CC_URL`). + +Note: Acceptance tests create real resources. + +```shell +make testacc +``` + +## Sending Pull Requests + +Before sending a new pull request, take a look at existing pull requests and issues to see if the proposed change or fix +has been discussed in the past, or if the change was already implemented but not yet released. + +We expect new pull requests to include tests for any affected behavior, and, as we follow semantic versioning, we may +reserve breaking changes until the next major version release. + +## Other Ways to Contribute + +We welcome anyone that wants to contribute to this Terraform provider to triage and reply to open issues to help troubleshoot +and fix existing bugs. Here is what you can do: + +- Help ensure that existing issues follows the recommendations from the _[Reporting Issues](#reporting-issues)_ section, + providing feedback to the issue's author on what might be missing. +- Review existing pull requests, and testing patches against real infrastructure. +- Write a test, or add a missing test case to an existing test. + +Thanks again for your interest on contributing to this Terraform provider! + +:heart: diff --git a/GNUmakefile b/GNUmakefile new file mode 100644 index 00000000..7771cd69 --- /dev/null +++ b/GNUmakefile @@ -0,0 +1,6 @@ +default: testacc + +# Run acceptance tests +.PHONY: testacc +testacc: + TF_ACC=1 go test ./... -v $(TESTARGS) -timeout 120m diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..a612ad98 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.md b/README.md new file mode 100644 index 00000000..bebd7478 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +[![Tests](https://github.com/netascode/terraform-provider-catalystcenter/actions/workflows/test.yml/badge.svg)](https://github.com/netascode/terraform-provider-catalystcenter/actions/workflows/test.yml) + +# Terraform Provider Cisco Catalyst Center + +The Catalyst Center provider provides resources to interact with a Cisco Catalyst Center instance. It communicates with Catalyst Center via the REST API. + +All resources and data sources have been tested with the following releases. + +All resources and data sources have been tested with the following releases. + +| Platform | Version | +| --------------- | ------- | +| Catalyst Center | 2.3.7 | + +Documentation: + +## Requirements + +- [Terraform](https://www.terraform.io/downloads.html) >= 1.0 +- [Go](https://golang.org/doc/install) >= 1.19 + +## Building The Provider + +1. Clone the repository +2. Enter the repository directory +3. Build the provider using the Go `install` command: + +```shell +go install +``` + +## Adding Dependencies + +This provider uses [Go modules](https://github.com/golang/go/wiki/Modules). +Please see the Go documentation for the most up to date information about using Go modules. + +To add a new dependency `github.com/author/dependency` to your Terraform provider: + +```shell +go get github.com/author/dependency +go mod tidy +``` + +Then commit the changes to `go.mod` and `go.sum`. + +## Using the provider + +This Terraform Provider is available to install automatically via `terraform init`. If you're building the provider, follow the instructions to +[install it as a plugin.](https://www.terraform.io/docs/plugins/basics.html#installing-a-plugin) +After placing it into your plugins directory, run `terraform init` to initialize it. + +Additional documentation, including available resources and their arguments/attributes can be found on the [Terraform documentation website](https://registry.terraform.io/providers/netascode/catalystcenter/latest/docs). + +## Developing the Provider + +If you wish to work on the provider, you'll first need [Go](http://www.golang.org) installed on your machine (see [Requirements](#requirements) above). + +To compile the provider, run `go install`. This will build the provider and put the provider binary in the `$GOPATH/bin` directory. + +To generate or update documentation, run `go generate`. + +In order to run the full suite of Acceptance tests, run `make testacc`. Make sure the respective environment variables are set (e.g., `CC_USERNAME`, `CC_PASSWORD`, `CC_URL`). + +Note: Acceptance tests create real resources. + +```shell +make testacc +``` diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..16e7837f --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,38 @@ +# Security Policies and Procedures + +This document outlines security procedures and general policies for this project. + +- [Reporting a Bug](#reporting-a-bug) +- [Disclosure Policy](#disclosure-policy) +- [Comments on this Policy](#comments-on-this-policy) + +## Reporting a Bug + +The team and community take all security bugs in this project seriously. Thank +you for improving the security of this project. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing `oss-security@cisco.com`. + +The lead maintainer will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the security team will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. + +## Disclosure Policy + +When the security team receives a security bug report, they will assign it to a +primary handler. This person will coordinate the fix and release process, +involving the following steps: + +- Confirm the problem and determine the affected versions. +- Audit code to find any potential similar problems. +- Prepare fixes for all releases still under maintenance. These fixes will be + released as quickly as possible. + +## Comments on this Policy + +If you have suggestions on how this process could be improved please submit a +pull request. diff --git a/docs/data-sources/area.md b/docs/data-sources/area.md new file mode 100644 index 00000000..e03bbfd3 --- /dev/null +++ b/docs/data-sources/area.md @@ -0,0 +1,31 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_area Data Source - terraform-provider-catalystcenter" +subcategory: "Sites" +description: |- + This data source can read the Area. +--- + +# catalystcenter_area (Data Source) + +This data source can read the Area. + +## Example Usage + +```terraform +data "catalystcenter_area" "example" { + id = "76d24097-41c4-4558-a4d0-a8c07ac08470" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object + +### Read-Only + +- `name` (String) The name of the area +- `parent_name` (String) The path of the parent area, e.g. `Global/Area5`. `Global` in case of root area. diff --git a/docs/data-sources/building.md b/docs/data-sources/building.md new file mode 100644 index 00000000..ff08bc95 --- /dev/null +++ b/docs/data-sources/building.md @@ -0,0 +1,35 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_building Data Source - terraform-provider-catalystcenter" +subcategory: "Sites" +description: |- + This data source can read the Building. +--- + +# catalystcenter_building (Data Source) + +This data source can read the Building. + +## Example Usage + +```terraform +data "catalystcenter_building" "example" { + id = "76d24097-41c4-4558-a4d0-a8c07ac08470" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object + +### Read-Only + +- `address` (String) The address of the building +- `country` (String) The country of the building +- `latitude` (Number) Latitude +- `longitude` (Number) Longitude +- `name` (String) The name of the building +- `parent_name` (String) The path of the parent area, e.g. `Global/Area5`. `Global` in case of root area. diff --git a/docs/data-sources/credentials_cli.md b/docs/data-sources/credentials_cli.md new file mode 100644 index 00000000..d8a4032d --- /dev/null +++ b/docs/data-sources/credentials_cli.md @@ -0,0 +1,33 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_cli Data Source - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This data source can read the Credentials CLI. +--- + +# catalystcenter_credentials_cli (Data Source) + +This data source can read the Credentials CLI. + +## Example Usage + +```terraform +data "catalystcenter_credentials_cli" "example" { + id = "My CLI credentials" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object + +### Read-Only + +- `description` (String) The description of the CLI credentials +- `enable_password` (String) Enable password +- `password` (String) Password +- `username` (String) Username diff --git a/docs/data-sources/credentials_https_read.md b/docs/data-sources/credentials_https_read.md new file mode 100644 index 00000000..f6fdd30b --- /dev/null +++ b/docs/data-sources/credentials_https_read.md @@ -0,0 +1,33 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_https_read Data Source - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This data source can read the Credentials HTTPS Read. +--- + +# catalystcenter_credentials_https_read (Data Source) + +This data source can read the Credentials HTTPS Read. + +## Example Usage + +```terraform +data "catalystcenter_credentials_https_read" "example" { + id = "My HTTPS read credentials" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object + +### Read-Only + +- `description` (String) The description of the HTTPS credentials +- `password` (String) Password +- `port` (Number) HTTPS port +- `username` (String) Username diff --git a/docs/data-sources/credentials_https_write.md b/docs/data-sources/credentials_https_write.md new file mode 100644 index 00000000..4dbd0df2 --- /dev/null +++ b/docs/data-sources/credentials_https_write.md @@ -0,0 +1,33 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_https_write Data Source - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This data source can read the Credentials HTTPS Write. +--- + +# catalystcenter_credentials_https_write (Data Source) + +This data source can read the Credentials HTTPS Write. + +## Example Usage + +```terraform +data "catalystcenter_credentials_https_write" "example" { + id = "My HTTPS write credentials" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object + +### Read-Only + +- `description` (String) The description of the HTTPS credentials +- `password` (String) Password +- `port` (Number) HTTPS port +- `username` (String) Username diff --git a/docs/data-sources/credentials_snmpv2_read.md b/docs/data-sources/credentials_snmpv2_read.md new file mode 100644 index 00000000..c5a618d3 --- /dev/null +++ b/docs/data-sources/credentials_snmpv2_read.md @@ -0,0 +1,31 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_snmpv2_read Data Source - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This data source can read the Credentials SNMPv2 Read. +--- + +# catalystcenter_credentials_snmpv2_read (Data Source) + +This data source can read the Credentials SNMPv2 Read. + +## Example Usage + +```terraform +data "catalystcenter_credentials_snmpv2_read" "example" { + id = "My SNMPv2 read credentials" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object + +### Read-Only + +- `description` (String) The description of the SNMPv2 credentials +- `read_community` (String) Read community diff --git a/docs/data-sources/credentials_snmpv2_write.md b/docs/data-sources/credentials_snmpv2_write.md new file mode 100644 index 00000000..67f0fd1f --- /dev/null +++ b/docs/data-sources/credentials_snmpv2_write.md @@ -0,0 +1,31 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_snmpv2_write Data Source - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This data source can read the Credentials SNMPv2 Write. +--- + +# catalystcenter_credentials_snmpv2_write (Data Source) + +This data source can read the Credentials SNMPv2 Write. + +## Example Usage + +```terraform +data "catalystcenter_credentials_snmpv2_write" "example" { + id = "My SNMPv2 write credentials" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object + +### Read-Only + +- `description` (String) The description of the SNMPv2 credentials +- `write_community` (String) Write community diff --git a/docs/data-sources/credentials_snmpv3.md b/docs/data-sources/credentials_snmpv3.md new file mode 100644 index 00000000..cf9fa261 --- /dev/null +++ b/docs/data-sources/credentials_snmpv3.md @@ -0,0 +1,36 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_snmpv3 Data Source - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This data source can read the Credentials SNMPv3. +--- + +# catalystcenter_credentials_snmpv3 (Data Source) + +This data source can read the Credentials SNMPv3. + +## Example Usage + +```terraform +data "catalystcenter_credentials_snmpv3" "example" { + id = "My SNMPv3 credentials" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object + +### Read-Only + +- `auth_password` (String) Authentication password +- `auth_type` (String) Authentication type +- `description` (String) The description of the SNMPv3 credentials +- `privacy_password` (String) Privacy password +- `privacy_type` (String) Privacy type +- `snmp_mode` (String) SNMP mode +- `username` (String) Username diff --git a/docs/data-sources/floor.md b/docs/data-sources/floor.md new file mode 100644 index 00000000..e49a1432 --- /dev/null +++ b/docs/data-sources/floor.md @@ -0,0 +1,35 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_floor Data Source - terraform-provider-catalystcenter" +subcategory: "Sites" +description: |- + This data source can read the Floor. +--- + +# catalystcenter_floor (Data Source) + +This data source can read the Floor. + +## Example Usage + +```terraform +data "catalystcenter_floor" "example" { + id = "76d24097-41c4-4558-a4d0-a8c07ac08470" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object + +### Read-Only + +- `height` (Number) Height +- `length` (Number) Length +- `name` (String) The name of the floor +- `parent_name` (String) The path of the parent building, e.g. `Global/Building1` +- `rf_model` (String) The RF model +- `width` (Number) Width diff --git a/docs/data-sources/ip_pool.md b/docs/data-sources/ip_pool.md new file mode 100644 index 00000000..09095894 --- /dev/null +++ b/docs/data-sources/ip_pool.md @@ -0,0 +1,36 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_ip_pool Data Source - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This data source can read the IP Pool. +--- + +# catalystcenter_ip_pool (Data Source) + +This data source can read the IP Pool. + +## Example Usage + +```terraform +data "catalystcenter_ip_pool" "example" { + id = "MyPool1" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object + +### Read-Only + +- `dhcp_server_ips` (List of String) List of DHCP Server IPs +- `dns_server_ips` (List of String) List of DNS Server IPs +- `gateway` (String) The gateway for the IP pool +- `ip_address_space` (String) IP address version +- `ip_subnet` (String) The IP subnet of the IP pool +- `name` (String) The name of the IP pool +- `type` (String) Choose `Tunnel` to assign IP addresses to site-to-site VPN for IPSec tunneling. Choose `Generic` for all other network types. diff --git a/docs/data-sources/ip_pool_reservation.md b/docs/data-sources/ip_pool_reservation.md new file mode 100644 index 00000000..8a39520e --- /dev/null +++ b/docs/data-sources/ip_pool_reservation.md @@ -0,0 +1,50 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_ip_pool_reservation Data Source - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This data source can read the IP Pool Reservation. +--- + +# catalystcenter_ip_pool_reservation (Data Source) + +This data source can read the IP Pool Reservation. + +## Example Usage + +```terraform +data "catalystcenter_ip_pool_reservation" "example" { + id = "MyRes1" +} +``` + + +## Schema + +### Required + +- `id` (String) The id of the object +- `site_id` (String) The site ID + +### Read-Only + +- `ipv4_dhcp_servers` (List of String) List of DHCP Server IPs +- `ipv4_dns_servers` (List of String) List of DNS Server IPs +- `ipv4_gateway` (String) The gateway for the IP pool reservation +- `ipv4_global_pool` (String) IPv4 Global pool address with cidr, example: 175.175.0.0/16 +- `ipv4_prefix` (Boolean) If this value is `true`, the `ipv4_prefix_length` attribute must be provided, if it is `false`, the `ipv4_total_host` attribute must be provided +- `ipv4_prefix_length` (Number) The IPv4 prefix length is required when `ipv4_prefix` value is `true`. +- `ipv4_subnet` (String) The IPv4 subnet +- `ipv4_total_host` (Number) The total number of IPv4 hosts +- `ipv6_address_space` (Boolean) If the value is `false` only IPv4 input are required, otherwise both IPv6 and IPv4 are required +- `ipv6_dhcp_servers` (List of String) List of DHCP Server IPs +- `ipv6_dns_servers` (List of String) List of DNS Server IPs +- `ipv6_gateway` (String) The gateway for the IP pool reservation +- `ipv6_global_pool` (String) IPv6 Global pool address with cidr, example: 2001:db8:85a3::/64 +- `ipv6_prefix` (Boolean) If this value is `true`, the `ipv6_prefix_length` attribute must be provided, if it is `false`, the `ipv6_total_host` attribute must be provided +- `ipv6_prefix_length` (Number) The IPv6 prefix length is required when `ipv6_prefix` value is `true`. +- `ipv6_subnet` (String) The IPv6 subnet, for example `2001:db8:85a3:0:100::` +- `ipv6_total_host` (Number) The total number of IPv6 hosts +- `name` (String) The name of the IP pool reservation +- `slaac_support` (Boolean) Enable SLAAC support +- `type` (String) The type of the IP pool reservation diff --git a/docs/guides/changelog.md b/docs/guides/changelog.md new file mode 100644 index 00000000..bd96b81d --- /dev/null +++ b/docs/guides/changelog.md @@ -0,0 +1,13 @@ +--- +subcategory: "Guides" +page_title: "Changelog" +description: |- + Changelog +--- + +# Changelog + +## 0.1.0 (unreleased) + +- Initial Release + diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000..ac2c61bc --- /dev/null +++ b/docs/index.md @@ -0,0 +1,38 @@ + +--- +layout: "" +page_title: "Provider: Catalyst Center" +description: |- + The Catalyst Center provider provides resources to interact with a Cisco Catalyst Center instance. +--- + +# Cisco Catalyst Center Provider + +The Catalyst Center provider provides resources to interact with a Cisco Catalyst Center instance. It communicates with Catalyst Center via the REST API. + +All resources and data sources have been tested with the following releases. + +| Platform | Version | +| --------------- | ------- | +| Catalyst Center | 2.3.7 | + +## Example Usage + +```terraform +provider "catalystcenter" { + username = "admin" + password = "password" + url = "https://10.1.1.1" +} +``` + + +## Schema + +### Optional + +- `insecure` (Boolean) Allow insecure HTTPS client. This can also be set as the CC_INSECURE environment variable. Defaults to `true`. +- `password` (String, Sensitive) Password for the Catalyst Center instance. This can also be set as the CC_PASSWORD environment variable. +- `retries` (Number) Number of retries for REST API calls. This can also be set as the CC_RETRIES environment variable. Defaults to `3`. +- `url` (String) URL of the Catalyst Center instance. This can also be set as the CC_URL environment variable. +- `username` (String) Username for the Catalyst Center instance. This can also be set as the CC_USERNAME environment variable. diff --git a/docs/resources/area.md b/docs/resources/area.md new file mode 100644 index 00000000..20a58057 --- /dev/null +++ b/docs/resources/area.md @@ -0,0 +1,43 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_area Resource - terraform-provider-catalystcenter" +subcategory: "Sites" +description: |- + This resource can manage an Area. +--- + +# catalystcenter_area (Resource) + +This resource can manage an Area. + +## Example Usage + +```terraform +resource "catalystcenter_area" "example" { + name = "Area1" + parent_name = "Global" +} +``` + + +## Schema + +### Required + +- `name` (String) The name of the area + +### Optional + +- `parent_name` (String) The path of the parent area, e.g. `Global/Area5`. `Global` in case of root area. + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_area.example "4b0b7a80-44c0-4bf2-bab5-fc24b4e0a17e" +``` diff --git a/docs/resources/building.md b/docs/resources/building.md new file mode 100644 index 00000000..16800d96 --- /dev/null +++ b/docs/resources/building.md @@ -0,0 +1,48 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_building Resource - terraform-provider-catalystcenter" +subcategory: "Sites" +description: |- + This resource can manage a Building. +--- + +# catalystcenter_building (Resource) + +This resource can manage a Building. + +## Example Usage + +```terraform +resource "catalystcenter_building" "example" { + name = "Building1" + parent_name = "Global" + country = "United States" + address = "150 W Tasman Dr, San Jose" + latitude = 37.338 + longitude = -121.832 +} +``` + + +## Schema + +### Required + +- `address` (String) The address of the building +- `country` (String) The country of the building +- `latitude` (Number) Latitude +- `longitude` (Number) Longitude +- `name` (String) The name of the building +- `parent_name` (String) The path of the parent area, e.g. `Global/Area5`. `Global` in case of root area. + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_building.example "4b0b7a80-44c0-4bf2-bab5-fc24b4e0a17e" +``` diff --git a/docs/resources/credentials_cli.md b/docs/resources/credentials_cli.md new file mode 100644 index 00000000..acd648d7 --- /dev/null +++ b/docs/resources/credentials_cli.md @@ -0,0 +1,46 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_cli Resource - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This resource can manage a Credentials CLI. +--- + +# catalystcenter_credentials_cli (Resource) + +This resource can manage a Credentials CLI. + +## Example Usage + +```terraform +resource "catalystcenter_credentials_cli" "example" { + description = "My CLI credentials" + username = "user1" + password = "password1" +} +``` + + +## Schema + +### Required + +- `description` (String) The description of the CLI credentials +- `password` (String) Password +- `username` (String) Username + +### Optional + +- `enable_password` (String) Enable password + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_credentials_cli.example "My CLI credentials" +``` diff --git a/docs/resources/credentials_https_read.md b/docs/resources/credentials_https_read.md new file mode 100644 index 00000000..a1fd30a8 --- /dev/null +++ b/docs/resources/credentials_https_read.md @@ -0,0 +1,48 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_https_read Resource - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This resource can manage a Credentials HTTPS Read. +--- + +# catalystcenter_credentials_https_read (Resource) + +This resource can manage a Credentials HTTPS Read. + +## Example Usage + +```terraform +resource "catalystcenter_credentials_https_read" "example" { + description = "My HTTPS read credentials" + username = "user1" + password = "password1" + port = 444 +} +``` + + +## Schema + +### Required + +- `description` (String) The description of the HTTPS credentials +- `password` (String) Password +- `username` (String) Username + +### Optional + +- `port` (Number) HTTPS port + - Default value: `443` + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_credentials_https_read.example "My HTTPS read credentials" +``` diff --git a/docs/resources/credentials_https_write.md b/docs/resources/credentials_https_write.md new file mode 100644 index 00000000..c60d40b5 --- /dev/null +++ b/docs/resources/credentials_https_write.md @@ -0,0 +1,48 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_https_write Resource - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This resource can manage a Credentials HTTPS Write. +--- + +# catalystcenter_credentials_https_write (Resource) + +This resource can manage a Credentials HTTPS Write. + +## Example Usage + +```terraform +resource "catalystcenter_credentials_https_write" "example" { + description = "My HTTPS write credentials" + username = "user1" + password = "password1" + port = 444 +} +``` + + +## Schema + +### Required + +- `description` (String) The description of the HTTPS credentials +- `password` (String) Password +- `username` (String) Username + +### Optional + +- `port` (Number) HTTPS port + - Default value: `443` + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_credentials_https_write.example "My HTTPS write credentials" +``` diff --git a/docs/resources/credentials_snmpv2_read.md b/docs/resources/credentials_snmpv2_read.md new file mode 100644 index 00000000..08c8b207 --- /dev/null +++ b/docs/resources/credentials_snmpv2_read.md @@ -0,0 +1,40 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_snmpv2_read Resource - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This resource can manage a Credentials SNMPv2 Read. +--- + +# catalystcenter_credentials_snmpv2_read (Resource) + +This resource can manage a Credentials SNMPv2 Read. + +## Example Usage + +```terraform +resource "catalystcenter_credentials_snmpv2_read" "example" { + description = "My SNMPv2 read credentials" + read_community = "community1" +} +``` + + +## Schema + +### Required + +- `description` (String) The description of the SNMPv2 credentials +- `read_community` (String) Read community + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_credentials_snmpv2_read.example "My SNMPv2 read credentials" +``` diff --git a/docs/resources/credentials_snmpv2_write.md b/docs/resources/credentials_snmpv2_write.md new file mode 100644 index 00000000..7e0b59c0 --- /dev/null +++ b/docs/resources/credentials_snmpv2_write.md @@ -0,0 +1,40 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_snmpv2_write Resource - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This resource can manage a Credentials SNMPv2 Write. +--- + +# catalystcenter_credentials_snmpv2_write (Resource) + +This resource can manage a Credentials SNMPv2 Write. + +## Example Usage + +```terraform +resource "catalystcenter_credentials_snmpv2_write" "example" { + description = "My SNMPv2 write credentials" + write_community = "community1" +} +``` + + +## Schema + +### Required + +- `description` (String) The description of the SNMPv2 credentials +- `write_community` (String) Write community + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_credentials_snmpv2_write.example "My SNMPv2 write credentials" +``` diff --git a/docs/resources/credentials_snmpv3.md b/docs/resources/credentials_snmpv3.md new file mode 100644 index 00000000..7776bb37 --- /dev/null +++ b/docs/resources/credentials_snmpv3.md @@ -0,0 +1,56 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_credentials_snmpv3 Resource - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This resource can manage a Credentials SNMPv3. +--- + +# catalystcenter_credentials_snmpv3 (Resource) + +This resource can manage a Credentials SNMPv3. + +## Example Usage + +```terraform +resource "catalystcenter_credentials_snmpv3" "example" { + description = "My SNMPv3 credentials" + username = "user1" + privacy_type = "AES128" + privacy_password = "password1" + auth_type = "SHA" + auth_password = "password1" + snmp_mode = "AUTHPRIV" +} +``` + + +## Schema + +### Required + +- `description` (String) The description of the SNMPv3 credentials +- `snmp_mode` (String) SNMP mode + - Choices: `AUTHPRIV`, `AUTHNOPRIV`, `NOAUTHNOPRIV` +- `username` (String) Username + +### Optional + +- `auth_password` (String) Authentication password +- `auth_type` (String) Authentication type + - Choices: `SHA`, `MD5` +- `privacy_password` (String) Privacy password +- `privacy_type` (String) Privacy type + - Choices: `AES128`, `AES192`, `AES256` + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_credentials_snmpv3.example "My SNMPv3 credentials" +``` diff --git a/docs/resources/floor.md b/docs/resources/floor.md new file mode 100644 index 00000000..863183f6 --- /dev/null +++ b/docs/resources/floor.md @@ -0,0 +1,49 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_floor Resource - terraform-provider-catalystcenter" +subcategory: "Sites" +description: |- + This resource can manage a Floor. +--- + +# catalystcenter_floor (Resource) + +This resource can manage a Floor. + +## Example Usage + +```terraform +resource "catalystcenter_floor" "example" { + name = "Floor1" + parent_name = "Global/Building1" + rf_model = "Drywall Office Only" + width = 30.5 + length = 50.5 + height = 3.5 +} +``` + + +## Schema + +### Required + +- `height` (Number) Height +- `length` (Number) Length +- `name` (String) The name of the floor +- `parent_name` (String) The path of the parent building, e.g. `Global/Building1` +- `rf_model` (String) The RF model + - Choices: `Cubes And Walled Offices`, `Drywall Office Only`, `Indoor High Ceiling`, `Outdoor Open Space` +- `width` (Number) Width + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_floor.example "4b0b7a80-44c0-4bf2-bab5-fc24b4e0a17e" +``` diff --git a/docs/resources/ip_pool.md b/docs/resources/ip_pool.md new file mode 100644 index 00000000..71bb1f53 --- /dev/null +++ b/docs/resources/ip_pool.md @@ -0,0 +1,57 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_ip_pool Resource - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This resource can manage an IP Pool. +--- + +# catalystcenter_ip_pool (Resource) + +This resource can manage an IP Pool. + +## Example Usage + +```terraform +resource "catalystcenter_ip_pool" "example" { + name = "MyPool1" + ip_address_space = "IPv4" + type = "Generic" + ip_subnet = "21.1.1.0/24" + gateway = "21.1.1.1" + dhcp_server_ips = ["1.2.3.4"] + dns_server_ips = ["2.3.4.5"] +} +``` + + +## Schema + +### Required + +- `ip_subnet` (String) The IP subnet of the IP pool +- `name` (String) The name of the IP pool + +### Optional + +- `dhcp_server_ips` (List of String) List of DHCP Server IPs +- `dns_server_ips` (List of String) List of DNS Server IPs +- `gateway` (String) The gateway for the IP pool +- `ip_address_space` (String) IP address version + - Choices: `IPv4`, `IPv6` + - Default value: `IPv4` +- `type` (String) Choose `Tunnel` to assign IP addresses to site-to-site VPN for IPSec tunneling. Choose `Generic` for all other network types. + - Choices: `Generic`, `Tunnel` + - Default value: `Generic` + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_ip_pool.example "MyPool1" +``` diff --git a/docs/resources/ip_pool_reservation.md b/docs/resources/ip_pool_reservation.md new file mode 100644 index 00000000..98260e18 --- /dev/null +++ b/docs/resources/ip_pool_reservation.md @@ -0,0 +1,73 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "catalystcenter_ip_pool_reservation Resource - terraform-provider-catalystcenter" +subcategory: "Network Settings" +description: |- + This resource can manage an IP Pool Reservation. +--- + +# catalystcenter_ip_pool_reservation (Resource) + +This resource can manage an IP Pool Reservation. + +## Example Usage + +```terraform +resource "catalystcenter_ip_pool_reservation" "example" { + site_id = "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1" + name = "MyRes1" + type = "Generic" + ipv6_address_space = false + ipv4_global_pool = "172.32.0.0/16" + ipv4_prefix = true + ipv4_prefix_length = 24 + ipv4_subnet = "172.32.1.0" + ipv4_gateway = "172.32.1.1" + ipv4_dhcp_servers = ["1.2.3.4"] + ipv4_dns_servers = ["2.3.4.5"] +} +``` + + +## Schema + +### Required + +- `ipv4_global_pool` (String) IPv4 Global pool address with cidr, example: 175.175.0.0/16 +- `ipv4_prefix` (Boolean) If this value is `true`, the `ipv4_prefix_length` attribute must be provided, if it is `false`, the `ipv4_total_host` attribute must be provided +- `name` (String) The name of the IP pool reservation +- `type` (String) The type of the IP pool reservation + - Choices: `Generic`, `LAN`, `WAN`, `management`, `service` + +### Optional + +- `ipv4_dhcp_servers` (List of String) List of DHCP Server IPs +- `ipv4_dns_servers` (List of String) List of DNS Server IPs +- `ipv4_gateway` (String) The gateway for the IP pool reservation +- `ipv4_prefix_length` (Number) The IPv4 prefix length is required when `ipv4_prefix` value is `true`. +- `ipv4_subnet` (String) The IPv4 subnet +- `ipv4_total_host` (Number) The total number of IPv4 hosts +- `ipv6_address_space` (Boolean) If the value is `false` only IPv4 input are required, otherwise both IPv6 and IPv4 are required + - Default value: `false` +- `ipv6_dhcp_servers` (List of String) List of DHCP Server IPs +- `ipv6_dns_servers` (List of String) List of DNS Server IPs +- `ipv6_gateway` (String) The gateway for the IP pool reservation +- `ipv6_global_pool` (String) IPv6 Global pool address with cidr, example: 2001:db8:85a3::/64 +- `ipv6_prefix` (Boolean) If this value is `true`, the `ipv6_prefix_length` attribute must be provided, if it is `false`, the `ipv6_total_host` attribute must be provided +- `ipv6_prefix_length` (Number) The IPv6 prefix length is required when `ipv6_prefix` value is `true`. +- `ipv6_subnet` (String) The IPv6 subnet, for example `2001:db8:85a3:0:100::` +- `ipv6_total_host` (Number) The total number of IPv6 hosts +- `site_id` (String) The site ID +- `slaac_support` (Boolean) Enable SLAAC support + +### Read-Only + +- `id` (String) The id of the object + +## Import + +Import is supported using the following syntax: + +```shell +terraform import catalystcenter_ip_pool_reservation.example "MyRes1" +``` diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 00000000..026c42c7 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,9 @@ +# Examples + +This directory contains examples that are mostly used for documentation, but can also be run/tested manually via the Terraform CLI. + +The document generation tool looks for files in the following locations by default. All other *.tf files besides the ones mentioned below are ignored by the documentation tool. This is useful for creating examples that can run and/or ar testable even if some parts are not relevant for the documentation. + +* **provider/provider.tf** example file for the provider index page +* **data-sources/`full data source name`/data-source.tf** example file for the named data source page +* **resources/`full resource name`/resource.tf** example file for the named data source page diff --git a/examples/data-sources/catalystcenter_area/data-source.tf b/examples/data-sources/catalystcenter_area/data-source.tf new file mode 100644 index 00000000..0c0ecfac --- /dev/null +++ b/examples/data-sources/catalystcenter_area/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_area" "example" { + id = "76d24097-41c4-4558-a4d0-a8c07ac08470" +} diff --git a/examples/data-sources/catalystcenter_building/data-source.tf b/examples/data-sources/catalystcenter_building/data-source.tf new file mode 100644 index 00000000..1b6c438c --- /dev/null +++ b/examples/data-sources/catalystcenter_building/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_building" "example" { + id = "76d24097-41c4-4558-a4d0-a8c07ac08470" +} diff --git a/examples/data-sources/catalystcenter_credentials_cli/data-source.tf b/examples/data-sources/catalystcenter_credentials_cli/data-source.tf new file mode 100644 index 00000000..e5767a49 --- /dev/null +++ b/examples/data-sources/catalystcenter_credentials_cli/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_credentials_cli" "example" { + id = "My CLI credentials" +} diff --git a/examples/data-sources/catalystcenter_credentials_https_read/data-source.tf b/examples/data-sources/catalystcenter_credentials_https_read/data-source.tf new file mode 100644 index 00000000..cabafc99 --- /dev/null +++ b/examples/data-sources/catalystcenter_credentials_https_read/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_credentials_https_read" "example" { + id = "My HTTPS read credentials" +} diff --git a/examples/data-sources/catalystcenter_credentials_https_write/data-source.tf b/examples/data-sources/catalystcenter_credentials_https_write/data-source.tf new file mode 100644 index 00000000..9b299de5 --- /dev/null +++ b/examples/data-sources/catalystcenter_credentials_https_write/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_credentials_https_write" "example" { + id = "My HTTPS write credentials" +} diff --git a/examples/data-sources/catalystcenter_credentials_snmpv2_read/data-source.tf b/examples/data-sources/catalystcenter_credentials_snmpv2_read/data-source.tf new file mode 100644 index 00000000..52d11c83 --- /dev/null +++ b/examples/data-sources/catalystcenter_credentials_snmpv2_read/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_credentials_snmpv2_read" "example" { + id = "My SNMPv2 read credentials" +} diff --git a/examples/data-sources/catalystcenter_credentials_snmpv2_write/data-source.tf b/examples/data-sources/catalystcenter_credentials_snmpv2_write/data-source.tf new file mode 100644 index 00000000..0b9c9cf1 --- /dev/null +++ b/examples/data-sources/catalystcenter_credentials_snmpv2_write/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_credentials_snmpv2_write" "example" { + id = "My SNMPv2 write credentials" +} diff --git a/examples/data-sources/catalystcenter_credentials_snmpv3/data-source.tf b/examples/data-sources/catalystcenter_credentials_snmpv3/data-source.tf new file mode 100644 index 00000000..41776c92 --- /dev/null +++ b/examples/data-sources/catalystcenter_credentials_snmpv3/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_credentials_snmpv3" "example" { + id = "My SNMPv3 credentials" +} diff --git a/examples/data-sources/catalystcenter_floor/data-source.tf b/examples/data-sources/catalystcenter_floor/data-source.tf new file mode 100644 index 00000000..ff653036 --- /dev/null +++ b/examples/data-sources/catalystcenter_floor/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_floor" "example" { + id = "76d24097-41c4-4558-a4d0-a8c07ac08470" +} diff --git a/examples/data-sources/catalystcenter_ip_pool/data-source.tf b/examples/data-sources/catalystcenter_ip_pool/data-source.tf new file mode 100644 index 00000000..db6d8c78 --- /dev/null +++ b/examples/data-sources/catalystcenter_ip_pool/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_ip_pool" "example" { + id = "MyPool1" +} diff --git a/examples/data-sources/catalystcenter_ip_pool_reservation/data-source.tf b/examples/data-sources/catalystcenter_ip_pool_reservation/data-source.tf new file mode 100644 index 00000000..c1963baf --- /dev/null +++ b/examples/data-sources/catalystcenter_ip_pool_reservation/data-source.tf @@ -0,0 +1,3 @@ +data "catalystcenter_ip_pool_reservation" "example" { + id = "MyRes1" +} diff --git a/examples/provider/provider.tf b/examples/provider/provider.tf new file mode 100644 index 00000000..19ffbbcd --- /dev/null +++ b/examples/provider/provider.tf @@ -0,0 +1,5 @@ +provider "catalystcenter" { + username = "admin" + password = "password" + url = "https://10.1.1.1" +} diff --git a/examples/resources/catalystcenter_area/import.sh b/examples/resources/catalystcenter_area/import.sh new file mode 100644 index 00000000..37794a81 --- /dev/null +++ b/examples/resources/catalystcenter_area/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_area.example "4b0b7a80-44c0-4bf2-bab5-fc24b4e0a17e" diff --git a/examples/resources/catalystcenter_area/resource.tf b/examples/resources/catalystcenter_area/resource.tf new file mode 100644 index 00000000..f0acbf3f --- /dev/null +++ b/examples/resources/catalystcenter_area/resource.tf @@ -0,0 +1,4 @@ +resource "catalystcenter_area" "example" { + name = "Area1" + parent_name = "Global" +} diff --git a/examples/resources/catalystcenter_building/import.sh b/examples/resources/catalystcenter_building/import.sh new file mode 100644 index 00000000..b892b134 --- /dev/null +++ b/examples/resources/catalystcenter_building/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_building.example "4b0b7a80-44c0-4bf2-bab5-fc24b4e0a17e" diff --git a/examples/resources/catalystcenter_building/resource.tf b/examples/resources/catalystcenter_building/resource.tf new file mode 100644 index 00000000..b56a00fc --- /dev/null +++ b/examples/resources/catalystcenter_building/resource.tf @@ -0,0 +1,8 @@ +resource "catalystcenter_building" "example" { + name = "Building1" + parent_name = "Global" + country = "United States" + address = "150 W Tasman Dr, San Jose" + latitude = 37.338 + longitude = -121.832 +} diff --git a/examples/resources/catalystcenter_credentials_cli/import.sh b/examples/resources/catalystcenter_credentials_cli/import.sh new file mode 100644 index 00000000..f55af583 --- /dev/null +++ b/examples/resources/catalystcenter_credentials_cli/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_credentials_cli.example "My CLI credentials" diff --git a/examples/resources/catalystcenter_credentials_cli/resource.tf b/examples/resources/catalystcenter_credentials_cli/resource.tf new file mode 100644 index 00000000..feacbd53 --- /dev/null +++ b/examples/resources/catalystcenter_credentials_cli/resource.tf @@ -0,0 +1,5 @@ +resource "catalystcenter_credentials_cli" "example" { + description = "My CLI credentials" + username = "user1" + password = "password1" +} diff --git a/examples/resources/catalystcenter_credentials_https_read/import.sh b/examples/resources/catalystcenter_credentials_https_read/import.sh new file mode 100644 index 00000000..ccb46439 --- /dev/null +++ b/examples/resources/catalystcenter_credentials_https_read/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_credentials_https_read.example "My HTTPS read credentials" diff --git a/examples/resources/catalystcenter_credentials_https_read/resource.tf b/examples/resources/catalystcenter_credentials_https_read/resource.tf new file mode 100644 index 00000000..9997e84b --- /dev/null +++ b/examples/resources/catalystcenter_credentials_https_read/resource.tf @@ -0,0 +1,6 @@ +resource "catalystcenter_credentials_https_read" "example" { + description = "My HTTPS read credentials" + username = "user1" + password = "password1" + port = 444 +} diff --git a/examples/resources/catalystcenter_credentials_https_write/import.sh b/examples/resources/catalystcenter_credentials_https_write/import.sh new file mode 100644 index 00000000..d9ef7c73 --- /dev/null +++ b/examples/resources/catalystcenter_credentials_https_write/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_credentials_https_write.example "My HTTPS write credentials" diff --git a/examples/resources/catalystcenter_credentials_https_write/resource.tf b/examples/resources/catalystcenter_credentials_https_write/resource.tf new file mode 100644 index 00000000..0ce8ee79 --- /dev/null +++ b/examples/resources/catalystcenter_credentials_https_write/resource.tf @@ -0,0 +1,6 @@ +resource "catalystcenter_credentials_https_write" "example" { + description = "My HTTPS write credentials" + username = "user1" + password = "password1" + port = 444 +} diff --git a/examples/resources/catalystcenter_credentials_snmpv2_read/import.sh b/examples/resources/catalystcenter_credentials_snmpv2_read/import.sh new file mode 100644 index 00000000..8d8fd613 --- /dev/null +++ b/examples/resources/catalystcenter_credentials_snmpv2_read/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_credentials_snmpv2_read.example "My SNMPv2 read credentials" diff --git a/examples/resources/catalystcenter_credentials_snmpv2_read/resource.tf b/examples/resources/catalystcenter_credentials_snmpv2_read/resource.tf new file mode 100644 index 00000000..241d8fab --- /dev/null +++ b/examples/resources/catalystcenter_credentials_snmpv2_read/resource.tf @@ -0,0 +1,4 @@ +resource "catalystcenter_credentials_snmpv2_read" "example" { + description = "My SNMPv2 read credentials" + read_community = "community1" +} diff --git a/examples/resources/catalystcenter_credentials_snmpv2_write/import.sh b/examples/resources/catalystcenter_credentials_snmpv2_write/import.sh new file mode 100644 index 00000000..6b99f04e --- /dev/null +++ b/examples/resources/catalystcenter_credentials_snmpv2_write/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_credentials_snmpv2_write.example "My SNMPv2 write credentials" diff --git a/examples/resources/catalystcenter_credentials_snmpv2_write/resource.tf b/examples/resources/catalystcenter_credentials_snmpv2_write/resource.tf new file mode 100644 index 00000000..fa7313e9 --- /dev/null +++ b/examples/resources/catalystcenter_credentials_snmpv2_write/resource.tf @@ -0,0 +1,4 @@ +resource "catalystcenter_credentials_snmpv2_write" "example" { + description = "My SNMPv2 write credentials" + write_community = "community1" +} diff --git a/examples/resources/catalystcenter_credentials_snmpv3/import.sh b/examples/resources/catalystcenter_credentials_snmpv3/import.sh new file mode 100644 index 00000000..9cebaaf8 --- /dev/null +++ b/examples/resources/catalystcenter_credentials_snmpv3/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_credentials_snmpv3.example "My SNMPv3 credentials" diff --git a/examples/resources/catalystcenter_credentials_snmpv3/resource.tf b/examples/resources/catalystcenter_credentials_snmpv3/resource.tf new file mode 100644 index 00000000..fffa1311 --- /dev/null +++ b/examples/resources/catalystcenter_credentials_snmpv3/resource.tf @@ -0,0 +1,9 @@ +resource "catalystcenter_credentials_snmpv3" "example" { + description = "My SNMPv3 credentials" + username = "user1" + privacy_type = "AES128" + privacy_password = "password1" + auth_type = "SHA" + auth_password = "password1" + snmp_mode = "AUTHPRIV" +} diff --git a/examples/resources/catalystcenter_floor/import.sh b/examples/resources/catalystcenter_floor/import.sh new file mode 100644 index 00000000..edf85971 --- /dev/null +++ b/examples/resources/catalystcenter_floor/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_floor.example "4b0b7a80-44c0-4bf2-bab5-fc24b4e0a17e" diff --git a/examples/resources/catalystcenter_floor/resource.tf b/examples/resources/catalystcenter_floor/resource.tf new file mode 100644 index 00000000..15f3b2f8 --- /dev/null +++ b/examples/resources/catalystcenter_floor/resource.tf @@ -0,0 +1,8 @@ +resource "catalystcenter_floor" "example" { + name = "Floor1" + parent_name = "Global/Building1" + rf_model = "Drywall Office Only" + width = 30.5 + length = 50.5 + height = 3.5 +} diff --git a/examples/resources/catalystcenter_ip_pool/import.sh b/examples/resources/catalystcenter_ip_pool/import.sh new file mode 100644 index 00000000..516cc148 --- /dev/null +++ b/examples/resources/catalystcenter_ip_pool/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_ip_pool.example "MyPool1" diff --git a/examples/resources/catalystcenter_ip_pool/resource.tf b/examples/resources/catalystcenter_ip_pool/resource.tf new file mode 100644 index 00000000..8975f03f --- /dev/null +++ b/examples/resources/catalystcenter_ip_pool/resource.tf @@ -0,0 +1,9 @@ +resource "catalystcenter_ip_pool" "example" { + name = "MyPool1" + ip_address_space = "IPv4" + type = "Generic" + ip_subnet = "21.1.1.0/24" + gateway = "21.1.1.1" + dhcp_server_ips = ["1.2.3.4"] + dns_server_ips = ["2.3.4.5"] +} diff --git a/examples/resources/catalystcenter_ip_pool_reservation/import.sh b/examples/resources/catalystcenter_ip_pool_reservation/import.sh new file mode 100644 index 00000000..67074251 --- /dev/null +++ b/examples/resources/catalystcenter_ip_pool_reservation/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_ip_pool_reservation.example "MyRes1" diff --git a/examples/resources/catalystcenter_ip_pool_reservation/resource.tf b/examples/resources/catalystcenter_ip_pool_reservation/resource.tf new file mode 100644 index 00000000..5e365d46 --- /dev/null +++ b/examples/resources/catalystcenter_ip_pool_reservation/resource.tf @@ -0,0 +1,13 @@ +resource "catalystcenter_ip_pool_reservation" "example" { + site_id = "5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1" + name = "MyRes1" + type = "Generic" + ipv6_address_space = false + ipv4_global_pool = "172.32.0.0/16" + ipv4_prefix = true + ipv4_prefix_length = 24 + ipv4_subnet = "172.32.1.0" + ipv4_gateway = "172.32.1.1" + ipv4_dhcp_servers = ["1.2.3.4"] + ipv4_dns_servers = ["2.3.4.5"] +} diff --git a/gen/definitions/area.yaml b/gen/definitions/area.yaml new file mode 100644 index 00000000..5c6c5d54 --- /dev/null +++ b/gen/definitions/area.yaml @@ -0,0 +1,24 @@ +--- +name: Area +rest_endpoint: /dna/intent/api/v1/site +get_rest_endpoint: /dna/intent/api/v2/site +id_path: siteId +id_query_param: id +doc_category: Sites +attributes: + - model_name: type + type: String + value: area + - model_name: name + data_path: site.area + response_data_path: response.0.name + type: String + mandatory: true + description: The name of the area + example: Area1 + - model_name: parentName + data_path: site.area + type: String + write_only: true + description: The path of the parent area, e.g. `Global/Area5`. `Global` in case of root area. + example: Global diff --git a/gen/definitions/building.yaml b/gen/definitions/building.yaml new file mode 100644 index 00000000..548a31b1 --- /dev/null +++ b/gen/definitions/building.yaml @@ -0,0 +1,53 @@ +--- +name: Building +rest_endpoint: /dna/intent/api/v1/site +get_rest_endpoint: /dna/intent/api/v2/site +id_path: siteId +id_query_param: id +doc_category: Sites +attributes: + - model_name: type + type: String + value: building + - model_name: name + data_path: site.building + response_data_path: response.0.name + type: String + mandatory: true + description: The name of the building + example: Building1 + - model_name: parentName + data_path: site.building + type: String + mandatory: true + write_only: true + description: The path of the parent area, e.g. `Global/Area5`. `Global` in case of root area. + example: Global + - model_name: country + data_path: site.building + response_data_path: response.0.additionalInfo.0.attributes.country + type: String + mandatory: true + description: The country of the building + example: United States + - model_name: address + data_path: site.building + response_data_path: response.0.additionalInfo.0.attributes.address + type: String + mandatory: true + description: The address of the building + example: 150 W Tasman Dr, San Jose + - model_name: latitude + data_path: site.building + response_data_path: response.0.additionalInfo.0.attributes.latitude + type: Float64 + mandatory: true + description: Latitude + example: 37.338 + - model_name: longitude + data_path: site.building + response_data_path: response.0.additionalInfo.0.attributes.longitude + type: Float64 + mandatory: true + description: Longitude + example: -121.832 \ No newline at end of file diff --git a/gen/definitions/credentials_cli.yaml b/gen/definitions/credentials_cli.yaml new file mode 100644 index 00000000..25592a67 --- /dev/null +++ b/gen/definitions/credentials_cli.yaml @@ -0,0 +1,36 @@ +--- +name: Credentials CLI +rest_endpoint: /dna/intent/api/v2/global-credential +get_from_all: true +id_from_query_path: response.cliCredential +put_id_include_path: cliCredential.0 +doc_category: Network Settings +attributes: + - model_name: description + data_path: cliCredential.0 + response_data_path: description + type: String + id: true + description: The description of the CLI credentials + example: My CLI credentials + - model_name: username + data_path: cliCredential.0 + response_data_path: username + type: String + mandatory: true + description: Username + example: user1 + - model_name: password + data_path: cliCredential.0 + type: String + mandatory: true + write_only: true + description: Password + example: password1 + - model_name: enablePassword + data_path: cliCredential.0 + type: String + write_only: true + description: Enable password + example: password1 + exclude_test: true \ No newline at end of file diff --git a/gen/definitions/credentials_https_read.yaml b/gen/definitions/credentials_https_read.yaml new file mode 100644 index 00000000..4b67d8d7 --- /dev/null +++ b/gen/definitions/credentials_https_read.yaml @@ -0,0 +1,37 @@ +--- +name: Credentials HTTPS Read +rest_endpoint: /dna/intent/api/v2/global-credential +get_from_all: true +id_from_query_path: response.httpsRead +put_id_include_path: httpsRead.0 +skip_minimum_test: true # using PUT always returns an error as of v2.3.7.3 +doc_category: Network Settings +attributes: + - model_name: description + data_path: httpsRead.0 + response_data_path: description + type: String + id: true + description: The description of the HTTPS credentials + example: My HTTPS read credentials + - model_name: username + data_path: httpsRead.0 + response_data_path: username + type: String + mandatory: true + description: Username + example: user1 + - model_name: password + data_path: httpsRead.0 + type: String + mandatory: true + write_only: true + description: Password + example: password1 + - model_name: port + data_path: httpsRead.0 + response_data_path: port + type: Int64 + default_value: 443 + description: HTTPS port + example: 444 diff --git a/gen/definitions/credentials_https_write.yaml b/gen/definitions/credentials_https_write.yaml new file mode 100644 index 00000000..9bea0ae2 --- /dev/null +++ b/gen/definitions/credentials_https_write.yaml @@ -0,0 +1,37 @@ +--- +name: Credentials HTTPS Write +rest_endpoint: /dna/intent/api/v2/global-credential +get_from_all: true +id_from_query_path: response.httpsWrite +put_id_include_path: httpsWrite.0 +skip_minimum_test: true # using PUT always returns an error as of v2.3.7.3 +doc_category: Network Settings +attributes: + - model_name: description + data_path: httpsWrite.0 + response_data_path: description + type: String + id: true + description: The description of the HTTPS credentials + example: My HTTPS write credentials + - model_name: username + data_path: httpsWrite.0 + response_data_path: username + type: String + mandatory: true + description: Username + example: user1 + - model_name: password + data_path: httpsWrite.0 + type: String + mandatory: true + write_only: true + description: Password + example: password1 + - model_name: port + data_path: httpsWrite.0 + response_data_path: port + type: Int64 + default_value: 443 + description: HTTPS port + example: 444 diff --git a/gen/definitions/credentials_snmpv2_read.yaml b/gen/definitions/credentials_snmpv2_read.yaml new file mode 100644 index 00000000..d7053bd0 --- /dev/null +++ b/gen/definitions/credentials_snmpv2_read.yaml @@ -0,0 +1,24 @@ +--- +name: Credentials SNMPv2 Read +rest_endpoint: /dna/intent/api/v2/global-credential +get_from_all: true +id_from_query_path: response.snmpV2cRead +put_id_include_path: snmpV2cRead.0 +doc_category: Network Settings +attributes: + - model_name: description + data_path: snmpV2cRead.0 + response_data_path: description + type: String + id: true + description: The description of the SNMPv2 credentials + example: My SNMPv2 read credentials + - model_name: readCommunity + data_path: snmpV2cRead.0 + response_data_path: readCommunity + type: String + mandatory: true + write_only: true + description: Read community + example: community1 + \ No newline at end of file diff --git a/gen/definitions/credentials_snmpv2_write.yaml b/gen/definitions/credentials_snmpv2_write.yaml new file mode 100644 index 00000000..caefb72c --- /dev/null +++ b/gen/definitions/credentials_snmpv2_write.yaml @@ -0,0 +1,24 @@ +--- +name: Credentials SNMPv2 Write +rest_endpoint: /dna/intent/api/v2/global-credential +get_from_all: true +id_from_query_path: response.snmpV2cWrite +put_id_include_path: snmpV2cWrite.0 +doc_category: Network Settings +attributes: + - model_name: description + data_path: snmpV2cWrite.0 + response_data_path: description + type: String + id: true + description: The description of the SNMPv2 credentials + example: My SNMPv2 write credentials + - model_name: writeCommunity + data_path: snmpV2cWrite.0 + response_data_path: writeCommunity + type: String + mandatory: true + write_only: true + description: Write community + example: community1 + \ No newline at end of file diff --git a/gen/definitions/credentials_snmpv3.yaml b/gen/definitions/credentials_snmpv3.yaml new file mode 100644 index 00000000..149b19de --- /dev/null +++ b/gen/definitions/credentials_snmpv3.yaml @@ -0,0 +1,59 @@ +--- +name: Credentials SNMPv3 +rest_endpoint: /dna/intent/api/v2/global-credential +get_from_all: true +id_from_query_path: response.snmpV3 +put_id_include_path: snmpV3.0 +skip_minimum_test: true # using PUT always returns an error as of v2.3.7.3 +doc_category: Network Settings +attributes: + - model_name: description + data_path: snmpV3.0 + response_data_path: description + type: String + id: true + description: The description of the SNMPv3 credentials + example: My SNMPv3 credentials + - model_name: username + data_path: snmpV3.0 + response_data_path: username + type: String + mandatory: true + description: Username + example: user1 + - model_name: privacyType + data_path: snmpV3.0 + response_data_path: privacyType + type: String + enum_values: [AES128, AES192, AES256] + description: Privacy type + example: AES128 + - model_name: privacyPassword + data_path: snmpV3.0 + response_data_path: privacyPassword + type: String + write_only: true + description: Privacy password + example: password1 + - model_name: authType + data_path: snmpV3.0 + response_data_path: authType + type: String + enum_values: [SHA, MD5] + description: Authentication type + example: SHA + - model_name: authPassword + data_path: snmpV3.0 + response_data_path: authPassword + type: String + write_only: true + description: Authentication password + example: password1 + - model_name: snmpMode + data_path: snmpV3.0 + response_data_path: snmpMode + type: String + mandatory: true + enum_values: [AUTHPRIV, AUTHNOPRIV, NOAUTHNOPRIV] + description: SNMP mode + example: AUTHPRIV \ No newline at end of file diff --git a/gen/definitions/floor.yaml b/gen/definitions/floor.yaml new file mode 100644 index 00000000..2df59bbd --- /dev/null +++ b/gen/definitions/floor.yaml @@ -0,0 +1,64 @@ +--- +name: Floor +rest_endpoint: /dna/intent/api/v1/site +get_rest_endpoint: /api/v1/dna-maps-service/domains +id_path: siteId +doc_category: Sites +attributes: + - model_name: type + type: String + value: floor + - model_name: name + data_path: site.floor + response_data_path: name + type: String + mandatory: true + description: The name of the floor + example: Floor1 + - model_name: parentName + data_path: site.floor + type: String + mandatory: true + write_only: true + description: The path of the parent building, e.g. `Global/Building1` + example: Global/Building1 + test_value: '"${catalystcenter_building.test.parent_name}/${catalystcenter_building.test.name}"' + - model_name: rfModel + data_path: site.floor + type: String + enum_values: ["Cubes And Walled Offices", "Drywall Office Only", "Indoor High Ceiling", "Outdoor Open Space"] + mandatory: true + write_only: true + description: The RF model + example: Drywall Office Only + - model_name: width + data_path: site.floor + response_data_path: geometry.width + type: Float64 + mandatory: true + description: Width + example: 30.5 + - model_name: length + data_path: site.floor + response_data_path: geometry.length + type: Float64 + mandatory: true + description: Length + example: 50.5 + - model_name: height + data_path: site.floor + response_data_path: geometry.height + type: Float64 + mandatory: true + description: Height + example: 3.5 +test_prerequisites: | + resource "catalystcenter_building" "test" { + name = "Building1" + parent_name = "Global" + country = "United States" + address = "150 W Tasman Dr, San Jose" + latitude = 37.338 + longitude = -121.832 + } + \ No newline at end of file diff --git a/gen/definitions/ip_pool.yaml b/gen/definitions/ip_pool.yaml new file mode 100644 index 00000000..5fe0a5fb --- /dev/null +++ b/gen/definitions/ip_pool.yaml @@ -0,0 +1,59 @@ +--- +name: IP Pool +rest_endpoint: /dna/intent/api/v1/global-pool +get_rest_endpoint: /api/v2/ippool +put_id_include_path: settings.ippool.0 +id_from_query_path: response +doc_category: Network Settings +attributes: + - model_name: ipPoolName + tf_name: name + data_path: settings.ippool.0 + response_data_path: response.ipPoolName + type: String + id: true + description: The name of the IP pool + example: MyPool1 + - model_name: IpAddressSpace + data_path: settings.ippool.0 + write_only: true + type: String + enum_values: [IPv4, IPv6] + default_value: IPv4 + description: IP address version + example: IPv4 + - model_name: type + data_path: settings.ippool.0 + type: String + write_only: true + enum_values: [Generic, Tunnel] + default_value: Generic + description: Choose `Tunnel` to assign IP addresses to site-to-site VPN for IPSec tunneling. Choose `Generic` for all other network types. + example: Generic + - model_name: ipPoolCidr + tf_name: ip_subnet + data_path: settings.ippool.0 + response_data_path: response.ipPoolCidr + type: String + mandatory: true + description: The IP subnet of the IP pool + example: 21.1.1.0/24 + - model_name: gateway + data_path: settings.ippool.0 + response_data_path: response.gateways.0 + type: String + description: The gateway for the IP pool + example: 21.1.1.1 + - model_name: dhcpServerIps + data_path: settings.ippool.0 + response_data_path: response.dhcpServerIps + type: StringList + description: List of DHCP Server IPs + example: 1.2.3.4 + - model_name: dnsServerIps + data_path: settings.ippool.0 + response_data_path: response.dnsServerIps + type: StringList + description: List of DNS Server IPs + example: 2.3.4.5 + diff --git a/gen/definitions/ip_pool_reservation.yaml b/gen/definitions/ip_pool_reservation.yaml new file mode 100644 index 00000000..1b38b95b --- /dev/null +++ b/gen/definitions/ip_pool_reservation.yaml @@ -0,0 +1,152 @@ +--- +name: IP Pool Reservation +rest_endpoint: /dna/intent/api/v1/reserve-ip-subpool +id_from_query_path: response +put_id_query_param: id +doc_category: Network Settings +attributes: + - model_name: siteId + type: String + query_param: true + description: The site ID + example: 5e6f7b3a-2b0b-4a7d-8b1c-0d4b1cd5e1b1 + test_value: catalystcenter_area.test.id + - model_name: name + response_model_name: groupName + response_data_path: response.0.groupName + type: String + id: true + description: The name of the IP pool reservation + example: MyRes1 + - model_name: type + type: String + mandatory: true + write_only: true + write_changes_only: true + enum_values: [Generic, LAN, WAN, management, service] + description: The type of the IP pool reservation + example: Generic + - model_name: ipv6AddressSpace + type: Bool + write_only: true + default_value: false + description: If the value is `false` only IPv4 input are required, otherwise both IPv6 and IPv4 are required + example: false + - model_name: ipv4GlobalPool + type: String + mandatory: true + write_only: true + write_changes_only: true + description: "IPv4 Global pool address with cidr, example: 175.175.0.0/16" + example: 172.32.0.0/16 + - model_name: ipv4Prefix + type: Bool + mandatory: true + write_only: true + write_changes_only: true + description: If this value is `true`, the `ipv4_prefix_length` attribute must be provided, if it is `false`, the `ipv4_total_host` attribute must be provided + example: true + - model_name: ipv4PrefixLength + type: Int64 + write_only: true + write_changes_only: true + description: The IPv4 prefix length is required when `ipv4_prefix` value is `true`. + example: 24 + minimum_test_value: 24 + - model_name: ipv4Subnet + type: String + write_only: true + write_changes_only: true + description: The IPv4 subnet + example: 172.32.1.0 + minimum_test_value: '"172.32.1.0"' + - model_name: ipv4GateWay + tf_name: ipv4_gateway + type: String + write_only: true + description: The gateway for the IP pool reservation + example: 172.32.1.1 + - model_name: ipv4DhcpServers + type: StringList + write_only: true + description: List of DHCP Server IPs + example: 1.2.3.4 + - model_name: ipv4DnsServers + type: StringList + write_only: true + description: List of DNS Server IPs + example: 2.3.4.5 + - model_name: ipv6GlobalPool + type: String + write_only: true + description: "IPv6 Global pool address with cidr, example: 2001:db8:85a3::/64" + example: 2001:db8:85a3::/64 + exclude_test: true + - model_name: ipv6Prefix + type: Bool + write_only: true + description: If this value is `true`, the `ipv6_prefix_length` attribute must be provided, if it is `false`, the `ipv6_total_host` attribute must be provided + example: true + exclude_test: true + - model_name: ipv6PrefixLength + type: Int64 + write_only: true + description: The IPv6 prefix length is required when `ipv6_prefix` value is `true`. + example: 80 + exclude_test: true + - model_name: ipv6Subnet + type: String + write_only: true + description: The IPv6 subnet, for example `2001:db8:85a3:0:100::` + example: "2001:db8:85a3:0:100::" + exclude_test: true + - model_name: ipv6GateWay + tf_name: ipv6_gateway + type: String + write_only: true + description: The gateway for the IP pool reservation + example: "2001:db8:85a3:0:100::1" + exclude_test: true + - model_name: ipv6DhcpServers + type: StringList + write_only: true + description: List of DHCP Server IPs + example: "2001:db8::1234" + exclude_test: true + - model_name: ipv6DnsServers + type: StringList + write_only: true + description: List of DNS Server IPs + example: "2001:db8::1234" + exclude_test: true + - model_name: ipv4TotalHost + type: Int64 + write_only: true + description: The total number of IPv4 hosts + example: 100 + exclude_test: true + - model_name: ipv6TotalHost + type: Int64 + write_only: true + description: The total number of IPv6 hosts + example: 100 + exclude_test: true + - model_name: slaacSupport + type: Bool + write_only: true + description: Enable SLAAC support + example: true + exclude_test: true + +test_prerequisites: | + resource "catalystcenter_area" "test" { + name = "Area1" + parent_name = "Global" + depends_on = [catalystcenter_ip_pool.test] + } + + resource "catalystcenter_ip_pool" "test" { + name = "MyPool1" + ip_subnet = "172.32.0.0/16" + } + \ No newline at end of file diff --git a/gen/doc_category.go b/gen/doc_category.go new file mode 100644 index 00000000..22d0cb85 --- /dev/null +++ b/gen/doc_category.go @@ -0,0 +1,104 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +//go:build ignore + +package main + +import ( + "log" + "os" + "path/filepath" + "strings" + + "gopkg.in/yaml.v3" +) + +const ( + definitionsPath = "./gen/definitions/" +) + +type YamlConfig struct { + Name string `yaml:"name"` + DocCategory string `yaml:"doc_category"` +} + +var docPaths = []string{"./docs/data-sources/", "./docs/resources/"} + +var extraDocs = map[string]string{} + +func SnakeCase(s string) string { + var g []string + + p := strings.Fields(s) + + for _, value := range p { + g = append(g, strings.ToLower(value)) + } + return strings.Join(g, "_") +} + +func main() { + files, _ := os.ReadDir(definitionsPath) + configs := make([]YamlConfig, len(files)) + + // Load configs + for i, filename := range files { + yamlFile, err := os.ReadFile(filepath.Join(definitionsPath, filename.Name())) + if err != nil { + log.Fatalf("Error reading file: %v", err) + } + + config := YamlConfig{} + err = yaml.Unmarshal(yamlFile, &config) + if err != nil { + log.Fatalf("Error parsing yaml: %v", err) + } + configs[i] = config + } + + // Update doc category + for i := range configs { + for _, path := range docPaths { + filename := path + SnakeCase(configs[i].Name) + ".md" + content, err := os.ReadFile(filename) + if err != nil { + log.Fatalf("Error opening documentation: %v", err) + } + + cat := configs[i].DocCategory + s := string(content) + s = strings.ReplaceAll(s, `subcategory: ""`, `subcategory: "`+cat+`"`) + + os.WriteFile(filename, []byte(s), 0644) + } + } + + // Update extra doc categories + for doc, cat := range extraDocs { + for _, path := range docPaths { + filename := path + doc + ".md" + content, err := os.ReadFile(filename) + if err == nil { + s := string(content) + s = strings.ReplaceAll(s, `subcategory: ""`, `subcategory: "`+cat+`"`) + + os.WriteFile(filename, []byte(s), 0644) + } + } + } +} diff --git a/gen/generator.go b/gen/generator.go new file mode 100644 index 00000000..06853587 --- /dev/null +++ b/gen/generator.go @@ -0,0 +1,445 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +//go:build ignore + +package main + +import ( + "bufio" + "bytes" + "fmt" + "log" + "os" + "path" + "path/filepath" + "regexp" + "strings" + "text/template" + "unicode" + + "gopkg.in/yaml.v3" +) + +const ( + definitionsPath = "./gen/definitions/" + providerTemplate = "./gen/templates/provider.go" + providerLocation = "./internal/provider/provider.go" + changelogTemplate = "./gen/templates/changelog.md.tmpl" + changelogLocation = "./templates/guides/changelog.md.tmpl" + changelogOriginal = "./CHANGELOG.md" +) + +type t struct { + path string + prefix string + suffix string +} + +var templates = []t{ + { + path: "./gen/templates/model.go", + prefix: "./internal/provider/model_catalystcenter_", + suffix: ".go", + }, + { + path: "./gen/templates/data_source.go", + prefix: "./internal/provider/data_source_catalystcenter_", + suffix: ".go", + }, + { + path: "./gen/templates/data_source_test.go", + prefix: "./internal/provider/data_source_catalystcenter_", + suffix: "_test.go", + }, + { + path: "./gen/templates/resource.go", + prefix: "./internal/provider/resource_catalystcenter_", + suffix: ".go", + }, + { + path: "./gen/templates/resource_test.go", + prefix: "./internal/provider/resource_catalystcenter_", + suffix: "_test.go", + }, + { + path: "./gen/templates/data-source.tf", + prefix: "./examples/data-sources/catalystcenter_", + suffix: "/data-source.tf", + }, + { + path: "./gen/templates/resource.tf", + prefix: "./examples/resources/catalystcenter_", + suffix: "/resource.tf", + }, + { + path: "./gen/templates/import.sh", + prefix: "./examples/resources/catalystcenter_", + suffix: "/import.sh", + }, +} + +type YamlConfig struct { + Name string `yaml:"name"` + RestEndpoint string `yaml:"rest_endpoint"` + GetRestEndpoint string `yaml:"get_rest_endpoint"` + GetNoId bool `yaml:"get_no_id"` + GetFromAll bool `yaml:"get_from_all"` + NoDelete bool `yaml:"no_delete"` + PostUpdate bool `yaml:"post_update"` + RootList bool `yaml:"root_list"` + NoReadPrefix bool `yaml:"no_read_prefix"` + IdPath string `yaml:"id_path"` + IdFromQueryPath string `yaml:"id_from_query_path"` + IdQueryParam string `yaml:"id_query_param"` + PutIdIncludePath string `yaml:"put_id_include_path"` + PutIdQueryParam string `yaml:"put_id_query_param"` + DataSourceNameQuery bool `yaml:"data_source_name_query"` + MinimumVersion string `yaml:"minimum_version"` + DsDescription string `yaml:"ds_description"` + ResDescription string `yaml:"res_description"` + DocCategory string `yaml:"doc_category"` + ExcludeTest bool `yaml:"exclude_test"` + SkipMinimumTest bool `yaml:"skip_minimum_test"` + Attributes []YamlConfigAttribute `yaml:"attributes"` + TestTags []string `yaml:"test_tags"` + TestPrerequisites string `yaml:"test_prerequisites"` +} + +type YamlConfigAttribute struct { + ModelName string `yaml:"model_name"` + ResponseModelName string `yaml:"response_model_name"` + TfName string `yaml:"tf_name"` + Type string `yaml:"type"` + DataPath string `yaml:"data_path"` + ResponseDataPath string `yaml:"response_data_path"` + Id bool `yaml:"id"` + Reference bool `yaml:"reference"` + QueryParam bool `yaml:"query_param"` + Mandatory bool `yaml:"mandatory"` + WriteOnly bool `yaml:"write_only"` + WriteChangesOnly bool `yaml:"write_changes_only"` + ExcludeTest bool `yaml:"exclude_test"` + ExcludeExample bool `yaml:"exclude_example"` + Description string `yaml:"description"` + Example string `yaml:"example"` + EnumValues []string `yaml:"enum_values"` + MinList int64 `yaml:"min_list"` + MaxList int64 `yaml:"max_list"` + MinInt int64 `yaml:"min_int"` + MaxInt int64 `yaml:"max_int"` + MinFloat float64 `yaml:"min_float"` + MaxFloat float64 `yaml:"max_float"` + StringPatterns []string `yaml:"string_patterns"` + StringMinLength int64 `yaml:"string_min_length"` + StringMaxLength int64 `yaml:"string_max_length"` + DefaultValue string `yaml:"default_value"` + Value string `yaml:"value"` + ValueCondition string `yaml:"value_condition"` + TestValue string `yaml:"test_value"` + MinimumTestValue string `yaml:"minimum_test_value"` + TestTags []string `yaml:"test_tags"` + Attributes []YamlConfigAttribute `yaml:"attributes"` +} + +// Templating helper function to convert TF name to GO name +func ToGoName(s string) string { + var g []string + + p := strings.Split(s, "_") + + for _, value := range p { + g = append(g, strings.Title(value)) + } + s = strings.Join(g, "") + return s +} + +// Templating helper function to convert string to camel case +func CamelCase(s string) string { + var g []string + + s = strings.ReplaceAll(s, "-", " ") + p := strings.Fields(s) + + for _, value := range p { + g = append(g, strings.Title(value)) + } + return strings.Join(g, "") +} + +// Templating helper function to convert string to snake case +func SnakeCase(s string) string { + var g []string + + s = strings.ReplaceAll(s, "-", " ") + p := strings.Fields(s) + + for _, value := range p { + g = append(g, strings.ToLower(value)) + } + return strings.Join(g, "_") +} + +// Templating helper function to build a SJSON path +func BuildPath(s []string) string { + return strings.Join(s, ".") +} + +func contains(s []string, str string) bool { + for _, v := range s { + if v == str { + return true + } + } + return false +} + +// Templating helper function to return true if id included in attributes +func HasId(attributes []YamlConfigAttribute) bool { + for _, attr := range attributes { + if attr.Id { + return true + } + } + return false +} + +// Templating helper function to return true if reference included in attributes +func HasReference(attributes []YamlConfigAttribute) bool { + for _, attr := range attributes { + if attr.Reference { + return true + } + } + return false +} + +// Templating helper function to return true if query parameters included in attributes +func HasQueryParam(attributes []YamlConfigAttribute) bool { + for _, attr := range attributes { + if attr.QueryParam { + return true + } + } + return false +} + +// Templating helper function to return the ID attribute +func GetId(attributes []YamlConfigAttribute) YamlConfigAttribute { + for _, attr := range attributes { + if attr.Id { + return attr + } + } + return YamlConfigAttribute{} +} + +// Templating helper function to return the query parameter attribute +func GetQueryParam(attributes []YamlConfigAttribute) YamlConfigAttribute { + for _, attr := range attributes { + if attr.QueryParam { + return attr + } + } + return YamlConfigAttribute{} +} + +// Map of templating functions +var functions = template.FuncMap{ + "toGoName": ToGoName, + "camelCase": CamelCase, + "snakeCase": SnakeCase, + "sprintf": fmt.Sprintf, + "toLower": strings.ToLower, + "path": BuildPath, + "hasId": HasId, + "hasReference": HasReference, + "hasQueryParam": HasQueryParam, + "getId": GetId, + "getQueryParam": GetQueryParam, +} + +func augmentAttribute(attr *YamlConfigAttribute) { + if attr.TfName == "" { + var words []string + l := 0 + for s := attr.ModelName; s != ""; s = s[l:] { + l = strings.IndexFunc(s[1:], unicode.IsUpper) + 1 + if l <= 0 { + l = len(s) + } + words = append(words, strings.ToLower(s[:l])) + } + attr.TfName = strings.Join(words, "_") + } + if attr.Type == "List" || attr.Type == "Set" { + for a := range attr.Attributes { + augmentAttribute(&attr.Attributes[a]) + } + } +} + +func augmentConfig(config *YamlConfig) { + for ia := range config.Attributes { + augmentAttribute(&config.Attributes[ia]) + } + if config.DsDescription == "" { + config.DsDescription = fmt.Sprintf("This data source can read the %s.", config.Name) + } + if config.ResDescription == "" { + name := strings.ToLower(config.Name) + if strings.HasPrefix(name, "a") || strings.HasPrefix(name, "e") || strings.HasPrefix(name, "i") || strings.HasPrefix(name, "o") || strings.HasPrefix(name, "u") { + config.ResDescription = fmt.Sprintf("This resource can manage an %s.", config.Name) + } else { + config.ResDescription = fmt.Sprintf("This resource can manage a %s.", config.Name) + } + } +} + +func getTemplateSection(content, name string) string { + scanner := bufio.NewScanner(strings.NewReader(content)) + result := "" + foundSection := false + beginRegex := regexp.MustCompile(`\/\/template:begin\s` + name + `$`) + endRegex := regexp.MustCompile(`\/\/template:end\s` + name + `$`) + for scanner.Scan() { + line := scanner.Text() + if !foundSection { + match := beginRegex.MatchString(line) + if match { + foundSection = true + result += line + "\n" + } + } else { + result += line + "\n" + match := endRegex.MatchString(line) + if match { + foundSection = false + } + } + } + return result +} + +func renderTemplate(templatePath, outputPath string, config interface{}) { + file, err := os.Open(templatePath) + if err != nil { + log.Fatalf("Error opening template: %v", err) + } + defer file.Close() + + // skip first line with 'build-ignore' directive for go files + scanner := bufio.NewScanner(file) + if strings.HasSuffix(templatePath, ".go") { + scanner.Scan() + } + var temp string + for scanner.Scan() { + temp = temp + scanner.Text() + "\n" + } + + template, err := template.New(path.Base(templatePath)).Funcs(functions).Parse(temp) + if err != nil { + log.Fatalf("Error parsing template: %v", err) + } + + output := new(bytes.Buffer) + err = template.Execute(output, config) + if err != nil { + log.Fatalf("Error executing template: %v", err) + } + + outputFile := filepath.Join(outputPath) + existingFile, err := os.Open(outputPath) + if err != nil { + os.MkdirAll(filepath.Dir(outputFile), 0755) + } else if strings.HasSuffix(templatePath, ".go") { + existingScanner := bufio.NewScanner(existingFile) + var newContent string + currentSectionName := "" + beginRegex := regexp.MustCompile(`\/\/template:begin\s(.*?)$`) + endRegex := regexp.MustCompile(`\/\/template:end\s(.*?)$`) + for existingScanner.Scan() { + line := existingScanner.Text() + if currentSectionName == "" { + matches := beginRegex.FindStringSubmatch(line) + if len(matches) > 1 && matches[1] != "" { + currentSectionName = matches[1] + } else { + newContent += line + "\n" + } + } else { + matches := endRegex.FindStringSubmatch(line) + if len(matches) > 1 && matches[1] == currentSectionName { + currentSectionName = "" + newSection := getTemplateSection(string(output.Bytes()), matches[1]) + newContent += newSection + } + } + } + output = bytes.NewBufferString(newContent) + } + // write to output file + f, err := os.Create(outputFile) + if err != nil { + log.Fatalf("Error creating output file: %v", err) + } + f.Write(output.Bytes()) +} + +func main() { + providerConfig := make([]string, 0) + + files, _ := os.ReadDir(definitionsPath) + configs := make([]YamlConfig, len(files)) + + // Load configs + for i, filename := range files { + yamlFile, err := os.ReadFile(filepath.Join(definitionsPath, filename.Name())) + if err != nil { + log.Fatalf("Error reading file: %v", err) + } + + config := YamlConfig{} + err = yaml.Unmarshal(yamlFile, &config) + if err != nil { + log.Fatalf("Error parsing yaml: %v", err) + } + configs[i] = config + } + + for i := range configs { + // Augment config + augmentConfig(&configs[i]) + + // Iterate over templates and render files + for _, t := range templates { + renderTemplate(t.path, t.prefix+SnakeCase(configs[i].Name)+t.suffix, configs[i]) + } + providerConfig = append(providerConfig, configs[i].Name) + } + + // render provider.go + renderTemplate(providerTemplate, providerLocation, providerConfig) + + changelog, err := os.ReadFile(changelogOriginal) + if err != nil { + log.Fatalf("Error reading changelog: %v", err) + } + renderTemplate(changelogTemplate, changelogLocation, string(changelog)) +} diff --git a/gen/schema/schema.yaml b/gen/schema/schema.yaml new file mode 100644 index 00000000..ea4cf69e --- /dev/null +++ b/gen/schema/schema.yaml @@ -0,0 +1,59 @@ +--- +name: str() # Name of the resource +rest_endpoint: str() # REST endpoint path +get_rest_endpoint: str(required=False) # Override GET REST endpoint path +get_no_id: bool(required=False) # Set to true if the GET request does not require an ID +get_from_all: bool(required=False) # Set to true if GET does not support querying individual objects +no_delete: bool(required=False) # Set to true if the DELETE request is not supported +post_update: bool(required=False) # Set to true if the POST request is used for update +root_list: bool(required=False) # Set to true if the root element of the data structure is a list +no_read_prefix: bool(required=False) # Set to true if it is an Open API endpoint put the response is not embeeded into a "response" element +id_path: str(required=False) # Path to the ID in the response (use "." to access nested elements) +id_from_query_path: str(required=False) # Specify path to ID container if ID is not included in POST response and needs to be resolved via separate GET request +id_query_param: str(required=False) # Query parameter used to specify the ID +put_id_include_path: str(required=False) # If PUT needs to have specific JSON path where ID should be inserted +put_id_query_param: str(required=False) # If PUT needs to have specific query parameter where ID should be inserted +data_source_name_query: bool(required=False) # Set to true if the data source supports name queries +minimum_version: str(required=False) # Define a minimum supported version +ds_description: str(required=False) # Define a data source description +res_description: str(required=False) # Define a resource description +doc_category: str(required=False) # Define a documentation category +skip_minimum_test: bool(required=False) # Do not perform a "minimum" (only mandatory attributes) test +attributes: list(include('attribute'), required=False) # List of attributes +test_tags: list(str(), required=False) # List of test tags, tests are only executed if an environment variable with one of these tags is configured +test_prerequisites: str(required=False) # HCL code that is included in the acceptance tests to define prerequisites +--- +attribute: + model_name: str(required=False) # Name of the attribute in the model (payload) + response_model_name: str(required=False) # Name of the attribute in the model (response payload) + tf_name: str(required=False) # Name of the attribute in the Terraform resource, by default derived from model_name + type: enum('String', 'Int64', 'Float64', 'Bool', 'List', 'Set', 'StringList', required=False) # Type of the attribute + data_path: str(required=False) # Path to the attribute in the model structure + response_data_path: str(required=False) # Path to the attribute in the response model structure + id: bool(required=False) # Set to true if the attribute is part of the ID + reference: bool(required=False) # Set to true if the attribute is a reference being used in the path (URL) of the REST endpoint + query_param: bool(required=False) # Set to true if the attribute is a query parameter and being used for GET, POST and PUT requests + mandatory: bool(required=False) # Set to true if the attribute is mandatory + write_only: bool(required=False) # Set to true if the attribute is write-only, meaning we cannot read the value + write_changes_only: bool(required=False) # Set to true if the attribute should only be written (included in PUT payload) if it has changed + exclude_test: bool(required=False) # Exclude attribute from example (documentation) and acceptance test + exclude_example: bool(required=False) # Exclude attribute from acceptance test only (example/documentation is still generated) + description: str(required=False) # Attribute description + example: any(str(), int(), bool(), num(), required=False) # Example value for documentation, also used for acceptance test + enum_values: list(str(), required=False) # List of enum values, only relevant if type is "String" + min_list: int(required=False) # Minimum number of elements in a list, only relevant if type is "List" + max_list: int(required=False) # Maximum number of elements in a list, only relevant if type is "List" + min_int: int(required=False) # Minimum value of an integer, only relevant if type is "Int64" + max_int: int(required=False) # Maximum value of an integer, only relevant if type is "Int64" + min_float: num(required=False) # Minimum value of a float, only relevant if type is "Float" + max_float: num(required=False) # Maximum value of a float, only relevant if type is "Float" + string_patterns: list(str(), required=False) # List of regular expressions that the string must match, only relevant if type is "String" + string_min_length: int(required=False) # Minimum length of a string, only relevant if type is "String" + string_max_length: int(required=False) # Maximum length of a string, only relevant if type is "String" + default_value: any(str(), int(), bool(), required=False) # Default value for the attribute + value: any(str(), int(), bool(), required=False) # Hardcoded value for the attribute + value_condition: str(required=False) # GO condition that must be true for the value to be included in the payload, only relevant if "value" is set + test_value: str(required=False) # Value used for acceptance test + minimum_test_value: any(str(), int(), bool(), num(), required=False) # Value used for "minimum" resource acceptance test + test_tags: list(str(), required=False) # List of test tags, attribute is only included in acceptance tests if an environment variable with one of these tags is configured + attributes: list(include('attribute'), required=False) # List of attributes, only relevant if type is "List" or "Set" diff --git a/gen/templates/changelog.md.tmpl b/gen/templates/changelog.md.tmpl new file mode 100644 index 00000000..dc53abff --- /dev/null +++ b/gen/templates/changelog.md.tmpl @@ -0,0 +1,10 @@ +--- +subcategory: "Guides" +page_title: "Changelog" +description: |- + Changelog +--- + +# Changelog + +{{.}} diff --git a/gen/templates/data-source.tf b/gen/templates/data-source.tf new file mode 100644 index 00000000..b713b7ad --- /dev/null +++ b/gen/templates/data-source.tf @@ -0,0 +1,8 @@ +data "catalystcenter_{{snakeCase .Name}}" "example" { + id = "{{$id := false}}{{range .Attributes}}{{if .Id}}{{$id = true}}{{.Example}}{{end}}{{end}}{{if not $id}}76d24097-41c4-4558-a4d0-a8c07ac08470{{end}}" + {{- range .Attributes}} + {{- if .Reference}} + {{.TfName}} = {{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}} + {{- end}} + {{- end}} +} diff --git a/gen/templates/data_source.go b/gen/templates/data_source.go new file mode 100644 index 00000000..53358209 --- /dev/null +++ b/gen/templates/data_source.go @@ -0,0 +1,233 @@ +//go:build ignore +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &{{camelCase .Name}}DataSource{} + _ datasource.DataSourceWithConfigure = &{{camelCase .Name}}DataSource{} +) + +func New{{camelCase .Name}}DataSource() datasource.DataSource { + return &{{camelCase .Name}}DataSource{} +} + +type {{camelCase .Name}}DataSource struct { + client *cc.Client +} + +func (d *{{camelCase .Name}}DataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_{{snakeCase .Name}}" +} + +{{- $nameQuery := .DataSourceNameQuery}} + +func (d *{{camelCase .Name}}DataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "{{.DsDescription}}", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + {{- if not .DataSourceNameQuery}} + Required: true, + {{- else}} + Optional: true, + Computed: true, + {{- end}} + }, + {{- range .Attributes}} + {{- if not .Value}} + "{{.TfName}}": schema.{{if or (eq .Type "List") (eq .Type "Set")}}{{.Type}}Nested{{else if eq .Type "StringList"}}List{{else}}{{.Type}}{{end}}Attribute{ + MarkdownDescription: "{{.Description}}", + {{- if eq .Type "StringList"}} + ElementType: types.StringType, + {{- end}} + {{- if or .Reference .QueryParam}} + Required: true, + {{- else}} + {{- if and (eq .ModelName "name") ($nameQuery)}} + Optional: true, + {{- end}} + Computed: true, + {{- end}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + {{- range .Attributes}} + {{- if not .Value}} + "{{.TfName}}": schema.{{if or (eq .Type "List") (eq .Type "Set")}}{{.Type}}Nested{{else if eq .Type "StringList"}}List{{else}}{{.Type}}{{end}}Attribute{ + MarkdownDescription: "{{.Description}}", + {{- if eq .Type "StringList"}} + ElementType: types.StringType, + {{- end}} + Computed: true, + {{- if or (eq .Type "List") (eq .Type "Set")}} + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + {{- range .Attributes}} + {{- if not .Value}} + "{{.TfName}}": schema.{{if or (eq .Type "List") (eq .Type "Set")}}{{.Type}}Nested{{else if eq .Type "StringList"}}List{{else}}{{.Type}}{{end}}Attribute{ + MarkdownDescription: "{{.Description}}", + {{- if eq .Type "StringList"}} + ElementType: types.StringType, + {{- end}} + Computed: true, + {{- if or (eq .Type "List") (eq .Type "Set")}} + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + {{- range .Attributes}} + {{- if not .Value}} + "{{.TfName}}": schema.{{if or (eq .Type "List") (eq .Type "Set")}}{{.Type}}Nested{{else if eq .Type "StringList"}}List{{else}}{{.Type}}{{end}}Attribute{ + MarkdownDescription: "{{.Description}}", + {{- if eq .Type "StringList"}} + ElementType: types.StringType, + {{- end}} + Computed: true, + }, + {{- end}} + {{- end}} + }, + }, + {{- end}} + }, + {{- end}} + {{- end}} + }, + }, + {{- end}} + }, + {{- end}} + {{- end}} + }, + }, + {{- end}} + }, + {{- end}} + {{- end}} + }, + } +} + +{{- if .DataSourceNameQuery}} +func (d *{{camelCase .Name}}DataSource) ConfigValidators(ctx context.Context) []datasource.ConfigValidator { + return []datasource.ConfigValidator{ + datasourcevalidator.ExactlyOneOf( + path.MatchRoot("id"), + path.MatchRoot("name"), + ), + } +} +{{- end}} + +func (d *{{camelCase .Name}}DataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} +//template:end model + +//template:begin read +func (d *{{camelCase .Name}}DataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config {{camelCase .Name}} + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + {{- if .DataSourceNameQuery}} + if config.Id.IsNull() && !config.Name.IsNull() { + res, err := d.client.Get(config.getPath()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve objects, got error: %s", err)) + return + } + if value := res.Get("response"); len(value.Array()) > 0 { + value.ForEach(func(k, v gjson.Result) bool { + if config.Name.ValueString() == v.Get("name").String() { + config.Id = types.StringValue(v.Get("id").String()) + tflog.Debug(ctx, fmt.Sprintf("%s: Found object with name '%v', id: %v", config.Id.String(), config.Name.ValueString(), config.Id.String())) + return false + } + return true + }) + } + + if config.Id.IsNull() { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to find object with name: %s", config.Name.ValueString())) + return + } + } + {{- end}} + + params := "" + {{- if .IdQueryParam}} + params += "?{{.IdQueryParam}}=" + config.Id.ValueString() + {{- else if hasQueryParam .Attributes}} + {{- $queryParam := getQueryParam .Attributes}} + params += "?{{$queryParam.ModelName}}=" + config.{{toGoName $queryParam.TfName}}.Value{{$queryParam.Type}}() + {{- else if and (not .GetNoId) (not .GetFromAll)}} + params += "/" + config.Id.ValueString() + {{- end}} + res, err := d.client.Get({{if .GetRestEndpoint}}"{{.GetRestEndpoint}}"{{else}}config.getPath(){{end}} + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + + {{- if .GetFromAll}} + res = res.Get("{{.IdFromQueryPath}}.#(id==\"" + config.Id.ValueString() + "\")") + {{- end}} + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} +//template:end read diff --git a/gen/templates/data_source_test.go b/gen/templates/data_source_test.go new file mode 100644 index 00000000..ba399bab --- /dev/null +++ b/gen/templates/data_source_test.go @@ -0,0 +1,229 @@ +//go:build ignore +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCc{{camelCase .Name}}(t *testing.T) { + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} && {{end}}os.Getenv("{{$e}}") == ""{{end}} { + t.Skip("skipping test, set environment variable {{range $i, $e := .TestTags}}{{if $i}} or {{end}}{{$e}}{{end}}") + } + {{- end}} + var checks []resource.TestCheckFunc + {{- $name := .Name }} + {{- range .Attributes}} + {{- if and (not .WriteOnly) (not .ExcludeTest) (not .Value) (not .TestValue)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- $list := .TfName }} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + {{- range .Attributes}} + {{- if and (not .WriteOnly) (not .ExcludeTest) (not .Value) (not .TestValue)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- $clist := .TfName }} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + {{- range .Attributes}} + {{- if and (not .WriteOnly) (not .ExcludeTest) (not .Value) (not .TestValue)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- $cclist := .TfName }} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + {{- range .Attributes}} + {{- if and (not .WriteOnly) (not .ExcludeTest) (not .Value) (not .TestValue)}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{$clist}}.0.{{$cclist}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + } + {{- else}} + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{$clist}}.0.{{$cclist}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + {{- end}} + {{- end}} + {{- end}} + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{$clist}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + } + {{- else}} + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{$clist}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + {{- end}} + {{- end}} + {{- end}} + {{- end}} + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + } + {{- else}} + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + {{- end}} + {{- end}} + {{- end}} + {{- end}} + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_{{snakeCase $name}}.test", "{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + } + {{- else}} + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_{{snakeCase $name}}.test", "{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + {{- end}} + {{- end}} + {{- end}} + {{- end}} + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: {{if .TestPrerequisites}}testAccDataSourceCc{{camelCase .Name}}PrerequisitesConfig+{{end}}testAccDataSourceCc{{camelCase .Name}}Config(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} +//template:end testAccDataSource + +//template:begin testPrerequisites +{{- if .TestPrerequisites}} +const testAccDataSourceCc{{camelCase .Name}}PrerequisitesConfig = ` +{{.TestPrerequisites}} +` +{{- end}} +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCc{{camelCase .Name}}Config() string { + config := `resource "catalystcenter_{{snakeCase $name}}" "test" {` + "\n" + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .Value)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + config += ` {{.TfName}} = [{` + "\n" + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .Value)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + config += ` {{.TfName}} = [{` + "\n" + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .Value)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + config += ` {{.TfName}} = [{` + "\n" + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .Value)}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + config += ` }]` + "\n" + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + {{- end}} + config += ` }]` + "\n" + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + {{- end}} + config += ` }]` + "\n" + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + {{- end}} + config += `}` + "\n" + + config += ` + data "catalystcenter_{{snakeCase .Name}}" "test" { + id = catalystcenter_{{snakeCase $name}}.test.id + {{- range .Attributes}} + {{- if or .Reference .QueryParam}} + {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}} + {{- end}} + {{- end}} + } + ` + return config +} +//template:end testAccDataSourceConfig diff --git a/gen/templates/import.sh b/gen/templates/import.sh new file mode 100644 index 00000000..5be885fb --- /dev/null +++ b/gen/templates/import.sh @@ -0,0 +1 @@ +terraform import catalystcenter_{{snakeCase .Name}}.example "{{$id := false}}{{range .Attributes}}{{if .Id}}{{$id = true}}{{.Example}}{{end}}{{end}}{{if not $id}}4b0b7a80-44c0-4bf2-bab5-fc24b4e0a17e{{end}}" diff --git a/gen/templates/model.go b/gen/templates/model.go new file mode 100644 index 00000000..e10031e1 --- /dev/null +++ b/gen/templates/model.go @@ -0,0 +1,549 @@ +//go:build ignore +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strconv" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) +//template:end imports + +//template:begin types +{{- $name := camelCase .Name}} +type {{camelCase .Name}} struct { + Id types.String `tfsdk:"id"` +{{- range .Attributes}} +{{- if not .Value}} +{{- if or (eq .Type "List") (eq .Type "Set")}} + {{toGoName .TfName}} []{{$name}}{{toGoName .TfName}} `tfsdk:"{{.TfName}}"` +{{- else if eq .Type "StringList"}} + {{toGoName .TfName}} types.List `tfsdk:"{{.TfName}}"` +{{- else}} + {{toGoName .TfName}} types.{{.Type}} `tfsdk:"{{.TfName}}"` +{{- end}} +{{- end}} +{{- end}} +} + +{{ range .Attributes}} +{{- if not .Value}} +{{- $childName := toGoName .TfName}} +{{- if or (eq .Type "List") (eq .Type "Set")}} +type {{$name}}{{toGoName .TfName}} struct { +{{- range .Attributes}} +{{- if not .Value}} +{{- if or (eq .Type "List") (eq .Type "Set")}} + {{toGoName .TfName}} []{{$name}}{{$childName}}{{toGoName .TfName}} `tfsdk:"{{.TfName}}"` +{{- else if eq .Type "StringList"}} + {{toGoName .TfName}} types.List `tfsdk:"{{.TfName}}"` +{{- else}} + {{toGoName .TfName}} types.{{.Type}} `tfsdk:"{{.TfName}}"` +{{- end}} +{{- end}} +{{- end}} +} +{{- end}} +{{- end}} +{{ end}} + +{{ range .Attributes}} +{{- if not .Value}} +{{- $childName := toGoName .TfName}} +{{- if or (eq .Type "List") (eq .Type "Set")}} +{{ range .Attributes}} +{{- if not .Value}} +{{- $childChildName := toGoName .TfName}} +{{- if or (eq .Type "List") (eq .Type "Set")}} +type {{$name}}{{$childName}}{{toGoName .TfName}} struct { +{{- range .Attributes}} +{{- if not .Value}} +{{- if or (eq .Type "List") (eq .Type "Set")}} + {{toGoName .TfName}} []{{$name}}{{$childName}}{{$childChildName}}{{toGoName .TfName}} `tfsdk:"{{.TfName}}"` +{{- else if eq .Type "StringList"}} + {{toGoName .TfName}} types.List `tfsdk:"{{.TfName}}"` +{{- else}} + {{toGoName .TfName}} types.{{.Type}} `tfsdk:"{{.TfName}}"` +{{- end}} +{{- end}} +{{- end}} +} +{{- end}} +{{- end}} +{{- end}} +{{- end}} +{{- end}} +{{ end}} + +{{ range .Attributes}} +{{- if not .Value}} +{{- $childName := toGoName .TfName}} +{{- if or (eq .Type "List") (eq .Type "Set")}} +{{ range .Attributes}} +{{- if not .Value}} +{{- $childChildName := toGoName .TfName}} +{{- if or (eq .Type "List") (eq .Type "Set")}} +{{ range .Attributes}} +{{- if not .Value}} +{{- if or (eq .Type "List") (eq .Type "Set")}} +type {{$name}}{{$childName}}{{$childChildName}}{{toGoName .TfName}} struct { +{{- range .Attributes}} +{{- if not .Value}} +{{- if eq .Type "StringList"}} + {{toGoName .TfName}} types.List `tfsdk:"{{.TfName}}"` +{{- else}} + {{toGoName .TfName}} types.{{.Type}} `tfsdk:"{{.TfName}}"` +{{- end}} +{{- end}} +{{- end}} +} +{{- end}} +{{- end}} +{{- end}} +{{- end}} +{{- end}} +{{- end}} +{{- end}} +{{- end}} +{{ end}} +//template:end types + +//template:begin getPath +func (data {{camelCase .Name}}) getPath() string { + {{- if hasReference .Attributes}} + return fmt.Sprintf("{{.RestEndpoint}}"{{range .Attributes}}{{if .Reference}}, data.{{toGoName .TfName}}.Value{{.Type}}(){{end}}{{end}}) + {{- else}} + return "{{.RestEndpoint}}" + {{- end}} +} +//template:end getPath + +//template:begin toBody +func (data {{camelCase .Name}}) toBody(ctx context.Context, state {{camelCase .Name}}) string { + {{- if .RootList}} + body := "[]" + {{- else}} + body := "" + {{- end}} + {{- if .PutIdIncludePath}} + if data.Id.ValueString() != "" { + body, _ = sjson.Set(body, "{{ .PutIdIncludePath}}.id", data.Id.ValueString()) + } + {{- end}} + {{- range .Attributes}} + {{- if .Value}} + {{- if .ValueCondition}} + if {{.ValueCondition}} { + body, _ = sjson.Set(body, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{if eq .Type "String"}}"{{end}}{{.Value}}{{if eq .Type "String"}}"{{end}}) + } + {{- else}} + body, _ = sjson.Set(body, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{if eq .Type "String"}}"{{end}}{{.Value}}{{if eq .Type "String"}}"{{end}}) + {{- end}} + {{- else if and (not .Reference) (not .QueryParam)}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if !data.{{toGoName .TfName}}.IsNull() {{if .WriteChangesOnly}}&& data.{{toGoName .TfName}} != state.{{toGoName .TfName}}{{end}} { + body, _ = sjson.Set(body, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", data.{{toGoName .TfName}}.Value{{.Type}}()) + } + {{- else if eq .Type "StringList"}} + if !data.{{toGoName .TfName}}.IsNull() { + var values []string + data.{{toGoName .TfName}}.ElementsAs(ctx, &values, false) + body, _ = sjson.Set(body, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", values) + } + {{- else if or (eq .Type "List") (eq .Type "Set")}} + if len(data.{{toGoName .TfName}}) > 0 { + body, _ = sjson.Set(body, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", []interface{}{}) + for _, item := range data.{{toGoName .TfName}} { + itemBody := "" + {{- range .Attributes}} + {{- if .Value}} + {{- if .ValueCondition}} + if {{.ValueCondition}} { + itemBody, _ = sjson.Set(itemBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{if eq .Type "String"}}"{{end}}{{.Value}}{{if eq .Type "String"}}"{{end}}) + } + {{- else}} + itemBody, _ = sjson.Set(itemBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{if eq .Type "String"}}"{{end}}{{.Value}}{{if eq .Type "String"}}"{{end}}) + {{- end}} + {{- else if not .Reference}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if !item.{{toGoName .TfName}}.IsNull() { + itemBody, _ = sjson.Set(itemBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", item.{{toGoName .TfName}}.Value{{.Type}}()) + } + {{- else if eq .Type "StringList"}} + if !item.{{toGoName .TfName}}.IsNull() { + var values []string + item.{{toGoName .TfName}}.ElementsAs(ctx, &values, false) + itemBody, _ = sjson.Set(itemBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", values) + } + {{- else if or (eq .Type "List") (eq .Type "Set")}} + if len(item.{{toGoName .TfName}}) > 0 { + itemBody, _ = sjson.Set(itemBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", []interface{}{}) + for _, childItem := range item.{{toGoName .TfName}} { + itemChildBody := "" + {{- range .Attributes}} + {{- if .Value}} + {{- if .ValueCondition}} + if {{.ValueCondition}} { + itemChildBody, _ = sjson.Set(itemChildBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{if eq .Type "String"}}"{{end}}{{.Value}}{{if eq .Type "String"}}"{{end}}) + } + {{- else}} + itemChildBody, _ = sjson.Set(itemChildBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{if eq .Type "String"}}"{{end}}{{.Value}}{{if eq .Type "String"}}"{{end}}) + {{- end}} + {{- else if not .Reference}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if !childItem.{{toGoName .TfName}}.IsNull() { + itemChildBody, _ = sjson.Set(itemChildBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", childItem.{{toGoName .TfName}}.Value{{.Type}}()) + } + {{- else if eq .Type "StringList"}} + if !childItem.{{toGoName .TfName}}.IsNull() { + var values []string + childItem.{{toGoName .TfName}}.ElementsAs(ctx, &values, false) + itemChildBody, _ = sjson.Set(itemChildBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", values) + } + {{- else if or (eq .Type "List") (eq .Type "Set")}} + if len(childItem.{{toGoName .TfName}}) > 0 { + itemChildBody, _ = sjson.Set(itemChildBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", []interface{}{}) + for _, childChildItem := range childItem.{{toGoName .TfName}} { + itemChildChildBody := "" + {{- range .Attributes}} + {{- if .Value}} + {{- if .ValueCondition}} + if {{.ValueCondition}} { + itemChildChildBody, _ = sjson.Set(itemChildChildBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{if eq .Type "String"}}"{{end}}{{.Value}}{{if eq .Type "String"}}"{{end}}) + } + {{- else}} + itemChildChildBody, _ = sjson.Set(itemChildChildBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{if eq .Type "String"}}"{{end}}{{.Value}}{{if eq .Type "String"}}"{{end}}) + {{- end}} + {{- else if not .Reference}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if !childChildItem.{{toGoName .TfName}}.IsNull() { + itemChildChildBody, _ = sjson.Set(itemChildChildBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", childChildItem.{{toGoName .TfName}}.Value{{.Type}}()) + } + {{- else if eq .Type "StringList"}} + if !childChildItem.{{toGoName .TfName}}.IsNull() { + var values []string + childChildItem.{{toGoName .TfName}}.ElementsAs(ctx, &values, false) + itemChildChildBody, _ = sjson.Set(itemChildChildBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", values) + } + {{- end}} + {{- end}} + {{- end}} + itemChildBody, _ = sjson.SetRaw(itemChildBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}.-1", itemChildChildBody) + } + } + {{- end}} + {{- end}} + {{- end}} + itemBody, _ = sjson.SetRaw(itemBody, "{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}.-1", itemChildBody) + } + } + {{- end}} + {{- end}} + {{- end}} + body, _ = sjson.SetRaw(body, "{{if .DataPath}}{{.DataPath}}.{{end}}{{if .ModelName}}{{.ModelName}}.{{end}}-1", itemBody) + } + } + {{- end}} + {{- end}} + {{- end}} + return body +} +//template:end toBody + +//template:begin fromBody +func (data *{{camelCase .Name}}) fromBody(ctx context.Context, res gjson.Result) { + {{- range .Attributes}} + {{- if and (not .Value) (not .WriteOnly) (not .Reference) (not .QueryParam)}} + {{- $cname := toGoName .TfName}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if value := res.Get("{{if .ResponseDataPath}}{{.ResponseDataPath}}{{else}}response.{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}{{end}}"); value.Exists() { + data.{{toGoName .TfName}} = types.{{.Type}}Value(value.{{if eq .Type "Int64"}}Int{{else if eq .Type "Float64"}}Float{{else}}{{.Type}}{{end}}()) + } else { + {{- if .DefaultValue}} + data.{{toGoName .TfName}} = types.{{.Type}}Value({{if eq .Type "String"}}"{{end}}{{.DefaultValue}}{{if eq .Type "String"}}"{{end}}) + {{- else}} + data.{{toGoName .TfName}} = types.{{.Type}}Null() + {{- end}} + } + {{- else if eq .Type "StringList"}} + if value := res.Get("{{if .ResponseDataPath}}{{.ResponseDataPath}}{{else}}response.{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}{{end}}"); value.Exists() { + data.{{toGoName .TfName}} = helpers.GetStringList(value.Array()) + } else { + data.{{toGoName .TfName}} = types.ListNull(types.StringType) + } + {{- else if or (eq .Type "List") (eq .Type "Set")}} + if value := res{{if .ModelName}}.Get("{{if .ResponseDataPath}}{{.ResponseDataPath}}{{else}}response.{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}{{end}}"){{end}}; value.Exists() { + data.{{toGoName .TfName}} = make([]{{$name}}{{toGoName .TfName}}, 0) + value.ForEach(func(k, v gjson.Result) bool { + item := {{$name}}{{toGoName .TfName}}{} + {{- range .Attributes}} + {{- $ccname := toGoName .TfName}} + {{- if and (not .Value) (not .WriteOnly) (not .Reference)}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if cValue := v.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); cValue.Exists() { + item.{{toGoName .TfName}} = types.{{.Type}}Value(cValue.{{if eq .Type "Int64"}}Int{{else if eq .Type "Float64"}}Float{{else}}{{.Type}}{{end}}()) + } else { + {{- if .DefaultValue}} + item.{{toGoName .TfName}} = types.{{.Type}}Value({{if eq .Type "String"}}"{{end}}{{.DefaultValue}}{{if eq .Type "String"}}"{{end}}) + {{- else}} + item.{{toGoName .TfName}} = types.{{.Type}}Null() + {{- end}} + } + {{- else if eq .Type "StringList"}} + if cValue := v.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); cValue.Exists() { + item.{{toGoName .TfName}} = helpers.GetStringList(cValue.Array()) + } else { + item.{{toGoName .TfName}} = types.ListNull(types.StringType) + } + {{- else if or (eq .Type "List") (eq .Type "Set")}} + if cValue := v.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); cValue.Exists() { + item.{{toGoName .TfName}} = make([]{{$name}}{{$cname}}{{toGoName .TfName}}, 0) + cValue.ForEach(func(ck, cv gjson.Result) bool { + cItem := {{$name}}{{$cname}}{{toGoName .TfName}}{} + {{- range .Attributes}} + {{- if and (not .Value) (not .WriteOnly) (not .Reference)}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if ccValue := cv.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); ccValue.Exists() { + cItem.{{toGoName .TfName}} = types.{{.Type}}Value(ccValue.{{if eq .Type "Int64"}}Int{{else if eq .Type "Float64"}}Float{{else}}{{.Type}}{{end}}()) + } else { + {{- if .DefaultValue}} + cItem.{{toGoName .TfName}} = types.{{.Type}}Value({{if eq .Type "String"}}"{{end}}{{.DefaultValue}}{{if eq .Type "String"}}"{{end}}) + {{- else}} + cItem.{{toGoName .TfName}} = types.{{.Type}}Null() + {{- end}} + } + {{- else if eq .Type "StringList"}} + if ccValue := cv.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); ccValue.Exists() { + cItem.{{toGoName .TfName}} = helpers.GetStringList(ccValue.Array()) + } else { + cItem.{{toGoName .TfName}} = types.ListNull(types.StringType) + } + {{- else if or (eq .Type "List") (eq .Type "Set")}} + if ccValue := cv.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); ccValue.Exists() { + cItem.{{toGoName .TfName}} = make([]{{$name}}{{$cname}}{{$ccname}}{{toGoName .TfName}}, 0) + ccValue.ForEach(func(cck, ccv gjson.Result) bool { + ccItem := {{$name}}{{$cname}}{{$ccname}}{{toGoName .TfName}}{} + {{- range .Attributes}} + {{- if and (not .Value) (not .WriteOnly) (not .Reference)}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if cccValue := ccv.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); cccValue.Exists() { + ccItem.{{toGoName .TfName}} = types.{{.Type}}Value(cccValue.{{if eq .Type "Int64"}}Int{{else if eq .Type "Float64"}}Float{{else}}{{.Type}}{{end}}()) + } else { + {{- if .DefaultValue}} + ccItem.{{toGoName .TfName}} = types.{{.Type}}Value({{if eq .Type "String"}}"{{end}}{{.DefaultValue}}{{if eq .Type "String"}}"{{end}}) + {{- else}} + ccItem.{{toGoName .TfName}} = types.{{.Type}}Null() + {{- end}} + } + {{- else if eq .Type "StringList"}} + if cccValue := ccv.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); cccValue.Exists() { + ccItem.{{toGoName .TfName}} = helpers.GetStringList(cccValue.Array()) + } else { + ccItem.{{toGoName .TfName}} = types.ListNull(types.StringType) + } + {{- end}} + {{- end}} + {{- end}} + cItem.{{toGoName .TfName}} = append(cItem.{{toGoName .TfName}}, ccItem) + return true + }) + } + {{- end}} + {{- end}} + {{- end}} + item.{{toGoName .TfName}} = append(item.{{toGoName .TfName}}, cItem) + return true + }) + } + {{- end}} + {{- end}} + {{- end}} + data.{{toGoName .TfName}} = append(data.{{toGoName .TfName}}, item) + return true + }) + } + {{- end}} + {{- end}} + {{- end}} +} +//template:end fromBody + +//template:begin updateFromBody +func (data *{{camelCase .Name}}) updateFromBody(ctx context.Context, res gjson.Result) { + {{- range .Attributes}} + {{- if and (not .Value) (not .WriteOnly) (not .Reference) (not .QueryParam)}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if value := res.Get("{{if .ResponseDataPath}}{{.ResponseDataPath}}{{else}}response.{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}{{end}}"); value.Exists() && !data.{{toGoName .TfName}}.IsNull() { + data.{{toGoName .TfName}} = types.{{.Type}}Value(value.{{if eq .Type "Int64"}}Int{{else if eq .Type "Float64"}}Float{{else}}{{.Type}}{{end}}()) + } else {{if .DefaultValue}}if data.{{toGoName .TfName}}.Value{{.Type}}() != {{if eq .Type "String"}}"{{end}}{{.DefaultValue}}{{if eq .Type "String"}}"{{end}} {{end}}{ + data.{{toGoName .TfName}} = types.{{.Type}}Null() + } + {{- else if eq .Type "StringList"}} + if value := res.Get("{{if .ResponseDataPath}}{{.ResponseDataPath}}{{else}}response.{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}{{end}}"); value.Exists() && !data.{{toGoName .TfName}}.IsNull() { + data.{{toGoName .TfName}} = helpers.GetStringList(value.Array()) + } else { + data.{{toGoName .TfName}} = types.ListNull(types.StringType) + } + {{- else if or (eq .Type "List") (eq .Type "Set")}} + {{- $list := (toGoName .TfName)}} + for i := range data.{{toGoName .TfName}} { + keys := [...]string{ {{$noId := not (hasId .Attributes)}}{{range .Attributes}}{{if or .Id $noId}}{{if or (eq .Type "Int64") (eq .Type "Bool") (eq .Type "String")}}"{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{end}}{{end}}{{end}} } + keyValues := [...]string{ {{$noId := not (hasId .Attributes)}}{{range .Attributes}}{{if or .Id $noId}}{{if eq .Type "Int64"}}strconv.FormatInt(data.{{$list}}[i].{{toGoName .TfName}}.ValueInt64(), 10), {{else if eq .Type "Bool"}}strconv.FormatBool(data.{{$list}}[i].{{toGoName .TfName}}.ValueBool()), {{else if eq .Type "String"}}data.{{$list}}[i].{{toGoName .TfName}}.Value{{.Type}}(), {{end}}{{end}}{{end}} } + + var r gjson.Result + res.{{if .ModelName}}Get("{{if .ResponseDataPath}}{{.ResponseDataPath}}{{else}}response.{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}{{end}}").{{end}}ForEach( + func(_, v gjson.Result) bool { + found := false + for ik := range keys { + if v.Get(keys[ik]).String() == keyValues[ik] { + found = true + continue + } + found = false + break + } + if found { + r = v + return false + } + return true + }, + ) + + {{- range .Attributes}} + {{- if and (not .Value) (not .WriteOnly) (not .Reference)}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if value := r.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); value.Exists() && !data.{{$list}}[i].{{toGoName .TfName}}.IsNull() { + data.{{$list}}[i].{{toGoName .TfName}} = types.{{.Type}}Value(value.{{if eq .Type "Int64"}}Int{{else if eq .Type "Float64"}}Float{{else}}{{.Type}}{{end}}()) + } else {{if .DefaultValue}}if data.{{$list}}[i].{{toGoName .TfName}}.Value{{.Type}}() != {{if eq .Type "String"}}"{{end}}{{.DefaultValue}}{{if eq .Type "String"}}"{{end}} {{end}}{ + data.{{$list}}[i].{{toGoName .TfName}} = types.{{.Type}}Null() + } + {{- else if eq .Type "StringList"}} + if value := r.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); value.Exists() && !data.{{$list}}[i].{{toGoName .TfName}}.IsNull() { + data.{{$list}}[i].{{toGoName .TfName}} = helpers.GetStringList(value.Array()) + } else { + data.{{$list}}[i].{{toGoName .TfName}} = types.ListNull(types.StringType) + } + {{- else if or (eq .Type "List") (eq .Type "Set")}} + {{- $clist := (toGoName .TfName)}} + for ci := range data.{{$list}}[i].{{toGoName .TfName}} { + keys := [...]string{ {{$noId := not (hasId .Attributes)}}{{range .Attributes}}{{if or .Id $noId}}{{if or (eq .Type "Int64") (eq .Type "Bool") (eq .Type "String")}}"{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{end}}{{end}}{{end}} } + keyValues := [...]string{ {{$noId := not (hasId .Attributes)}}{{range .Attributes}}{{if or .Id $noId}}{{if eq .Type "Int64"}}strconv.FormatInt(data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}}.ValueInt64(), 10), {{else if eq .Type "Bool"}}strconv.FormatBool(data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}}.ValueBool()), {{else if eq .Type "String"}}data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}}.Value{{.Type}}(), {{end}}{{end}}{{end}} } + + var cr gjson.Result + r.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}").ForEach( + func(_, v gjson.Result) bool { + found := false + for ik := range keys { + if v.Get(keys[ik]).String() == keyValues[ik] { + found = true + continue + } + found = false + break + } + if found { + cr = v + return false + } + return true + }, + ) + + {{- range .Attributes}} + {{- if and (not .Value) (not .WriteOnly) (not .Reference)}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if value := cr.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); value.Exists() && !data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}}.IsNull() { + data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}} = types.{{.Type}}Value(value.{{if eq .Type "Int64"}}Int{{else if eq .Type "Float64"}}Float{{else}}{{.Type}}{{end}}()) + } else {{if .DefaultValue}}if data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}}.Value{{.Type}}() != {{if eq .Type "String"}}"{{end}}{{.DefaultValue}}{{if eq .Type "String"}}"{{end}} {{end}}{ + data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}} = types.{{.Type}}Null() + } + {{- else if eq .Type "StringList"}} + if value := cr.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); value.Exists() && !data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}}.IsNull() { + data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}} = helpers.GetStringList(value.Array()) + } else { + data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}} = types.ListNull(types.StringType) + } + {{- else if or (eq .Type "List") (eq .Type "Set")}} + {{- $cclist := (toGoName .TfName)}} + for cci := range data.{{$list}}[i].{{$clist}}[ci].{{toGoName .TfName}} { + keys := [...]string{ {{$noId := not (hasId .Attributes)}}{{range .Attributes}}{{if or .Id $noId}}{{if or (eq .Type "Int64") (eq .Type "Bool") (eq .Type "String")}}"{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}", {{end}}{{end}}{{end}} } + keyValues := [...]string{ {{$noId := not (hasId .Attributes)}}{{range .Attributes}}{{if or .Id $noId}}{{if eq .Type "Int64"}}strconv.FormatInt(data.{{$list}}[i].{{$clist}}[ci].{{$cclist}}[cci].{{toGoName .TfName}}.ValueInt64(), 10), {{else if eq .Type "Bool"}}strconv.FormatBool(data.{{$list}}[i].{{$clist}}[ci].{{$cclist}}[cci].{{toGoName .TfName}}.ValueBool()), {{else if eq .Type "String"}}data.{{$list}}[i].{{$clist}}[ci].{{$cclist}}[cci].{{toGoName .TfName}}.Value{{.Type}}(), {{end}}{{end}}{{end}} } + + var ccr gjson.Result + cr.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}").ForEach( + func(_, v gjson.Result) bool { + found := false + for ik := range keys { + if v.Get(keys[ik]).String() == keyValues[ik] { + found = true + continue + } + found = false + break + } + if found { + ccr = v + return false + } + return true + }, + ) + + {{- range .Attributes}} + {{- if and (not .Value) (not .WriteOnly) (not .Reference)}} + {{- if or (eq .Type "String") (eq .Type "Int64") (eq .Type "Float64") (eq .Type "Bool")}} + if value := ccr.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); value.Exists() && !data.{{$list}}[i].{{$clist}}[ci].{{$cclist}}[cci].{{toGoName .TfName}}.IsNull() { + data.{{$list}}[i].{{$clist}}[ci].{{$cclist}}[cci].{{toGoName .TfName}} = types.{{.Type}}Value(value.{{if eq .Type "Int64"}}Int{{else if eq .Type "Float64"}}Float{{else}}{{.Type}}{{end}}()) + } else {{if .DefaultValue}}if data.{{$list}}[i].{{$clist}}[ci].{{$cclist}}[cci].{{toGoName .TfName}}.Value{{.Type}}() != {{if eq .Type "String"}}"{{end}}{{.DefaultValue}}{{if eq .Type "String"}}"{{end}} {{end}}{ + data.{{$list}}[i].{{$clist}}[ci].{{$cclist}}[cci].{{toGoName .TfName}} = types.{{.Type}}Null() + } + {{- else if eq .Type "StringList"}} + if value := ccr.Get("{{if .DataPath}}{{.DataPath}}.{{end}}{{.ModelName}}"); value.Exists() && !data.{{$list}}[i].{{$clist}}[ci].{{$cclist}}[cci].{{toGoName .TfName}}.IsNull() { + data.{{$list}}[i].{{$clist}}[ci].{{$cclist}}[cci].{{toGoName .TfName}} = helpers.GetStringList(value.Array()) + } else { + data.{{$list}}[i].{{$clist}}[ci].{{$cclist}}[cci].{{toGoName .TfName}} = types.ListNull(types.StringType) + } + {{- end}} + {{- end}} + {{- end}} + } + + {{- end}} + {{- end}} + {{- end}} + } + {{- end}} + {{- end}} + {{- end}} + } + {{- end}} + {{- end}} + {{- end}} +} +//template:end updateFromBody diff --git a/gen/templates/provider.go b/gen/templates/provider.go new file mode 100644 index 00000000..591035eb --- /dev/null +++ b/gen/templates/provider.go @@ -0,0 +1,266 @@ +//go:build ignore +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin provider +import ( + "context" + "os" + "strconv" + "sync" + + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/provider" + "github.com/hashicorp/terraform-plugin-framework/provider/schema" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/netascode/go-catalystcenter" +) + +// CcProvider defines the provider implementation. +type CcProvider struct { + // version is set to the provider version on release, "dev" when the + // provider is built and ran locally, and "test" when running acceptance + // testing. + version string +} + +// CcProviderModel describes the provider data model. +type CcProviderModel struct { + Username types.String `tfsdk:"username"` + Password types.String `tfsdk:"password"` + URL types.String `tfsdk:"url"` + Insecure types.Bool `tfsdk:"insecure"` + Retries types.Int64 `tfsdk:"retries"` +} + +// CcProviderData describes the data maintained by the provider. +type CcProviderData struct { + Client *cc.Client +} + +// Metadata returns the provider type name. +func (p *CcProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) { + resp.TypeName = "catalystcenter" + resp.Version = p.version +} + +func (p *CcProvider) Schema(ctx context.Context, req provider.SchemaRequest, resp *provider.SchemaResponse) { + resp.Schema = schema.Schema{ + Attributes: map[string]schema.Attribute{ + "username": schema.StringAttribute{ + MarkdownDescription: "Username for the Catalyst Center instance. This can also be set as the CC_USERNAME environment variable.", + Optional: true, + }, + "password": schema.StringAttribute{ + MarkdownDescription: "Password for the Catalyst Center instance. This can also be set as the CC_PASSWORD environment variable.", + Optional: true, + Sensitive: true, + }, + "url": schema.StringAttribute{ + MarkdownDescription: "URL of the Catalyst Center instance. This can also be set as the CC_URL environment variable.", + Optional: true, + }, + "insecure": schema.BoolAttribute{ + MarkdownDescription: "Allow insecure HTTPS client. This can also be set as the CC_INSECURE environment variable. Defaults to `true`.", + Optional: true, + }, + "retries": schema.Int64Attribute{ + MarkdownDescription: "Number of retries for REST API calls. This can also be set as the CC_RETRIES environment variable. Defaults to `3`.", + Optional: true, + Validators: []validator.Int64{ + int64validator.Between(0, 9), + }, + }, + }, + } +} + +func (p *CcProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { + // Retrieve provider data from configuration + var config CcProviderModel + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + // User must provide a username to the provider + var username string + if config.Username.IsUnknown() { + // Cannot connect to client with an unknown value + resp.Diagnostics.AddWarning( + "Unable to create client", + "Cannot use unknown value as username", + ) + return + } + + if config.Username.IsNull() { + username = os.Getenv("CC_USERNAME") + } else { + username = config.Username.ValueString() + } + + if username == "" { + // Error vs warning - empty value must stop execution + resp.Diagnostics.AddError( + "Unable to find username", + "Username cannot be an empty string", + ) + return + } + + // User must provide a password to the provider + var password string + if config.Password.IsUnknown() { + // Cannot connect to client with an unknown value + resp.Diagnostics.AddWarning( + "Unable to create client", + "Cannot use unknown value as password", + ) + return + } + + if config.Password.IsNull() { + password = os.Getenv("CC_PASSWORD") + } else { + password = config.Password.ValueString() + } + + if password == "" { + // Error vs warning - empty value must stop execution + resp.Diagnostics.AddError( + "Unable to find password", + "Password cannot be an empty string", + ) + return + } + + // User must provide a username to the provider + var url string + if config.URL.IsUnknown() { + // Cannot connect to client with an unknown value + resp.Diagnostics.AddWarning( + "Unable to create client", + "Cannot use unknown value as url", + ) + return + } + + if config.URL.IsNull() { + url = os.Getenv("CC_URL") + } else { + url = config.URL.ValueString() + } + + if url == "" { + // Error vs warning - empty value must stop execution + resp.Diagnostics.AddError( + "Unable to find url", + "URL cannot be an empty string", + ) + return + } + + var insecure bool + if config.Insecure.IsUnknown() { + // Cannot connect to client with an unknown value + resp.Diagnostics.AddWarning( + "Unable to create client", + "Cannot use unknown value as insecure", + ) + return + } + + if config.Insecure.IsNull() { + insecureStr := os.Getenv("CC_INSECURE") + if insecureStr == "" { + insecure = true + } else { + insecure, _ = strconv.ParseBool(insecureStr) + } + } else { + insecure = config.Insecure.ValueBool() + } + + var retries int64 + if config.Retries.IsUnknown() { + // Cannot connect to client with an unknown value + resp.Diagnostics.AddWarning( + "Unable to create client", + "Cannot use unknown value as retries", + ) + return + } + + if config.Retries.IsNull() { + retriesStr := os.Getenv("CC_RETRIES") + if retriesStr == "" { + retries = 3 + } else { + retries, _ = strconv.ParseInt(retriesStr, 0, 64) + } + } else { + retries = config.Retries.ValueInt64() + } + + // Create a new catalyst center client and set it to the provider client + c, err := cc.NewClient(url, username, password, cc.Insecure(insecure), cc.MaxRetries(int(retries))) + if err != nil { + resp.Diagnostics.AddError( + "Unable to create client", + "Unable to create catalyst center client:\n\n"+err.Error(), + ) + return + } + + data := CcProviderData{Client: &c} + resp.DataSourceData = &data + resp.ResourceData = &data +} + +func (p *CcProvider) Resources(ctx context.Context) []func() resource.Resource { + return []func() resource.Resource{ + {{- range .}} + New{{camelCase .}}Resource, + {{- end}} + } +} + +func (p *CcProvider) DataSources(ctx context.Context) []func() datasource.DataSource { + return []func() datasource.DataSource{ + {{- range .}} + New{{camelCase .}}DataSource, + {{- end}} + } +} + +func New(version string) func() provider.Provider { + return func() provider.Provider { + return &CcProvider{ + version: version, + } + } +} +//template:end provider diff --git a/gen/templates/resource.go b/gen/templates/resource.go new file mode 100644 index 00000000..2b92bd61 --- /dev/null +++ b/gen/templates/resource.go @@ -0,0 +1,557 @@ +//go:build ignore +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + "sync" + + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" + "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default" +) +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &{{camelCase .Name}}Resource{} +var _ resource.ResourceWithImportState = &{{camelCase .Name}}Resource{} + +func New{{camelCase .Name}}Resource() resource.Resource { + return &{{camelCase .Name}}Resource{} +} + +type {{camelCase .Name}}Resource struct { + client *cc.Client +} + +func (r *{{camelCase .Name}}Resource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_{{snakeCase .Name}}" +} + +func (r *{{camelCase .Name}}Resource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("{{.ResDescription}}").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + {{- range .Attributes}} + {{- if not .Value}} + "{{.TfName}}": schema.{{if or (eq .Type "List") (eq .Type "Set")}}{{.Type}}Nested{{else if eq .Type "StringList"}}List{{else}}{{.Type}}{{end}}Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("{{.Description}}") + {{- if len .EnumValues -}} + .AddStringEnumDescription({{range .EnumValues}}"{{.}}", {{end}}) + {{- end -}} + {{- if or (ne .MinInt 0) (ne .MaxInt 0) -}} + .AddIntegerRangeDescription({{.MinInt}}, {{.MaxInt}}) + {{- end -}} + {{- if or (ne .MinFloat 0.0) (ne .MaxFloat 0.0) -}} + .AddFloatRangeDescription({{.MinFloat}}, {{.MaxFloat}}) + {{- end -}} + {{- if .DefaultValue -}} + .AddDefaultValueDescription("{{.DefaultValue}}") + {{- end -}} + .String, + {{- if eq .Type "StringList"}} + ElementType: types.StringType, + {{- end}} + {{- if or .Id .Reference .Mandatory}} + Required: true, + {{- else}} + Optional: true, + {{- end}} + {{- if len .DefaultValue}} + Computed: true, + {{- end}} + {{- if len .EnumValues}} + Validators: []validator.String{ + stringvalidator.OneOf({{range .EnumValues}}"{{.}}", {{end}}), + }, + {{- else if or (len .StringPatterns) (ne .StringMinLength 0) (ne .StringMaxLength 0) }} + Validators: []validator.String{ + {{- if or (ne .StringMinLength 0) (ne .StringMaxLength 0)}} + stringvalidator.LengthBetween({{.StringMinLength}}, {{.StringMaxLength}}), + {{- end}} + {{- range .StringPatterns}} + stringvalidator.RegexMatches(regexp.MustCompile(`{{.}}`), ""), + {{- end}} + }, + {{- else if or (ne .MinInt 0) (ne .MaxInt 0)}} + Validators: []validator.Int64{ + int64validator.Between({{.MinInt}}, {{.MaxInt}}), + }, + {{- else if or (ne .MinFloat 0.0) (ne .MaxFloat 0.0)}} + Validators: []validator.Float64{ + float64validator.Between({{.MinFloat}}, {{.MaxFloat}}), + }, + {{- end}} + {{- if and (len .DefaultValue) (eq .Type "Int64")}} + Default: int64default.StaticInt64({{.DefaultValue}}), + {{- else if and (len .DefaultValue) (eq .Type "Bool")}} + Default: booldefault.StaticBool({{.DefaultValue}}), + {{- else if and (len .DefaultValue) (eq .Type "String")}} + Default: stringdefault.StaticString("{{.DefaultValue}}"), + {{- end}} + {{- if or .Id .Reference}} + PlanModifiers: []planmodifier.{{.Type}}{ + {{snakeCase .Type}}planmodifier.RequiresReplace(), + }, + {{- end}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + {{- range .Attributes}} + {{- if not .Value}} + "{{.TfName}}": schema.{{if or (eq .Type "List") (eq .Type "Set")}}{{.Type}}Nested{{else if eq .Type "StringList"}}List{{else}}{{.Type}}{{end}}Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("{{.Description}}") + {{- if len .EnumValues -}} + .AddStringEnumDescription({{range .EnumValues}}"{{.}}", {{end}}) + {{- end -}} + {{- if or (ne .MinInt 0) (ne .MaxInt 0) -}} + .AddIntegerRangeDescription({{.MinInt}}, {{.MaxInt}}) + {{- end -}} + {{- if or (ne .MinFloat 0.0) (ne .MaxFloat 0.0) -}} + .AddFloatRangeDescription({{.MinFloat}}, {{.MaxFloat}}) + {{- end -}} + {{- if .DefaultValue -}} + .AddDefaultValueDescription("{{.DefaultValue}}") + {{- end -}} + .String, + {{- if eq .Type "StringList"}} + ElementType: types.StringType, + {{- end}} + {{- if or .Id .Reference .Mandatory}} + Required: true, + {{- else}} + Optional: true, + {{- end}} + {{- if len .DefaultValue}} + Computed: true, + {{- end}} + {{- if len .EnumValues}} + Validators: []validator.String{ + stringvalidator.OneOf({{range .EnumValues}}"{{.}}", {{end}}), + }, + {{- else if or (len .StringPatterns) (ne .StringMinLength 0) (ne .StringMaxLength 0) }} + Validators: []validator.String{ + {{- if or (ne .StringMinLength 0) (ne .StringMaxLength 0)}} + stringvalidator.LengthBetween({{.StringMinLength}}, {{.StringMaxLength}}), + {{- end}} + {{- range .StringPatterns}} + stringvalidator.RegexMatches(regexp.MustCompile(`{{.}}`), ""), + {{- end}} + }, + {{- else if or (ne .MinInt 0) (ne .MaxInt 0)}} + Validators: []validator.Int64{ + int64validator.Between({{.MinInt}}, {{.MaxInt}}), + }, + {{- else if or (ne .MinFloat 0.0) (ne .MaxFloat 0.0)}} + Validators: []validator.Float64{ + float64validator.Between({{.MinFloat}}, {{.MaxFloat}}), + }, + {{- end}} + {{- if and (len .DefaultValue) (eq .Type "Int64")}} + Default: int64default.StaticInt64({{.DefaultValue}}), + {{- else if and (len .DefaultValue) (eq .Type "Bool")}} + Default: booldefault.StaticBool({{.DefaultValue}}), + {{- else if and (len .DefaultValue) (eq .Type "String")}} + Default: stringdefault.StaticString("{{.DefaultValue}}"), + {{- end}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + {{- range .Attributes}} + {{- if not .Value}} + "{{.TfName}}": schema.{{if or (eq .Type "List") (eq .Type "Set")}}{{.Type}}Nested{{else if eq .Type "StringList"}}List{{else}}{{.Type}}{{end}}Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("{{.Description}}") + {{- if len .EnumValues -}} + .AddStringEnumDescription({{range .EnumValues}}"{{.}}", {{end}}) + {{- end -}} + {{- if or (ne .MinInt 0) (ne .MaxInt 0) -}} + .AddIntegerRangeDescription({{.MinInt}}, {{.MaxInt}}) + {{- end -}} + {{- if or (ne .MinFloat 0.0) (ne .MaxFloat 0.0) -}} + .AddFloatRangeDescription({{.MinFloat}}, {{.MaxFloat}}) + {{- end -}} + {{- if .DefaultValue -}} + .AddDefaultValueDescription("{{.DefaultValue}}") + {{- end -}} + .String, + {{- if eq .Type "StringList"}} + ElementType: types.StringType, + {{- end}} + {{- if or .Id .Reference .Mandatory}} + Required: true, + {{- else}} + Optional: true, + {{- end}} + {{- if len .DefaultValue}} + Computed: true, + {{- end}} + {{- if len .EnumValues}} + Validators: []validator.String{ + stringvalidator.OneOf({{range .EnumValues}}"{{.}}", {{end}}), + }, + {{- else if or (len .StringPatterns) (ne .StringMinLength 0) (ne .StringMaxLength 0) }} + Validators: []validator.String{ + {{- if or (ne .StringMinLength 0) (ne .StringMaxLength 0)}} + stringvalidator.LengthBetween({{.StringMinLength}}, {{.StringMaxLength}}), + {{- end}} + {{- range .StringPatterns}} + stringvalidator.RegexMatches(regexp.MustCompile(`{{.}}`), ""), + {{- end}} + }, + {{- else if or (ne .MinInt 0) (ne .MaxInt 0)}} + Validators: []validator.Int64{ + int64validator.Between({{.MinInt}}, {{.MaxInt}}), + }, + {{- else if or (ne .MinFloat 0.0) (ne .MaxFloat 0.0)}} + Validators: []validator.Float64{ + float64validator.Between({{.MinFloat}}, {{.MaxFloat}}), + }, + {{- end}} + {{- if and (len .DefaultValue) (eq .Type "Int64")}} + Default: int64default.StaticInt64({{.DefaultValue}}), + {{- else if and (len .DefaultValue) (eq .Type "Bool")}} + Default: booldefault.StaticBool({{.DefaultValue}}), + {{- else if and (len .DefaultValue) (eq .Type "String")}} + Default: stringdefault.StaticString("{{.DefaultValue}}"), + {{- end}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + {{- range .Attributes}} + {{- if not .Value}} + "{{.TfName}}": schema.{{if or (eq .Type "List") (eq .Type "Set")}}{{.Type}}Nested{{else if eq .Type "StringList"}}List{{else}}{{.Type}}{{end}}Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("{{.Description}}") + {{- if len .EnumValues -}} + .AddStringEnumDescription({{range .EnumValues}}"{{.}}", {{end}}) + {{- end -}} + {{- if or (ne .MinInt 0) (ne .MaxInt 0) -}} + .AddIntegerRangeDescription({{.MinInt}}, {{.MaxInt}}) + {{- end -}} + {{- if or (ne .MinFloat 0.0) (ne .MaxFloat 0.0) -}} + .AddFloatRangeDescription({{.MinFloat}}, {{.MaxFloat}}) + {{- end -}} + {{- if .DefaultValue -}} + .AddDefaultValueDescription("{{.DefaultValue}}") + {{- end -}} + .String, + {{- if eq .Type "StringList"}} + ElementType: types.StringType, + {{- end}} + {{- if or .Id .Reference .Mandatory}} + Required: true, + {{- else}} + Optional: true, + {{- end}} + {{- if len .DefaultValue}} + Computed: true, + {{- end}} + {{- if len .EnumValues}} + Validators: []validator.String{ + stringvalidator.OneOf({{range .EnumValues}}"{{.}}", {{end}}), + }, + {{- else if or (len .StringPatterns) (ne .StringMinLength 0) (ne .StringMaxLength 0) }} + Validators: []validator.String{ + {{- if or (ne .StringMinLength 0) (ne .StringMaxLength 0)}} + stringvalidator.LengthBetween({{.StringMinLength}}, {{.StringMaxLength}}), + {{- end}} + {{- range .StringPatterns}} + stringvalidator.RegexMatches(regexp.MustCompile(`{{.}}`), ""), + {{- end}} + }, + {{- else if or (ne .MinInt 0) (ne .MaxInt 0)}} + Validators: []validator.Int64{ + int64validator.Between({{.MinInt}}, {{.MaxInt}}), + }, + {{- else if or (ne .MinFloat 0.0) (ne .MaxFloat 0.0)}} + Validators: []validator.Float64{ + float64validator.Between({{.MinFloat}}, {{.MaxFloat}}), + }, + {{- end}} + {{- if and (len .DefaultValue) (eq .Type "Int64")}} + Default: int64default.StaticInt64({{.DefaultValue}}), + {{- else if and (len .DefaultValue) (eq .Type "Bool")}} + Default: booldefault.StaticBool({{.DefaultValue}}), + {{- else if and (len .DefaultValue) (eq .Type "String")}} + Default: stringdefault.StaticString("{{.DefaultValue}}"), + {{- end}} + }, + {{- end}} + {{- end}} + }, + }, + {{- if or (ne .MinList 0) (ne .MaxList 0)}} + Validators: []validator.List{ + {{- if ne .MinList 0}} + listvalidator.SizeAtLeast({{.MinList}}), + {{- end}} + {{- if ne .MaxList 0}} + listvalidator.SizeAtMost({{.MaxList}}), + {{- end}} + }, + {{- end}} + {{- end}} + }, + {{- end}} + {{- end}} + }, + }, + {{- if or (ne .MinList 0) (ne .MaxList 0)}} + Validators: []validator.List{ + {{- if ne .MinList 0}} + listvalidator.SizeAtLeast({{.MinList}}), + {{- end}} + {{- if ne .MaxList 0}} + listvalidator.SizeAtMost({{.MaxList}}), + {{- end}} + }, + {{- end}} + {{- end}} + }, + {{- end}} + {{- end}} + }, + }, + {{- if or (ne .MinList 0) (ne .MaxList 0)}} + Validators: []validator.List{ + {{- if ne .MinList 0}} + listvalidator.SizeAtLeast({{.MinList}}), + {{- end}} + {{- if ne .MaxList 0}} + listvalidator.SizeAtMost({{.MaxList}}), + {{- end}} + }, + {{- end}} + {{- end}} + }, + {{- end}} + {{- end}} + }, + } +} + +func (r *{{camelCase .Name}}Resource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} +//template:end model + +//template:begin create +func (r *{{camelCase .Name}}Resource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan {{camelCase .Name}} + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, {{camelCase .Name}}{}) + + params := "" + {{- if hasQueryParam .Attributes}} + {{- $queryParam := getQueryParam .Attributes}} + params += "/" + plan.{{toGoName $queryParam.TfName}}.Value{{$queryParam.Type}}() + {{- end}} + res, err := r.client.Post(plan.getPath() + params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + {{- if .IdPath}} + plan.Id = types.StringValue(res.Get("{{.IdPath}}").String()) + {{- else if .IdFromQueryPath}} + {{- $id := getId .Attributes}} + params = "" + {{- if hasQueryParam .Attributes}} + {{- $queryParam := getQueryParam .Attributes}} + params += "?{{$queryParam.ModelName}}=" + plan.{{toGoName $queryParam.TfName}}.Value{{$queryParam.Type}}() + {{- end}} + res, err = r.client.Get({{if .GetRestEndpoint}}"{{.GetRestEndpoint}}"{{else}}plan.getPath(){{end}} + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("{{.IdFromQueryPath}}.#({{if $id.ResponseModelName}}{{$id.ResponseModelName}}{{else}}{{$id.ModelName}}{{end}}==\""+ plan.{{toGoName $id.TfName}}.Value{{$id.Type}}() +"\").id").String()) + {{- end}} + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} +//template:end create + +//template:begin read +func (r *{{camelCase .Name}}Resource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state {{camelCase .Name}} + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + {{- if .IdQueryParam}} + params += "?{{.IdQueryParam}}=" + state.Id.ValueString() + {{- else if hasQueryParam .Attributes}} + {{- $queryParam := getQueryParam .Attributes}} + params += "?{{$queryParam.ModelName}}=" + state.{{toGoName $queryParam.TfName}}.Value{{$queryParam.Type}}() + {{- else if and (not .GetNoId) (not .GetFromAll)}} + params += "/" + state.Id.ValueString() + {{- end}} + res, err := r.client.Get({{if .GetRestEndpoint}}"{{.GetRestEndpoint}}"{{else}}state.getPath(){{end}} + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + + {{- if .GetFromAll}} + res = res.Get("{{.IdFromQueryPath}}.#(id==\"" + state.Id.ValueString() + "\")") + {{- end}} + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} +//template:end read + +//template:begin update +func (r *{{camelCase .Name}}Resource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state {{camelCase .Name}} + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + {{- if hasQueryParam .Attributes}} + {{- $queryParam := getQueryParam .Attributes}} + params += "/" + plan.{{toGoName $queryParam.TfName}}.Value{{$queryParam.Type}}() + {{- end}} + {{- if .PutIdQueryParam}} + params += "?{{.PutIdQueryParam}}=" + plan.Id.ValueString() + {{- end}} + {{if .PostUpdate}} + res, err := r.client.Post(plan.getPath() + params, body) + {{- else if hasQueryParam .Attributes}} + res, err := r.client.Put(plan.getPath() + params, body) + {{- else}} + res, err := r.client.Put(plan.getPath() + "/" + plan.Id.ValueString() + params, body) + {{- end}} + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} +//template:end update + +//template:begin delete +func (r *{{camelCase .Name}}Resource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state {{camelCase .Name}} + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + + {{- if not .NoDelete}} + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + {{- end}} + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} +//template:end delete + +//template:begin import +func (r *{{camelCase .Name}}Resource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} +//template:end import diff --git a/gen/templates/resource.tf b/gen/templates/resource.tf new file mode 100644 index 00000000..80cdd0fe --- /dev/null +++ b/gen/templates/resource.tf @@ -0,0 +1,43 @@ +resource "catalystcenter_{{snakeCase .Name}}" "example" { +{{- range .Attributes}} +{{- if and (not .ExcludeTest) (not .ExcludeExample) (not .Value)}} +{{- if or (eq .Type "List") (eq .Type "Set")}} + {{.TfName}} = [ + { + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .ExcludeExample) (not .Value)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{.TfName}} = [ + { + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .ExcludeExample) (not .Value)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{.TfName}} = [ + { + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .ExcludeExample) (not .Value)}} + {{.TfName}} = {{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}} + {{- end}} + {{- end}} + } + ] + {{- else}} + {{.TfName}} = {{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}} + {{- end}} + {{- end}} + {{- end}} + } + ] + {{- else}} + {{.TfName}} = {{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}} + {{- end}} + {{- end}} + {{- end}} + } + ] +{{- else}} + {{.TfName}} = {{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}} +{{- end}} +{{- end}} +{{- end}} +} diff --git a/gen/templates/resource_test.go b/gen/templates/resource_test.go new file mode 100644 index 00000000..282d4b6c --- /dev/null +++ b/gen/templates/resource_test.go @@ -0,0 +1,318 @@ +//go:build ignore +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) +//template:end imports + +//template:begin testAcc +func TestAccCc{{camelCase .Name}}(t *testing.T) { + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} && {{end}}os.Getenv("{{$e}}") == ""{{end}} { + t.Skip("skipping test, set environment variable {{range $i, $e := .TestTags}}{{if $i}} or {{end}}{{$e}}{{end}}") + } + {{- end}} + var checks []resource.TestCheckFunc + {{- $name := .Name }} + {{- range .Attributes}} + {{- if and (not .WriteOnly) (not .ExcludeTest) (not .Value) (not .TestValue)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- $list := .TfName }} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + {{- range .Attributes}} + {{- if and (not .WriteOnly) (not .ExcludeTest) (not .Value) (not .TestValue)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- $clist := .TfName }} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + {{- range .Attributes}} + {{- if and (not .WriteOnly) (not .ExcludeTest) (not .Value) (not .TestValue)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- $cclist := .TfName }} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + {{- range .Attributes}} + {{- if and (not .WriteOnly) (not .ExcludeTest) (not .Value) (not .TestValue)}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{$clist}}.0.{{$cclist}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + } + {{- else}} + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{$clist}}.0.{{$cclist}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + {{- end}} + {{- end}} + {{- end}} + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{$clist}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + } + {{- else}} + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{$clist}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + {{- end}} + {{- end}} + {{- end}} + {{- end}} + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + } + {{- else}} + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_{{snakeCase $name}}.test", "{{$list}}.0.{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + {{- end}} + {{- end}} + {{- end}} + {{- end}} + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_{{snakeCase $name}}.test", "{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + } + {{- else}} + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_{{snakeCase $name}}.test", "{{.TfName}}{{if eq .Type "StringList"}}.0{{end}}", "{{.Example}}")) + {{- end}} + {{- end}} + {{- end}} + {{- end}} + + var steps []resource.TestStep + {{- if not .SkipMinimumTest}} + if os.Getenv("SKIP_MINIMUM_TEST") == "" { + steps = append(steps, resource.TestStep{ + Config: {{if .TestPrerequisites}}testAccCc{{camelCase .Name}}PrerequisitesConfig+{{end}}testAccCc{{camelCase .Name}}Config_minimum(), + }) + } + {{- end}} + steps = append(steps, resource.TestStep{ + Config: {{if .TestPrerequisites}}testAccCc{{camelCase .Name}}PrerequisitesConfig+{{end}}testAccCc{{camelCase .Name}}Config_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + {{- if and (not (hasReference .Attributes)) (not (hasQueryParam .Attributes))}} + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_{{snakeCase $name}}.test", + ImportState: true, + }) + {{- end}} + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} +//template:end testAcc + +//template:begin testPrerequisites +{{- if .TestPrerequisites}} +const testAccCc{{camelCase .Name}}PrerequisitesConfig = ` +{{.TestPrerequisites}} +` +{{- end}} +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCc{{camelCase .Name}}Config_minimum() string { + config := `resource "catalystcenter_{{snakeCase $name}}" "test" {` + "\n" + {{- range .Attributes}} + {{- if or .Id .Reference .Mandatory .MinimumTestValue .QueryParam}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + config += ` {{.TfName}} = [{` + "\n" + {{- range .Attributes}} + {{- if or .Id .Reference .Mandatory .MinimumTestValue}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + config += ` {{.TfName}} = [{` + "\n" + {{- range .Attributes}} + {{- if or .Id .Reference .Mandatory .MinimumTestValue}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + config += ` {{.TfName}} = [{` + "\n" + {{- range .Attributes}} + {{- if or .Id .Reference .Mandatory .MinimumTestValue}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .MinimumTestValue}}{{.MinimumTestValue}}{{else if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .MinimumTestValue}}{{.MinimumTestValue}}{{else if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + config += ` }]` + "\n" + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .MinimumTestValue}}{{.MinimumTestValue}}{{else if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .MinimumTestValue}}{{.MinimumTestValue}}{{else if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + {{- end}} + config += ` }]` + "\n" + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .MinimumTestValue}}{{.MinimumTestValue}}{{else if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .MinimumTestValue}}{{.MinimumTestValue}}{{else if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + {{- end}} + config += ` }]` + "\n" + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .MinimumTestValue}}{{.MinimumTestValue}}{{else if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .MinimumTestValue}}{{.MinimumTestValue}}{{else if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + {{- end}} + config += `}` + "\n" + return config +} +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCc{{camelCase .Name}}Config_all() string { + config := `resource "catalystcenter_{{snakeCase $name}}" "test" {` + "\n" + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .Value)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + config += ` {{.TfName}} = [{` + "\n" + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .Value)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + config += ` {{.TfName}} = [{` + "\n" + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .Value)}} + {{- if or (eq .Type "List") (eq .Type "Set")}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + {{- end}} + config += ` {{.TfName}} = [{` + "\n" + {{- range .Attributes}} + {{- if and (not .ExcludeTest) (not .Value)}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + config += ` }]` + "\n" + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + {{- end}} + config += ` }]` + "\n" + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + {{- end}} + config += ` }]` + "\n" + {{- if len .TestTags}} + } + {{- end}} + {{- else}} + {{- if len .TestTags}} + if {{range $i, $e := .TestTags}}{{if $i}} || {{end}}os.Getenv("{{$e}}") != ""{{end}} { + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + } + {{- else}} + config += ` {{.TfName}} = {{if .TestValue}}{{.TestValue}}{{else}}{{if eq .Type "String"}}"{{.Example}}"{{else if eq .Type "StringList"}}["{{.Example}}"]{{else}}{{.Example}}{{end}}{{end}}` + "\n" + {{- end}} + {{- end}} + {{- end}} + {{- end}} + config += `}` + "\n" + return config +} +//template:end testAccConfigAll diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..9e181728 --- /dev/null +++ b/go.mod @@ -0,0 +1,82 @@ +module github.com/netascode/terraform-provider-catalystcenter + +go 1.19 + +require ( + github.com/hashicorp/terraform-plugin-docs v0.16.0 + github.com/hashicorp/terraform-plugin-framework v1.4.2 + github.com/hashicorp/terraform-plugin-framework-validators v0.12.0 + github.com/hashicorp/terraform-plugin-go v0.19.0 + github.com/hashicorp/terraform-plugin-log v0.9.0 + github.com/hashicorp/terraform-plugin-testing v1.5.1 + github.com/netascode/go-catalystcenter v0.1.0 + github.com/tidwall/gjson v1.17.0 + github.com/tidwall/sjson v1.2.5 + golang.org/x/tools v0.14.0 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/Masterminds/goutils v1.1.1 // indirect + github.com/Masterminds/semver/v3 v3.1.1 // indirect + github.com/Masterminds/sprig/v3 v3.2.2 // indirect + github.com/ProtonMail/go-crypto v0.0.0-20230717121422-5aa5874ade95 // indirect + github.com/agext/levenshtein v1.2.2 // indirect + github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect + github.com/armon/go-radix v1.0.0 // indirect + github.com/bgentry/speakeasy v0.1.0 // indirect + github.com/cloudflare/circl v1.3.3 // indirect + github.com/fatih/color v1.15.0 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/google/uuid v1.3.1 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-checkpoint v0.5.0 // indirect + 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-multierror v1.1.1 // indirect + github.com/hashicorp/go-plugin v1.5.2 // indirect + github.com/hashicorp/go-uuid v1.0.3 // indirect + github.com/hashicorp/go-version v1.6.0 // indirect + github.com/hashicorp/hc-install v0.6.0 // indirect + github.com/hashicorp/hcl/v2 v2.18.0 // indirect + github.com/hashicorp/logutils v1.0.0 // indirect + github.com/hashicorp/terraform-exec v0.19.0 // indirect + github.com/hashicorp/terraform-json v0.17.1 // indirect + github.com/hashicorp/terraform-plugin-sdk/v2 v2.29.0 // indirect + github.com/hashicorp/terraform-registry-address v0.2.2 // indirect + github.com/hashicorp/terraform-svchost v0.1.1 // indirect + github.com/hashicorp/yamux v0.1.1 // indirect + github.com/huandu/xstrings v1.3.2 // indirect + github.com/imdario/mergo v0.3.15 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mitchellh/cli v1.1.5 // 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 + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/mitchellh/reflectwalk v1.0.2 // indirect + github.com/oklog/run v1.1.0 // indirect + github.com/posener/complete v1.2.3 // indirect + github.com/russross/blackfriday v1.6.0 // indirect + github.com/shopspring/decimal v1.3.1 // indirect + github.com/spf13/cast v1.5.0 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.1 // indirect + github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect + github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect + github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect + github.com/zclconf/go-cty v1.14.0 // indirect + golang.org/x/crypto v0.14.0 // indirect + golang.org/x/exp v0.0.0-20230809150735-7b3493d9a819 // indirect + golang.org/x/mod v0.13.0 // indirect + golang.org/x/net v0.17.0 // indirect + golang.org/x/sys v0.13.0 // indirect + golang.org/x/text v0.13.0 // indirect + google.golang.org/appengine v1.6.7 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b // indirect + google.golang.org/grpc v1.59.0 // indirect + google.golang.org/protobuf v1.31.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..df7338e3 --- /dev/null +++ b/go.sum @@ -0,0 +1,284 @@ +dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= +github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= +github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc= +github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= +github.com/Masterminds/sprig/v3 v3.2.1/go.mod h1:UoaO7Yp8KlPnJIYWTFkMaqPUYKTfGFPhxNuwnnxkKlk= +github.com/Masterminds/sprig/v3 v3.2.2 h1:17jRggJu518dr3QaafizSXOjKYp94wKfABxUmyxvxX8= +github.com/Masterminds/sprig/v3 v3.2.2/go.mod h1:UoaO7Yp8KlPnJIYWTFkMaqPUYKTfGFPhxNuwnnxkKlk= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/ProtonMail/go-crypto v0.0.0-20230717121422-5aa5874ade95 h1:KLq8BE0KwCL+mmXnjLWEAOYO+2l2AE4YMmqG1ZpZHBs= +github.com/ProtonMail/go-crypto v0.0.0-20230717121422-5aa5874ade95/go.mod h1:EjAoLdwvbIOoOQr3ihjnSoLZRtE8azugULFRteWMNc0= +github.com/acomagu/bufpipe v1.0.4 h1:e3H4WUzM3npvo5uv95QuJM3cQspFNtFBzvJ2oNjKIDQ= +github.com/agext/levenshtein v1.2.2 h1:0S/Yg6LYmFJ5stwQeRp6EeOcCbj7xiqQSdNelsXvaqE= +github.com/agext/levenshtein v1.2.2/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec= +github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY= +github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI= +github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bufbuild/protocompile v0.4.0 h1:LbFKd2XowZvQ/kajzguUp2DC9UEIQhIq77fZZlaQsNA= +github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= +github.com/cloudflare/circl v1.3.3 h1:fE/Qz0QdIGqeWfnwq0RE0R7MI51s0M2E4Ga9kq5AEMs= +github.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= +github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= +github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= +github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= +github.com/go-git/go-billy/v5 v5.4.1 h1:Uwp5tDRkPr+l/TnbHOQzp+tmJfLceOlbVucgpTz8ix4= +github.com/go-git/go-git/v5 v5.8.1 h1:Zo79E4p7TRk0xoRgMq0RShiTHGKcKI4+DI6BfJc/Q+A= +github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= +github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-checkpoint v0.5.0 h1:MFYpPZCnQqQTE18jFwSII6eUQrD/oxMFp3mlgcqk5mU= +github.com/hashicorp/go-checkpoint v0.5.0/go.mod h1:7nfLNL10NsxqO4iWuW6tWW0HjZuDrwkBuEQsVcpCOgg= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 h1:1/D3zfFHttUKaCaGKZ/dR2roBXv0vKbSCnssIldfQdI= +github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320/go.mod h1:EiZBMaudVLy8fmjf9Npq1dq9RalhveqZG5w/yz3mHWs= +github.com/hashicorp/go-hclog v1.5.0 h1:bI2ocEMgcVlz55Oj1xZNBsVi900c7II+fWDyV9o+13c= +github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-plugin v1.5.2 h1:aWv8eimFqWlsEiMrYZdPYl+FdHaBJSN4AWwGWfT1G2Y= +github.com/hashicorp/go-plugin v1.5.2/go.mod h1:w1sAEES3g3PuV/RzUrgow20W2uErMly84hhD3um1WL4= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= +github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/hc-install v0.6.0 h1:fDHnU7JNFNSQebVKYhHZ0va1bC6SrPQ8fpebsvNr2w4= +github.com/hashicorp/hc-install v0.6.0/go.mod h1:10I912u3nntx9Umo1VAeYPUUuehk0aRQJYpMwbX5wQA= +github.com/hashicorp/hcl/v2 v2.18.0 h1:wYnG7Lt31t2zYkcquwgKo6MWXzRUDIeIVU5naZwHLl8= +github.com/hashicorp/hcl/v2 v2.18.0/go.mod h1:ThLC89FV4p9MPW804KVbe/cEXoQ8NZEh+JtMeeGErHE= +github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= +github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/terraform-exec v0.19.0 h1:FpqZ6n50Tk95mItTSS9BjeOVUb4eg81SpgVtZNNtFSM= +github.com/hashicorp/terraform-exec v0.19.0/go.mod h1:tbxUpe3JKruE9Cuf65mycSIT8KiNPZ0FkuTE3H4urQg= +github.com/hashicorp/terraform-json v0.17.1 h1:eMfvh/uWggKmY7Pmb3T85u86E2EQg6EQHgyRwf3RkyA= +github.com/hashicorp/terraform-json v0.17.1/go.mod h1:Huy6zt6euxaY9knPAFKjUITn8QxUFIe9VuSzb4zn/0o= +github.com/hashicorp/terraform-plugin-docs v0.16.0 h1:UmxFr3AScl6Wged84jndJIfFccGyBZn52KtMNsS12dI= +github.com/hashicorp/terraform-plugin-docs v0.16.0/go.mod h1:M3ZrlKBJAbPMtNOPwHicGi1c+hZUh7/g0ifT/z7TVfA= +github.com/hashicorp/terraform-plugin-framework v1.4.2 h1:P7a7VP1GZbjc4rv921Xy5OckzhoiO3ig6SGxwelD2sI= +github.com/hashicorp/terraform-plugin-framework v1.4.2/go.mod h1:GWl3InPFZi2wVQmdVnINPKys09s9mLmTZr95/ngLnbY= +github.com/hashicorp/terraform-plugin-framework-validators v0.12.0 h1:HOjBuMbOEzl7snOdOoUfE2Jgeto6JOjLVQ39Ls2nksc= +github.com/hashicorp/terraform-plugin-framework-validators v0.12.0/go.mod h1:jfHGE/gzjxYz6XoUwi/aYiiKrJDeutQNUtGQXkaHklg= +github.com/hashicorp/terraform-plugin-go v0.19.0 h1:BuZx/6Cp+lkmiG0cOBk6Zps0Cb2tmqQpDM3iAtnhDQU= +github.com/hashicorp/terraform-plugin-go v0.19.0/go.mod h1:EhRSkEPNoylLQntYsk5KrDHTZJh9HQoumZXbOGOXmec= +github.com/hashicorp/terraform-plugin-log v0.9.0 h1:i7hOA+vdAItN1/7UrfBqBwvYPQ9TFvymaRGZED3FCV0= +github.com/hashicorp/terraform-plugin-log v0.9.0/go.mod h1:rKL8egZQ/eXSyDqzLUuwUYLVdlYeamldAHSxjUFADow= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.29.0 h1:wcOKYwPI9IorAJEBLzgclh3xVolO7ZorYd6U1vnok14= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.29.0/go.mod h1:qH/34G25Ugdj5FcM95cSoXzUgIbgfhVLXCcEcYaMwq8= +github.com/hashicorp/terraform-plugin-testing v1.5.1 h1:T4aQh9JAhmWo4+t1A7x+rnxAJHCDIYW9kXyo4sVO92c= +github.com/hashicorp/terraform-plugin-testing v1.5.1/go.mod h1:dg8clO6K59rZ8w9EshBmDp1CxTIPu3yA4iaDpX1h5u0= +github.com/hashicorp/terraform-registry-address v0.2.2 h1:lPQBg403El8PPicg/qONZJDC6YlgCVbWDtNmmZKtBno= +github.com/hashicorp/terraform-registry-address v0.2.2/go.mod h1:LtwNbCihUoUZ3RYriyS2wF/lGPB6gF9ICLRtuDk7hSo= +github.com/hashicorp/terraform-svchost v0.1.1 h1:EZZimZ1GxdqFRinZ1tpJwVxxt49xc/S52uzrw4x0jKQ= +github.com/hashicorp/terraform-svchost v0.1.1/go.mod h1:mNsjQfZyf/Jhz35v6/0LWcv26+X7JPS+buii2c9/ctc= +github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE= +github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ= +github.com/huandu/xstrings v1.3.1/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= +github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= +github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= +github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/imdario/mergo v0.3.15 h1:M8XP7IuFNsqUx6VPK2P9OSmsYsI/YFaGil0uD21V3dM= +github.com/imdario/mergo v0.3.15/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= +github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= +github.com/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c= +github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mitchellh/cli v1.1.5 h1:OxRIeJXpAMztws/XHlN2vu6imG5Dpq+j61AzAX5fLng= +github.com/mitchellh/cli v1.1.5/go.mod h1:v8+iFts2sPIKUV1ltktPXMCC8fumSKFItNcD2cLtRR4= +github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= +github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= +github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= +github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= +github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8= +github.com/mitchellh/go-wordwrap v1.0.0 h1:6GlHJ/LTGMrIJbwgdqdl2eEH8o+Exx/0m8ir9Gns0u4= +github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= +github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/netascode/go-catalystcenter v0.1.0 h1:TA/KAi+mA3KMs+CFQbZOOtTtw/oFpvMwHSM4lU8comE= +github.com/netascode/go-catalystcenter v0.1.0/go.mod h1:TbQE/MnDhCaFsj0mIjzQDN+6g810pP4PERbxaJOFs0E= +github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA= +github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= +github.com/pjbgf/sha1cd v0.3.0 h1:4D5XXmUUBUl/xQ6IjCkEAbqXskkq/4O7LmGn0AqMDs4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/posener/complete v1.2.3 h1:NP0eAhjcjImqslEwo/1hq7gpajME0fTLTezBKDqfXqo= +github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= +github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= +github.com/russross/blackfriday v1.6.0 h1:KqfZb0pUVN2lYqZUYRddxF4OR8ZMURnJIG5Y3VRLtww= +github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY= +github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= +github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= +github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/skeema/knownhosts v1.2.0 h1:h9r9cf0+u7wSE+M183ZtMGgOJKiL96brpaz5ekfJCpM= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= +github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM= +github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= +github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= +github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI= +github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= +github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= +github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= +github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= +github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= +github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/zclconf/go-cty v1.14.0 h1:/Xrd39K7DXbHzlisFP9c4pHao4yyf+/Ug9LEz+Y/yhc= +github.com/zclconf/go-cty v1.14.0/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200414173820-0848c9571904/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= +golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/exp v0.0.0-20230809150735-7b3493d9a819 h1:EDuYyU/MkFXllv9QF9819VlI9a4tzGuCbhG0ExK9o1U= +golang.org/x/exp v0.0.0-20230809150735-7b3493d9a819/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.13.0 h1:I/DsJXRlw/8l/0c24sM9yb0T4z9liZTduXvdAWYiysY= +golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.14.0 h1:jvNa2pY0M4r62jkRQ6RwEZZyPcymeL9XZMLBbV7U2nc= +golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b h1:ZlWIi1wSK56/8hn4QcBp/j9M7Gt3U/3hZw3mC7vDICo= +google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b/go.mod h1:swOH3j0KzcDDgGUWr+SNpyTen5YrXjS3eyPzFYKc6lc= +google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk= +google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/h2non/gock.v1 v1.1.2 h1:jBbHXgGBK/AoPVfJh5x4r/WxIrElvbLel8TCZkkZJoY= +gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/provider/data_source_catalystcenter_area.go b/internal/provider/data_source_catalystcenter_area.go new file mode 100644 index 00000000..6b107ab1 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_area.go @@ -0,0 +1,116 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &AreaDataSource{} + _ datasource.DataSourceWithConfigure = &AreaDataSource{} +) + +func NewAreaDataSource() datasource.DataSource { + return &AreaDataSource{} +} + +type AreaDataSource struct { + client *cc.Client +} + +func (d *AreaDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_area" +} + +func (d *AreaDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the Area.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the area", + Computed: true, + }, + "parent_name": schema.StringAttribute{ + MarkdownDescription: "The path of the parent area, e.g. `Global/Area5`. `Global` in case of root area.", + Computed: true, + }, + }, + } +} + +func (d *AreaDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *AreaDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config Area + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + params += "?id=" + config.Id.ValueString() + res, err := d.client.Get("/dna/intent/api/v2/site" + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_area_test.go b/internal/provider/data_source_catalystcenter_area_test.go new file mode 100644 index 00000000..dcded09d --- /dev/null +++ b/internal/provider/data_source_catalystcenter_area_test.go @@ -0,0 +1,67 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcArea(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_area.test", "name", "Area1")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcAreaConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcAreaConfig() string { + config := `resource "catalystcenter_area" "test" {` + "\n" + config += ` name = "Area1"` + "\n" + config += ` parent_name = "Global"` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_area" "test" { + id = catalystcenter_area.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/data_source_catalystcenter_building.go b/internal/provider/data_source_catalystcenter_building.go new file mode 100644 index 00000000..b48d98ce --- /dev/null +++ b/internal/provider/data_source_catalystcenter_building.go @@ -0,0 +1,132 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &BuildingDataSource{} + _ datasource.DataSourceWithConfigure = &BuildingDataSource{} +) + +func NewBuildingDataSource() datasource.DataSource { + return &BuildingDataSource{} +} + +type BuildingDataSource struct { + client *cc.Client +} + +func (d *BuildingDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_building" +} + +func (d *BuildingDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the Building.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the building", + Computed: true, + }, + "parent_name": schema.StringAttribute{ + MarkdownDescription: "The path of the parent area, e.g. `Global/Area5`. `Global` in case of root area.", + Computed: true, + }, + "country": schema.StringAttribute{ + MarkdownDescription: "The country of the building", + Computed: true, + }, + "address": schema.StringAttribute{ + MarkdownDescription: "The address of the building", + Computed: true, + }, + "latitude": schema.Float64Attribute{ + MarkdownDescription: "Latitude", + Computed: true, + }, + "longitude": schema.Float64Attribute{ + MarkdownDescription: "Longitude", + Computed: true, + }, + }, + } +} + +func (d *BuildingDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *BuildingDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config Building + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + params += "?id=" + config.Id.ValueString() + res, err := d.client.Get("/dna/intent/api/v2/site" + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_building_test.go b/internal/provider/data_source_catalystcenter_building_test.go new file mode 100644 index 00000000..43cef347 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_building_test.go @@ -0,0 +1,75 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcBuilding(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_building.test", "name", "Building1")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_building.test", "country", "United States")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_building.test", "address", "150 W Tasman Dr, San Jose")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_building.test", "latitude", "37.338")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_building.test", "longitude", "-121.832")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcBuildingConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcBuildingConfig() string { + config := `resource "catalystcenter_building" "test" {` + "\n" + config += ` name = "Building1"` + "\n" + config += ` parent_name = "Global"` + "\n" + config += ` country = "United States"` + "\n" + config += ` address = "150 W Tasman Dr, San Jose"` + "\n" + config += ` latitude = 37.338` + "\n" + config += ` longitude = -121.832` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_building" "test" { + id = catalystcenter_building.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/data_source_catalystcenter_credentials_cli.go b/internal/provider/data_source_catalystcenter_credentials_cli.go new file mode 100644 index 00000000..0c299846 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_cli.go @@ -0,0 +1,124 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &CredentialsCLIDataSource{} + _ datasource.DataSourceWithConfigure = &CredentialsCLIDataSource{} +) + +func NewCredentialsCLIDataSource() datasource.DataSource { + return &CredentialsCLIDataSource{} +} + +type CredentialsCLIDataSource struct { + client *cc.Client +} + +func (d *CredentialsCLIDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_cli" +} + +func (d *CredentialsCLIDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the Credentials CLI.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "description": schema.StringAttribute{ + MarkdownDescription: "The description of the CLI credentials", + Computed: true, + }, + "username": schema.StringAttribute{ + MarkdownDescription: "Username", + Computed: true, + }, + "password": schema.StringAttribute{ + MarkdownDescription: "Password", + Computed: true, + }, + "enable_password": schema.StringAttribute{ + MarkdownDescription: "Enable password", + Computed: true, + }, + }, + } +} + +func (d *CredentialsCLIDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *CredentialsCLIDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config CredentialsCLI + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + res, err := d.client.Get(config.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + res = res.Get("response.cliCredential.#(id==\"" + config.Id.ValueString() + "\")") + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_credentials_cli_test.go b/internal/provider/data_source_catalystcenter_credentials_cli_test.go new file mode 100644 index 00000000..881589dd --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_cli_test.go @@ -0,0 +1,69 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcCredentialsCLI(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_cli.test", "description", "My CLI credentials")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_cli.test", "username", "user1")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcCredentialsCLIConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcCredentialsCLIConfig() string { + config := `resource "catalystcenter_credentials_cli" "test" {` + "\n" + config += ` description = "My CLI credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` password = "password1"` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_credentials_cli" "test" { + id = catalystcenter_credentials_cli.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/data_source_catalystcenter_credentials_https_read.go b/internal/provider/data_source_catalystcenter_credentials_https_read.go new file mode 100644 index 00000000..f091b048 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_https_read.go @@ -0,0 +1,124 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &CredentialsHTTPSReadDataSource{} + _ datasource.DataSourceWithConfigure = &CredentialsHTTPSReadDataSource{} +) + +func NewCredentialsHTTPSReadDataSource() datasource.DataSource { + return &CredentialsHTTPSReadDataSource{} +} + +type CredentialsHTTPSReadDataSource struct { + client *cc.Client +} + +func (d *CredentialsHTTPSReadDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_https_read" +} + +func (d *CredentialsHTTPSReadDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the Credentials HTTPS Read.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "description": schema.StringAttribute{ + MarkdownDescription: "The description of the HTTPS credentials", + Computed: true, + }, + "username": schema.StringAttribute{ + MarkdownDescription: "Username", + Computed: true, + }, + "password": schema.StringAttribute{ + MarkdownDescription: "Password", + Computed: true, + }, + "port": schema.Int64Attribute{ + MarkdownDescription: "HTTPS port", + Computed: true, + }, + }, + } +} + +func (d *CredentialsHTTPSReadDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *CredentialsHTTPSReadDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config CredentialsHTTPSRead + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + res, err := d.client.Get(config.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + res = res.Get("response.httpsRead.#(id==\"" + config.Id.ValueString() + "\")") + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_credentials_https_read_test.go b/internal/provider/data_source_catalystcenter_credentials_https_read_test.go new file mode 100644 index 00000000..1b188185 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_https_read_test.go @@ -0,0 +1,71 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcCredentialsHTTPSRead(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_https_read.test", "description", "My HTTPS read credentials")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_https_read.test", "username", "user1")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_https_read.test", "port", "444")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcCredentialsHTTPSReadConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcCredentialsHTTPSReadConfig() string { + config := `resource "catalystcenter_credentials_https_read" "test" {` + "\n" + config += ` description = "My HTTPS read credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` password = "password1"` + "\n" + config += ` port = 444` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_credentials_https_read" "test" { + id = catalystcenter_credentials_https_read.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/data_source_catalystcenter_credentials_https_write.go b/internal/provider/data_source_catalystcenter_credentials_https_write.go new file mode 100644 index 00000000..49eac03c --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_https_write.go @@ -0,0 +1,124 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &CredentialsHTTPSWriteDataSource{} + _ datasource.DataSourceWithConfigure = &CredentialsHTTPSWriteDataSource{} +) + +func NewCredentialsHTTPSWriteDataSource() datasource.DataSource { + return &CredentialsHTTPSWriteDataSource{} +} + +type CredentialsHTTPSWriteDataSource struct { + client *cc.Client +} + +func (d *CredentialsHTTPSWriteDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_https_write" +} + +func (d *CredentialsHTTPSWriteDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the Credentials HTTPS Write.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "description": schema.StringAttribute{ + MarkdownDescription: "The description of the HTTPS credentials", + Computed: true, + }, + "username": schema.StringAttribute{ + MarkdownDescription: "Username", + Computed: true, + }, + "password": schema.StringAttribute{ + MarkdownDescription: "Password", + Computed: true, + }, + "port": schema.Int64Attribute{ + MarkdownDescription: "HTTPS port", + Computed: true, + }, + }, + } +} + +func (d *CredentialsHTTPSWriteDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *CredentialsHTTPSWriteDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config CredentialsHTTPSWrite + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + res, err := d.client.Get(config.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + res = res.Get("response.httpsWrite.#(id==\"" + config.Id.ValueString() + "\")") + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_credentials_https_write_test.go b/internal/provider/data_source_catalystcenter_credentials_https_write_test.go new file mode 100644 index 00000000..75f9e1c1 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_https_write_test.go @@ -0,0 +1,71 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcCredentialsHTTPSWrite(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_https_write.test", "description", "My HTTPS write credentials")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_https_write.test", "username", "user1")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_https_write.test", "port", "444")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcCredentialsHTTPSWriteConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcCredentialsHTTPSWriteConfig() string { + config := `resource "catalystcenter_credentials_https_write" "test" {` + "\n" + config += ` description = "My HTTPS write credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` password = "password1"` + "\n" + config += ` port = 444` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_credentials_https_write" "test" { + id = catalystcenter_credentials_https_write.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/data_source_catalystcenter_credentials_snmpv2_read.go b/internal/provider/data_source_catalystcenter_credentials_snmpv2_read.go new file mode 100644 index 00000000..e9ea6240 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_snmpv2_read.go @@ -0,0 +1,116 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &CredentialsSNMPv2ReadDataSource{} + _ datasource.DataSourceWithConfigure = &CredentialsSNMPv2ReadDataSource{} +) + +func NewCredentialsSNMPv2ReadDataSource() datasource.DataSource { + return &CredentialsSNMPv2ReadDataSource{} +} + +type CredentialsSNMPv2ReadDataSource struct { + client *cc.Client +} + +func (d *CredentialsSNMPv2ReadDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_snmpv2_read" +} + +func (d *CredentialsSNMPv2ReadDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the Credentials SNMPv2 Read.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "description": schema.StringAttribute{ + MarkdownDescription: "The description of the SNMPv2 credentials", + Computed: true, + }, + "read_community": schema.StringAttribute{ + MarkdownDescription: "Read community", + Computed: true, + }, + }, + } +} + +func (d *CredentialsSNMPv2ReadDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *CredentialsSNMPv2ReadDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config CredentialsSNMPv2Read + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + res, err := d.client.Get(config.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + res = res.Get("response.snmpV2cRead.#(id==\"" + config.Id.ValueString() + "\")") + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_credentials_snmpv2_read_test.go b/internal/provider/data_source_catalystcenter_credentials_snmpv2_read_test.go new file mode 100644 index 00000000..b66a0a54 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_snmpv2_read_test.go @@ -0,0 +1,67 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcCredentialsSNMPv2Read(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_snmpv2_read.test", "description", "My SNMPv2 read credentials")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcCredentialsSNMPv2ReadConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcCredentialsSNMPv2ReadConfig() string { + config := `resource "catalystcenter_credentials_snmpv2_read" "test" {` + "\n" + config += ` description = "My SNMPv2 read credentials"` + "\n" + config += ` read_community = "community1"` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_credentials_snmpv2_read" "test" { + id = catalystcenter_credentials_snmpv2_read.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/data_source_catalystcenter_credentials_snmpv2_write.go b/internal/provider/data_source_catalystcenter_credentials_snmpv2_write.go new file mode 100644 index 00000000..bcd651be --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_snmpv2_write.go @@ -0,0 +1,116 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &CredentialsSNMPv2WriteDataSource{} + _ datasource.DataSourceWithConfigure = &CredentialsSNMPv2WriteDataSource{} +) + +func NewCredentialsSNMPv2WriteDataSource() datasource.DataSource { + return &CredentialsSNMPv2WriteDataSource{} +} + +type CredentialsSNMPv2WriteDataSource struct { + client *cc.Client +} + +func (d *CredentialsSNMPv2WriteDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_snmpv2_write" +} + +func (d *CredentialsSNMPv2WriteDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the Credentials SNMPv2 Write.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "description": schema.StringAttribute{ + MarkdownDescription: "The description of the SNMPv2 credentials", + Computed: true, + }, + "write_community": schema.StringAttribute{ + MarkdownDescription: "Write community", + Computed: true, + }, + }, + } +} + +func (d *CredentialsSNMPv2WriteDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *CredentialsSNMPv2WriteDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config CredentialsSNMPv2Write + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + res, err := d.client.Get(config.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + res = res.Get("response.snmpV2cWrite.#(id==\"" + config.Id.ValueString() + "\")") + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_credentials_snmpv2_write_test.go b/internal/provider/data_source_catalystcenter_credentials_snmpv2_write_test.go new file mode 100644 index 00000000..653a0136 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_snmpv2_write_test.go @@ -0,0 +1,67 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcCredentialsSNMPv2Write(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_snmpv2_write.test", "description", "My SNMPv2 write credentials")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcCredentialsSNMPv2WriteConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcCredentialsSNMPv2WriteConfig() string { + config := `resource "catalystcenter_credentials_snmpv2_write" "test" {` + "\n" + config += ` description = "My SNMPv2 write credentials"` + "\n" + config += ` write_community = "community1"` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_credentials_snmpv2_write" "test" { + id = catalystcenter_credentials_snmpv2_write.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/data_source_catalystcenter_credentials_snmpv3.go b/internal/provider/data_source_catalystcenter_credentials_snmpv3.go new file mode 100644 index 00000000..e6a3d4db --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_snmpv3.go @@ -0,0 +1,136 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &CredentialsSNMPv3DataSource{} + _ datasource.DataSourceWithConfigure = &CredentialsSNMPv3DataSource{} +) + +func NewCredentialsSNMPv3DataSource() datasource.DataSource { + return &CredentialsSNMPv3DataSource{} +} + +type CredentialsSNMPv3DataSource struct { + client *cc.Client +} + +func (d *CredentialsSNMPv3DataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_snmpv3" +} + +func (d *CredentialsSNMPv3DataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the Credentials SNMPv3.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "description": schema.StringAttribute{ + MarkdownDescription: "The description of the SNMPv3 credentials", + Computed: true, + }, + "username": schema.StringAttribute{ + MarkdownDescription: "Username", + Computed: true, + }, + "privacy_type": schema.StringAttribute{ + MarkdownDescription: "Privacy type", + Computed: true, + }, + "privacy_password": schema.StringAttribute{ + MarkdownDescription: "Privacy password", + Computed: true, + }, + "auth_type": schema.StringAttribute{ + MarkdownDescription: "Authentication type", + Computed: true, + }, + "auth_password": schema.StringAttribute{ + MarkdownDescription: "Authentication password", + Computed: true, + }, + "snmp_mode": schema.StringAttribute{ + MarkdownDescription: "SNMP mode", + Computed: true, + }, + }, + } +} + +func (d *CredentialsSNMPv3DataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *CredentialsSNMPv3DataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config CredentialsSNMPv3 + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + res, err := d.client.Get(config.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + res = res.Get("response.snmpV3.#(id==\"" + config.Id.ValueString() + "\")") + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_credentials_snmpv3_test.go b/internal/provider/data_source_catalystcenter_credentials_snmpv3_test.go new file mode 100644 index 00000000..f590ed54 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_credentials_snmpv3_test.go @@ -0,0 +1,76 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcCredentialsSNMPv3(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_snmpv3.test", "description", "My SNMPv3 credentials")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_snmpv3.test", "username", "user1")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_snmpv3.test", "privacy_type", "AES128")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_snmpv3.test", "auth_type", "SHA")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_credentials_snmpv3.test", "snmp_mode", "AUTHPRIV")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcCredentialsSNMPv3Config(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcCredentialsSNMPv3Config() string { + config := `resource "catalystcenter_credentials_snmpv3" "test" {` + "\n" + config += ` description = "My SNMPv3 credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` privacy_type = "AES128"` + "\n" + config += ` privacy_password = "password1"` + "\n" + config += ` auth_type = "SHA"` + "\n" + config += ` auth_password = "password1"` + "\n" + config += ` snmp_mode = "AUTHPRIV"` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_credentials_snmpv3" "test" { + id = catalystcenter_credentials_snmpv3.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/data_source_catalystcenter_floor.go b/internal/provider/data_source_catalystcenter_floor.go new file mode 100644 index 00000000..d065e496 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_floor.go @@ -0,0 +1,132 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &FloorDataSource{} + _ datasource.DataSourceWithConfigure = &FloorDataSource{} +) + +func NewFloorDataSource() datasource.DataSource { + return &FloorDataSource{} +} + +type FloorDataSource struct { + client *cc.Client +} + +func (d *FloorDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_floor" +} + +func (d *FloorDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the Floor.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the floor", + Computed: true, + }, + "parent_name": schema.StringAttribute{ + MarkdownDescription: "The path of the parent building, e.g. `Global/Building1`", + Computed: true, + }, + "rf_model": schema.StringAttribute{ + MarkdownDescription: "The RF model", + Computed: true, + }, + "width": schema.Float64Attribute{ + MarkdownDescription: "Width", + Computed: true, + }, + "length": schema.Float64Attribute{ + MarkdownDescription: "Length", + Computed: true, + }, + "height": schema.Float64Attribute{ + MarkdownDescription: "Height", + Computed: true, + }, + }, + } +} + +func (d *FloorDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *FloorDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config Floor + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + params += "/" + config.Id.ValueString() + res, err := d.client.Get("/api/v1/dna-maps-service/domains" + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_floor_test.go b/internal/provider/data_source_catalystcenter_floor_test.go new file mode 100644 index 00000000..c0ca1c50 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_floor_test.go @@ -0,0 +1,86 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcFloor(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_floor.test", "name", "Floor1")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_floor.test", "width", "30.5")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_floor.test", "length", "50.5")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_floor.test", "height", "3.5")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcFloorPrerequisitesConfig + testAccDataSourceCcFloorConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +const testAccDataSourceCcFloorPrerequisitesConfig = ` +resource "catalystcenter_building" "test" { + name = "Building1" + parent_name = "Global" + country = "United States" + address = "150 W Tasman Dr, San Jose" + latitude = 37.338 + longitude = -121.832 +} + +` + +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcFloorConfig() string { + config := `resource "catalystcenter_floor" "test" {` + "\n" + config += ` name = "Floor1"` + "\n" + config += ` parent_name = "${catalystcenter_building.test.parent_name}/${catalystcenter_building.test.name}"` + "\n" + config += ` rf_model = "Drywall Office Only"` + "\n" + config += ` width = 30.5` + "\n" + config += ` length = 50.5` + "\n" + config += ` height = 3.5` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_floor" "test" { + id = catalystcenter_floor.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/data_source_catalystcenter_ip_pool.go b/internal/provider/data_source_catalystcenter_ip_pool.go new file mode 100644 index 00000000..016fc599 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_ip_pool.go @@ -0,0 +1,139 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &IPPoolDataSource{} + _ datasource.DataSourceWithConfigure = &IPPoolDataSource{} +) + +func NewIPPoolDataSource() datasource.DataSource { + return &IPPoolDataSource{} +} + +type IPPoolDataSource struct { + client *cc.Client +} + +func (d *IPPoolDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_ip_pool" +} + +func (d *IPPoolDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the IP Pool.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the IP pool", + Computed: true, + }, + "ip_address_space": schema.StringAttribute{ + MarkdownDescription: "IP address version", + Computed: true, + }, + "type": schema.StringAttribute{ + MarkdownDescription: "Choose `Tunnel` to assign IP addresses to site-to-site VPN for IPSec tunneling. Choose `Generic` for all other network types.", + Computed: true, + }, + "ip_subnet": schema.StringAttribute{ + MarkdownDescription: "The IP subnet of the IP pool", + Computed: true, + }, + "gateway": schema.StringAttribute{ + MarkdownDescription: "The gateway for the IP pool", + Computed: true, + }, + "dhcp_server_ips": schema.ListAttribute{ + MarkdownDescription: "List of DHCP Server IPs", + ElementType: types.StringType, + Computed: true, + }, + "dns_server_ips": schema.ListAttribute{ + MarkdownDescription: "List of DNS Server IPs", + ElementType: types.StringType, + Computed: true, + }, + }, + } +} + +func (d *IPPoolDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *IPPoolDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config IPPool + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + params += "/" + config.Id.ValueString() + res, err := d.client.Get("/api/v2/ippool" + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_ip_pool_reservation.go b/internal/provider/data_source_catalystcenter_ip_pool_reservation.go new file mode 100644 index 00000000..33e4da98 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_ip_pool_reservation.go @@ -0,0 +1,197 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" +) + +//template:end imports + +//template:begin model + +// Ensure the implementation satisfies the expected interfaces. +var ( + _ datasource.DataSource = &IPPoolReservationDataSource{} + _ datasource.DataSourceWithConfigure = &IPPoolReservationDataSource{} +) + +func NewIPPoolReservationDataSource() datasource.DataSource { + return &IPPoolReservationDataSource{} +} + +type IPPoolReservationDataSource struct { + client *cc.Client +} + +func (d *IPPoolReservationDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_ip_pool_reservation" +} + +func (d *IPPoolReservationDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: "This data source can read the IP Pool Reservation.", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Required: true, + }, + "site_id": schema.StringAttribute{ + MarkdownDescription: "The site ID", + Required: true, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the IP pool reservation", + Computed: true, + }, + "type": schema.StringAttribute{ + MarkdownDescription: "The type of the IP pool reservation", + Computed: true, + }, + "ipv6_address_space": schema.BoolAttribute{ + MarkdownDescription: "If the value is `false` only IPv4 input are required, otherwise both IPv6 and IPv4 are required", + Computed: true, + }, + "ipv4_global_pool": schema.StringAttribute{ + MarkdownDescription: "IPv4 Global pool address with cidr, example: 175.175.0.0/16", + Computed: true, + }, + "ipv4_prefix": schema.BoolAttribute{ + MarkdownDescription: "If this value is `true`, the `ipv4_prefix_length` attribute must be provided, if it is `false`, the `ipv4_total_host` attribute must be provided", + Computed: true, + }, + "ipv4_prefix_length": schema.Int64Attribute{ + MarkdownDescription: "The IPv4 prefix length is required when `ipv4_prefix` value is `true`.", + Computed: true, + }, + "ipv4_subnet": schema.StringAttribute{ + MarkdownDescription: "The IPv4 subnet", + Computed: true, + }, + "ipv4_gateway": schema.StringAttribute{ + MarkdownDescription: "The gateway for the IP pool reservation", + Computed: true, + }, + "ipv4_dhcp_servers": schema.ListAttribute{ + MarkdownDescription: "List of DHCP Server IPs", + ElementType: types.StringType, + Computed: true, + }, + "ipv4_dns_servers": schema.ListAttribute{ + MarkdownDescription: "List of DNS Server IPs", + ElementType: types.StringType, + Computed: true, + }, + "ipv6_global_pool": schema.StringAttribute{ + MarkdownDescription: "IPv6 Global pool address with cidr, example: 2001:db8:85a3::/64", + Computed: true, + }, + "ipv6_prefix": schema.BoolAttribute{ + MarkdownDescription: "If this value is `true`, the `ipv6_prefix_length` attribute must be provided, if it is `false`, the `ipv6_total_host` attribute must be provided", + Computed: true, + }, + "ipv6_prefix_length": schema.Int64Attribute{ + MarkdownDescription: "The IPv6 prefix length is required when `ipv6_prefix` value is `true`.", + Computed: true, + }, + "ipv6_subnet": schema.StringAttribute{ + MarkdownDescription: "The IPv6 subnet, for example `2001:db8:85a3:0:100::`", + Computed: true, + }, + "ipv6_gateway": schema.StringAttribute{ + MarkdownDescription: "The gateway for the IP pool reservation", + Computed: true, + }, + "ipv6_dhcp_servers": schema.ListAttribute{ + MarkdownDescription: "List of DHCP Server IPs", + ElementType: types.StringType, + Computed: true, + }, + "ipv6_dns_servers": schema.ListAttribute{ + MarkdownDescription: "List of DNS Server IPs", + ElementType: types.StringType, + Computed: true, + }, + "ipv4_total_host": schema.Int64Attribute{ + MarkdownDescription: "The total number of IPv4 hosts", + Computed: true, + }, + "ipv6_total_host": schema.Int64Attribute{ + MarkdownDescription: "The total number of IPv6 hosts", + Computed: true, + }, + "slaac_support": schema.BoolAttribute{ + MarkdownDescription: "Enable SLAAC support", + Computed: true, + }, + }, + } +} + +func (d *IPPoolReservationDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, _ *datasource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + d.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin read +func (d *IPPoolReservationDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var config IPPoolReservation + + // Read config + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", config.Id.String())) + + params := "" + params += "?siteId=" + config.SiteId.ValueString() + res, err := d.client.Get(config.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object, got error: %s", err)) + return + } + + config.fromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", config.Id.ValueString())) + + diags = resp.State.Set(ctx, &config) + resp.Diagnostics.Append(diags...) +} + +//template:end read diff --git a/internal/provider/data_source_catalystcenter_ip_pool_reservation_test.go b/internal/provider/data_source_catalystcenter_ip_pool_reservation_test.go new file mode 100644 index 00000000..5ce5a0e3 --- /dev/null +++ b/internal/provider/data_source_catalystcenter_ip_pool_reservation_test.go @@ -0,0 +1,91 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcIPPoolReservation(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_ip_pool_reservation.test", "name", "MyRes1")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcIPPoolReservationPrerequisitesConfig + testAccDataSourceCcIPPoolReservationConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +const testAccDataSourceCcIPPoolReservationPrerequisitesConfig = ` +resource "catalystcenter_area" "test" { + name = "Area1" + parent_name = "Global" + depends_on = [catalystcenter_ip_pool.test] +} + +resource "catalystcenter_ip_pool" "test" { + name = "MyPool1" + ip_subnet = "172.32.0.0/16" +} + +` + +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcIPPoolReservationConfig() string { + config := `resource "catalystcenter_ip_pool_reservation" "test" {` + "\n" + config += ` site_id = catalystcenter_area.test.id` + "\n" + config += ` name = "MyRes1"` + "\n" + config += ` type = "Generic"` + "\n" + config += ` ipv6_address_space = false` + "\n" + config += ` ipv4_global_pool = "172.32.0.0/16"` + "\n" + config += ` ipv4_prefix = true` + "\n" + config += ` ipv4_prefix_length = 24` + "\n" + config += ` ipv4_subnet = "172.32.1.0"` + "\n" + config += ` ipv4_gateway = "172.32.1.1"` + "\n" + config += ` ipv4_dhcp_servers = ["1.2.3.4"]` + "\n" + config += ` ipv4_dns_servers = ["2.3.4.5"]` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_ip_pool_reservation" "test" { + id = catalystcenter_ip_pool_reservation.test.id + site_id = catalystcenter_area.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/data_source_catalystcenter_ip_pool_test.go b/internal/provider/data_source_catalystcenter_ip_pool_test.go new file mode 100644 index 00000000..d715875a --- /dev/null +++ b/internal/provider/data_source_catalystcenter_ip_pool_test.go @@ -0,0 +1,76 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAccDataSource +func TestAccDataSourceCcIPPool(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_ip_pool.test", "name", "MyPool1")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_ip_pool.test", "ip_subnet", "21.1.1.0/24")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_ip_pool.test", "gateway", "21.1.1.1")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_ip_pool.test", "dhcp_server_ips.0", "1.2.3.4")) + checks = append(checks, resource.TestCheckResourceAttr("data.catalystcenter_ip_pool.test", "dns_server_ips.0", "2.3.4.5")) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceCcIPPoolConfig(), + Check: resource.ComposeTestCheckFunc(checks...), + }, + }, + }) +} + +//template:end testAccDataSource + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccDataSourceConfig +func testAccDataSourceCcIPPoolConfig() string { + config := `resource "catalystcenter_ip_pool" "test" {` + "\n" + config += ` name = "MyPool1"` + "\n" + config += ` ip_address_space = "IPv4"` + "\n" + config += ` type = "Generic"` + "\n" + config += ` ip_subnet = "21.1.1.0/24"` + "\n" + config += ` gateway = "21.1.1.1"` + "\n" + config += ` dhcp_server_ips = ["1.2.3.4"]` + "\n" + config += ` dns_server_ips = ["2.3.4.5"]` + "\n" + config += `}` + "\n" + + config += ` + data "catalystcenter_ip_pool" "test" { + id = catalystcenter_ip_pool.test.id + } + ` + return config +} + +//template:end testAccDataSourceConfig diff --git a/internal/provider/helpers/description_builder.go b/internal/provider/helpers/description_builder.go new file mode 100644 index 00000000..95b2b720 --- /dev/null +++ b/internal/provider/helpers/description_builder.go @@ -0,0 +1,60 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +package helpers + +import ( + "fmt" + "strings" +) + +type AttributeDescription struct { + String string +} + +func NewAttributeDescription(s string) *AttributeDescription { + return &AttributeDescription{s} +} + +func (d *AttributeDescription) AddMinimumVersionDescription(minimumVersion string) *AttributeDescription { + d.String = fmt.Sprintf("%s\n - Minimum Catalyst Center version: `%s`", d.String, minimumVersion) + return d +} + +func (d *AttributeDescription) AddDefaultValueDescription(defaultValue string) *AttributeDescription { + d.String = fmt.Sprintf("%s\n - Default value: `%s`", d.String, defaultValue) + return d +} + +func (d *AttributeDescription) AddStringEnumDescription(values ...string) *AttributeDescription { + v := make([]string, len(values)) + for i, value := range values { + v[i] = fmt.Sprintf("`%s`", value) + } + d.String = fmt.Sprintf("%s\n - Choices: %s", d.String, strings.Join(v, ", ")) + return d +} + +func (d *AttributeDescription) AddIntegerRangeDescription(min, max int64) *AttributeDescription { + d.String = fmt.Sprintf("%s\n - Range: `%v`-`%v`", d.String, min, max) + return d +} + +func (d *AttributeDescription) AddFloatRangeDescription(min, max float64) *AttributeDescription { + d.String = fmt.Sprintf("%s\n - Range: `%v`-`%v`", d.String, min, max) + return d +} diff --git a/internal/provider/helpers/utils.go b/internal/provider/helpers/utils.go new file mode 100644 index 00000000..372e0662 --- /dev/null +++ b/internal/provider/helpers/utils.go @@ -0,0 +1,41 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +package helpers + +import ( + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" +) + +func Contains(s []string, str string) bool { + for _, v := range s { + if v == str { + return true + } + } + return false +} + +func GetStringList(result []gjson.Result) types.List { + v := make([]attr.Value, len(result)) + for r := range result { + v[r] = types.StringValue(result[r].String()) + } + return types.ListValueMust(types.StringType, v) +} diff --git a/internal/provider/model_catalystcenter_area.go b/internal/provider/model_catalystcenter_area.go new file mode 100644 index 00000000..495d263d --- /dev/null +++ b/internal/provider/model_catalystcenter_area.go @@ -0,0 +1,84 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type Area struct { + Id types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + ParentName types.String `tfsdk:"parent_name"` +} + +//template:end types + +//template:begin getPath +func (data Area) getPath() string { + return "/dna/intent/api/v1/site" +} + +//template:end getPath + +//template:begin toBody +func (data Area) toBody(ctx context.Context, state Area) string { + body := "" + body, _ = sjson.Set(body, "type", "area") + if !data.Name.IsNull() { + body, _ = sjson.Set(body, "site.area.name", data.Name.ValueString()) + } + if !data.ParentName.IsNull() { + body, _ = sjson.Set(body, "site.area.parentName", data.ParentName.ValueString()) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *Area) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("response.0.name"); value.Exists() { + data.Name = types.StringValue(value.String()) + } else { + data.Name = types.StringNull() + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *Area) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("response.0.name"); value.Exists() && !data.Name.IsNull() { + data.Name = types.StringValue(value.String()) + } else { + data.Name = types.StringNull() + } +} + +//template:end updateFromBody diff --git a/internal/provider/model_catalystcenter_building.go b/internal/provider/model_catalystcenter_building.go new file mode 100644 index 00000000..732aa89a --- /dev/null +++ b/internal/provider/model_catalystcenter_building.go @@ -0,0 +1,140 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type Building struct { + Id types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + ParentName types.String `tfsdk:"parent_name"` + Country types.String `tfsdk:"country"` + Address types.String `tfsdk:"address"` + Latitude types.Float64 `tfsdk:"latitude"` + Longitude types.Float64 `tfsdk:"longitude"` +} + +//template:end types + +//template:begin getPath +func (data Building) getPath() string { + return "/dna/intent/api/v1/site" +} + +//template:end getPath + +//template:begin toBody +func (data Building) toBody(ctx context.Context, state Building) string { + body := "" + body, _ = sjson.Set(body, "type", "building") + if !data.Name.IsNull() { + body, _ = sjson.Set(body, "site.building.name", data.Name.ValueString()) + } + if !data.ParentName.IsNull() { + body, _ = sjson.Set(body, "site.building.parentName", data.ParentName.ValueString()) + } + if !data.Country.IsNull() { + body, _ = sjson.Set(body, "site.building.country", data.Country.ValueString()) + } + if !data.Address.IsNull() { + body, _ = sjson.Set(body, "site.building.address", data.Address.ValueString()) + } + if !data.Latitude.IsNull() { + body, _ = sjson.Set(body, "site.building.latitude", data.Latitude.ValueFloat64()) + } + if !data.Longitude.IsNull() { + body, _ = sjson.Set(body, "site.building.longitude", data.Longitude.ValueFloat64()) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *Building) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("response.0.name"); value.Exists() { + data.Name = types.StringValue(value.String()) + } else { + data.Name = types.StringNull() + } + if value := res.Get("response.0.additionalInfo.0.attributes.country"); value.Exists() { + data.Country = types.StringValue(value.String()) + } else { + data.Country = types.StringNull() + } + if value := res.Get("response.0.additionalInfo.0.attributes.address"); value.Exists() { + data.Address = types.StringValue(value.String()) + } else { + data.Address = types.StringNull() + } + if value := res.Get("response.0.additionalInfo.0.attributes.latitude"); value.Exists() { + data.Latitude = types.Float64Value(value.Float()) + } else { + data.Latitude = types.Float64Null() + } + if value := res.Get("response.0.additionalInfo.0.attributes.longitude"); value.Exists() { + data.Longitude = types.Float64Value(value.Float()) + } else { + data.Longitude = types.Float64Null() + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *Building) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("response.0.name"); value.Exists() && !data.Name.IsNull() { + data.Name = types.StringValue(value.String()) + } else { + data.Name = types.StringNull() + } + if value := res.Get("response.0.additionalInfo.0.attributes.country"); value.Exists() && !data.Country.IsNull() { + data.Country = types.StringValue(value.String()) + } else { + data.Country = types.StringNull() + } + if value := res.Get("response.0.additionalInfo.0.attributes.address"); value.Exists() && !data.Address.IsNull() { + data.Address = types.StringValue(value.String()) + } else { + data.Address = types.StringNull() + } + if value := res.Get("response.0.additionalInfo.0.attributes.latitude"); value.Exists() && !data.Latitude.IsNull() { + data.Latitude = types.Float64Value(value.Float()) + } else { + data.Latitude = types.Float64Null() + } + if value := res.Get("response.0.additionalInfo.0.attributes.longitude"); value.Exists() && !data.Longitude.IsNull() { + data.Longitude = types.Float64Value(value.Float()) + } else { + data.Longitude = types.Float64Null() + } +} + +//template:end updateFromBody diff --git a/internal/provider/model_catalystcenter_credentials_cli.go b/internal/provider/model_catalystcenter_credentials_cli.go new file mode 100644 index 00000000..13524e71 --- /dev/null +++ b/internal/provider/model_catalystcenter_credentials_cli.go @@ -0,0 +1,104 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type CredentialsCLI struct { + Id types.String `tfsdk:"id"` + Description types.String `tfsdk:"description"` + Username types.String `tfsdk:"username"` + Password types.String `tfsdk:"password"` + EnablePassword types.String `tfsdk:"enable_password"` +} + +//template:end types + +//template:begin getPath +func (data CredentialsCLI) getPath() string { + return "/dna/intent/api/v2/global-credential" +} + +//template:end getPath + +//template:begin toBody +func (data CredentialsCLI) toBody(ctx context.Context, state CredentialsCLI) string { + body := "" + if data.Id.ValueString() != "" { + body, _ = sjson.Set(body, "cliCredential.0.id", data.Id.ValueString()) + } + if !data.Description.IsNull() { + body, _ = sjson.Set(body, "cliCredential.0.description", data.Description.ValueString()) + } + if !data.Username.IsNull() { + body, _ = sjson.Set(body, "cliCredential.0.username", data.Username.ValueString()) + } + if !data.Password.IsNull() { + body, _ = sjson.Set(body, "cliCredential.0.password", data.Password.ValueString()) + } + if !data.EnablePassword.IsNull() { + body, _ = sjson.Set(body, "cliCredential.0.enablePassword", data.EnablePassword.ValueString()) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *CredentialsCLI) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } + if value := res.Get("username"); value.Exists() { + data.Username = types.StringValue(value.String()) + } else { + data.Username = types.StringNull() + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *CredentialsCLI) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() && !data.Description.IsNull() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } + if value := res.Get("username"); value.Exists() && !data.Username.IsNull() { + data.Username = types.StringValue(value.String()) + } else { + data.Username = types.StringNull() + } +} + +//template:end updateFromBody diff --git a/internal/provider/model_catalystcenter_credentials_https_read.go b/internal/provider/model_catalystcenter_credentials_https_read.go new file mode 100644 index 00000000..d0c8ae39 --- /dev/null +++ b/internal/provider/model_catalystcenter_credentials_https_read.go @@ -0,0 +1,114 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type CredentialsHTTPSRead struct { + Id types.String `tfsdk:"id"` + Description types.String `tfsdk:"description"` + Username types.String `tfsdk:"username"` + Password types.String `tfsdk:"password"` + Port types.Int64 `tfsdk:"port"` +} + +//template:end types + +//template:begin getPath +func (data CredentialsHTTPSRead) getPath() string { + return "/dna/intent/api/v2/global-credential" +} + +//template:end getPath + +//template:begin toBody +func (data CredentialsHTTPSRead) toBody(ctx context.Context, state CredentialsHTTPSRead) string { + body := "" + if data.Id.ValueString() != "" { + body, _ = sjson.Set(body, "httpsRead.0.id", data.Id.ValueString()) + } + if !data.Description.IsNull() { + body, _ = sjson.Set(body, "httpsRead.0.description", data.Description.ValueString()) + } + if !data.Username.IsNull() { + body, _ = sjson.Set(body, "httpsRead.0.username", data.Username.ValueString()) + } + if !data.Password.IsNull() { + body, _ = sjson.Set(body, "httpsRead.0.password", data.Password.ValueString()) + } + if !data.Port.IsNull() { + body, _ = sjson.Set(body, "httpsRead.0.port", data.Port.ValueInt64()) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *CredentialsHTTPSRead) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } + if value := res.Get("username"); value.Exists() { + data.Username = types.StringValue(value.String()) + } else { + data.Username = types.StringNull() + } + if value := res.Get("port"); value.Exists() { + data.Port = types.Int64Value(value.Int()) + } else { + data.Port = types.Int64Value(443) + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *CredentialsHTTPSRead) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() && !data.Description.IsNull() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } + if value := res.Get("username"); value.Exists() && !data.Username.IsNull() { + data.Username = types.StringValue(value.String()) + } else { + data.Username = types.StringNull() + } + if value := res.Get("port"); value.Exists() && !data.Port.IsNull() { + data.Port = types.Int64Value(value.Int()) + } else if data.Port.ValueInt64() != 443 { + data.Port = types.Int64Null() + } +} + +//template:end updateFromBody diff --git a/internal/provider/model_catalystcenter_credentials_https_write.go b/internal/provider/model_catalystcenter_credentials_https_write.go new file mode 100644 index 00000000..fdc579a5 --- /dev/null +++ b/internal/provider/model_catalystcenter_credentials_https_write.go @@ -0,0 +1,114 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type CredentialsHTTPSWrite struct { + Id types.String `tfsdk:"id"` + Description types.String `tfsdk:"description"` + Username types.String `tfsdk:"username"` + Password types.String `tfsdk:"password"` + Port types.Int64 `tfsdk:"port"` +} + +//template:end types + +//template:begin getPath +func (data CredentialsHTTPSWrite) getPath() string { + return "/dna/intent/api/v2/global-credential" +} + +//template:end getPath + +//template:begin toBody +func (data CredentialsHTTPSWrite) toBody(ctx context.Context, state CredentialsHTTPSWrite) string { + body := "" + if data.Id.ValueString() != "" { + body, _ = sjson.Set(body, "httpsWrite.0.id", data.Id.ValueString()) + } + if !data.Description.IsNull() { + body, _ = sjson.Set(body, "httpsWrite.0.description", data.Description.ValueString()) + } + if !data.Username.IsNull() { + body, _ = sjson.Set(body, "httpsWrite.0.username", data.Username.ValueString()) + } + if !data.Password.IsNull() { + body, _ = sjson.Set(body, "httpsWrite.0.password", data.Password.ValueString()) + } + if !data.Port.IsNull() { + body, _ = sjson.Set(body, "httpsWrite.0.port", data.Port.ValueInt64()) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *CredentialsHTTPSWrite) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } + if value := res.Get("username"); value.Exists() { + data.Username = types.StringValue(value.String()) + } else { + data.Username = types.StringNull() + } + if value := res.Get("port"); value.Exists() { + data.Port = types.Int64Value(value.Int()) + } else { + data.Port = types.Int64Value(443) + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *CredentialsHTTPSWrite) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() && !data.Description.IsNull() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } + if value := res.Get("username"); value.Exists() && !data.Username.IsNull() { + data.Username = types.StringValue(value.String()) + } else { + data.Username = types.StringNull() + } + if value := res.Get("port"); value.Exists() && !data.Port.IsNull() { + data.Port = types.Int64Value(value.Int()) + } else if data.Port.ValueInt64() != 443 { + data.Port = types.Int64Null() + } +} + +//template:end updateFromBody diff --git a/internal/provider/model_catalystcenter_credentials_snmpv2_read.go b/internal/provider/model_catalystcenter_credentials_snmpv2_read.go new file mode 100644 index 00000000..985f4d97 --- /dev/null +++ b/internal/provider/model_catalystcenter_credentials_snmpv2_read.go @@ -0,0 +1,86 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type CredentialsSNMPv2Read struct { + Id types.String `tfsdk:"id"` + Description types.String `tfsdk:"description"` + ReadCommunity types.String `tfsdk:"read_community"` +} + +//template:end types + +//template:begin getPath +func (data CredentialsSNMPv2Read) getPath() string { + return "/dna/intent/api/v2/global-credential" +} + +//template:end getPath + +//template:begin toBody +func (data CredentialsSNMPv2Read) toBody(ctx context.Context, state CredentialsSNMPv2Read) string { + body := "" + if data.Id.ValueString() != "" { + body, _ = sjson.Set(body, "snmpV2cRead.0.id", data.Id.ValueString()) + } + if !data.Description.IsNull() { + body, _ = sjson.Set(body, "snmpV2cRead.0.description", data.Description.ValueString()) + } + if !data.ReadCommunity.IsNull() { + body, _ = sjson.Set(body, "snmpV2cRead.0.readCommunity", data.ReadCommunity.ValueString()) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *CredentialsSNMPv2Read) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *CredentialsSNMPv2Read) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() && !data.Description.IsNull() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } +} + +//template:end updateFromBody diff --git a/internal/provider/model_catalystcenter_credentials_snmpv2_write.go b/internal/provider/model_catalystcenter_credentials_snmpv2_write.go new file mode 100644 index 00000000..ff585ac6 --- /dev/null +++ b/internal/provider/model_catalystcenter_credentials_snmpv2_write.go @@ -0,0 +1,86 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type CredentialsSNMPv2Write struct { + Id types.String `tfsdk:"id"` + Description types.String `tfsdk:"description"` + WriteCommunity types.String `tfsdk:"write_community"` +} + +//template:end types + +//template:begin getPath +func (data CredentialsSNMPv2Write) getPath() string { + return "/dna/intent/api/v2/global-credential" +} + +//template:end getPath + +//template:begin toBody +func (data CredentialsSNMPv2Write) toBody(ctx context.Context, state CredentialsSNMPv2Write) string { + body := "" + if data.Id.ValueString() != "" { + body, _ = sjson.Set(body, "snmpV2cWrite.0.id", data.Id.ValueString()) + } + if !data.Description.IsNull() { + body, _ = sjson.Set(body, "snmpV2cWrite.0.description", data.Description.ValueString()) + } + if !data.WriteCommunity.IsNull() { + body, _ = sjson.Set(body, "snmpV2cWrite.0.writeCommunity", data.WriteCommunity.ValueString()) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *CredentialsSNMPv2Write) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *CredentialsSNMPv2Write) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() && !data.Description.IsNull() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } +} + +//template:end updateFromBody diff --git a/internal/provider/model_catalystcenter_credentials_snmpv3.go b/internal/provider/model_catalystcenter_credentials_snmpv3.go new file mode 100644 index 00000000..e1762a0e --- /dev/null +++ b/internal/provider/model_catalystcenter_credentials_snmpv3.go @@ -0,0 +1,146 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type CredentialsSNMPv3 struct { + Id types.String `tfsdk:"id"` + Description types.String `tfsdk:"description"` + Username types.String `tfsdk:"username"` + PrivacyType types.String `tfsdk:"privacy_type"` + PrivacyPassword types.String `tfsdk:"privacy_password"` + AuthType types.String `tfsdk:"auth_type"` + AuthPassword types.String `tfsdk:"auth_password"` + SnmpMode types.String `tfsdk:"snmp_mode"` +} + +//template:end types + +//template:begin getPath +func (data CredentialsSNMPv3) getPath() string { + return "/dna/intent/api/v2/global-credential" +} + +//template:end getPath + +//template:begin toBody +func (data CredentialsSNMPv3) toBody(ctx context.Context, state CredentialsSNMPv3) string { + body := "" + if data.Id.ValueString() != "" { + body, _ = sjson.Set(body, "snmpV3.0.id", data.Id.ValueString()) + } + if !data.Description.IsNull() { + body, _ = sjson.Set(body, "snmpV3.0.description", data.Description.ValueString()) + } + if !data.Username.IsNull() { + body, _ = sjson.Set(body, "snmpV3.0.username", data.Username.ValueString()) + } + if !data.PrivacyType.IsNull() { + body, _ = sjson.Set(body, "snmpV3.0.privacyType", data.PrivacyType.ValueString()) + } + if !data.PrivacyPassword.IsNull() { + body, _ = sjson.Set(body, "snmpV3.0.privacyPassword", data.PrivacyPassword.ValueString()) + } + if !data.AuthType.IsNull() { + body, _ = sjson.Set(body, "snmpV3.0.authType", data.AuthType.ValueString()) + } + if !data.AuthPassword.IsNull() { + body, _ = sjson.Set(body, "snmpV3.0.authPassword", data.AuthPassword.ValueString()) + } + if !data.SnmpMode.IsNull() { + body, _ = sjson.Set(body, "snmpV3.0.snmpMode", data.SnmpMode.ValueString()) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *CredentialsSNMPv3) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } + if value := res.Get("username"); value.Exists() { + data.Username = types.StringValue(value.String()) + } else { + data.Username = types.StringNull() + } + if value := res.Get("privacyType"); value.Exists() { + data.PrivacyType = types.StringValue(value.String()) + } else { + data.PrivacyType = types.StringNull() + } + if value := res.Get("authType"); value.Exists() { + data.AuthType = types.StringValue(value.String()) + } else { + data.AuthType = types.StringNull() + } + if value := res.Get("snmpMode"); value.Exists() { + data.SnmpMode = types.StringValue(value.String()) + } else { + data.SnmpMode = types.StringNull() + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *CredentialsSNMPv3) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("description"); value.Exists() && !data.Description.IsNull() { + data.Description = types.StringValue(value.String()) + } else { + data.Description = types.StringNull() + } + if value := res.Get("username"); value.Exists() && !data.Username.IsNull() { + data.Username = types.StringValue(value.String()) + } else { + data.Username = types.StringNull() + } + if value := res.Get("privacyType"); value.Exists() && !data.PrivacyType.IsNull() { + data.PrivacyType = types.StringValue(value.String()) + } else { + data.PrivacyType = types.StringNull() + } + if value := res.Get("authType"); value.Exists() && !data.AuthType.IsNull() { + data.AuthType = types.StringValue(value.String()) + } else { + data.AuthType = types.StringNull() + } + if value := res.Get("snmpMode"); value.Exists() && !data.SnmpMode.IsNull() { + data.SnmpMode = types.StringValue(value.String()) + } else { + data.SnmpMode = types.StringNull() + } +} + +//template:end updateFromBody diff --git a/internal/provider/model_catalystcenter_floor.go b/internal/provider/model_catalystcenter_floor.go new file mode 100644 index 00000000..e593316f --- /dev/null +++ b/internal/provider/model_catalystcenter_floor.go @@ -0,0 +1,130 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type Floor struct { + Id types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + ParentName types.String `tfsdk:"parent_name"` + RfModel types.String `tfsdk:"rf_model"` + Width types.Float64 `tfsdk:"width"` + Length types.Float64 `tfsdk:"length"` + Height types.Float64 `tfsdk:"height"` +} + +//template:end types + +//template:begin getPath +func (data Floor) getPath() string { + return "/dna/intent/api/v1/site" +} + +//template:end getPath + +//template:begin toBody +func (data Floor) toBody(ctx context.Context, state Floor) string { + body := "" + body, _ = sjson.Set(body, "type", "floor") + if !data.Name.IsNull() { + body, _ = sjson.Set(body, "site.floor.name", data.Name.ValueString()) + } + if !data.ParentName.IsNull() { + body, _ = sjson.Set(body, "site.floor.parentName", data.ParentName.ValueString()) + } + if !data.RfModel.IsNull() { + body, _ = sjson.Set(body, "site.floor.rfModel", data.RfModel.ValueString()) + } + if !data.Width.IsNull() { + body, _ = sjson.Set(body, "site.floor.width", data.Width.ValueFloat64()) + } + if !data.Length.IsNull() { + body, _ = sjson.Set(body, "site.floor.length", data.Length.ValueFloat64()) + } + if !data.Height.IsNull() { + body, _ = sjson.Set(body, "site.floor.height", data.Height.ValueFloat64()) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *Floor) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("name"); value.Exists() { + data.Name = types.StringValue(value.String()) + } else { + data.Name = types.StringNull() + } + if value := res.Get("geometry.width"); value.Exists() { + data.Width = types.Float64Value(value.Float()) + } else { + data.Width = types.Float64Null() + } + if value := res.Get("geometry.length"); value.Exists() { + data.Length = types.Float64Value(value.Float()) + } else { + data.Length = types.Float64Null() + } + if value := res.Get("geometry.height"); value.Exists() { + data.Height = types.Float64Value(value.Float()) + } else { + data.Height = types.Float64Null() + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *Floor) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("name"); value.Exists() && !data.Name.IsNull() { + data.Name = types.StringValue(value.String()) + } else { + data.Name = types.StringNull() + } + if value := res.Get("geometry.width"); value.Exists() && !data.Width.IsNull() { + data.Width = types.Float64Value(value.Float()) + } else { + data.Width = types.Float64Null() + } + if value := res.Get("geometry.length"); value.Exists() && !data.Length.IsNull() { + data.Length = types.Float64Value(value.Float()) + } else { + data.Length = types.Float64Null() + } + if value := res.Get("geometry.height"); value.Exists() && !data.Height.IsNull() { + data.Height = types.Float64Value(value.Float()) + } else { + data.Height = types.Float64Null() + } +} + +//template:end updateFromBody diff --git a/internal/provider/model_catalystcenter_ip_pool.go b/internal/provider/model_catalystcenter_ip_pool.go new file mode 100644 index 00000000..1f21028e --- /dev/null +++ b/internal/provider/model_catalystcenter_ip_pool.go @@ -0,0 +1,151 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type IPPool struct { + Id types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + IpAddressSpace types.String `tfsdk:"ip_address_space"` + Type types.String `tfsdk:"type"` + IpSubnet types.String `tfsdk:"ip_subnet"` + Gateway types.String `tfsdk:"gateway"` + DhcpServerIps types.List `tfsdk:"dhcp_server_ips"` + DnsServerIps types.List `tfsdk:"dns_server_ips"` +} + +//template:end types + +//template:begin getPath +func (data IPPool) getPath() string { + return "/dna/intent/api/v1/global-pool" +} + +//template:end getPath + +//template:begin toBody +func (data IPPool) toBody(ctx context.Context, state IPPool) string { + body := "" + if data.Id.ValueString() != "" { + body, _ = sjson.Set(body, "settings.ippool.0.id", data.Id.ValueString()) + } + if !data.Name.IsNull() { + body, _ = sjson.Set(body, "settings.ippool.0.ipPoolName", data.Name.ValueString()) + } + if !data.IpAddressSpace.IsNull() { + body, _ = sjson.Set(body, "settings.ippool.0.IpAddressSpace", data.IpAddressSpace.ValueString()) + } + if !data.Type.IsNull() { + body, _ = sjson.Set(body, "settings.ippool.0.type", data.Type.ValueString()) + } + if !data.IpSubnet.IsNull() { + body, _ = sjson.Set(body, "settings.ippool.0.ipPoolCidr", data.IpSubnet.ValueString()) + } + if !data.Gateway.IsNull() { + body, _ = sjson.Set(body, "settings.ippool.0.gateway", data.Gateway.ValueString()) + } + if !data.DhcpServerIps.IsNull() { + var values []string + data.DhcpServerIps.ElementsAs(ctx, &values, false) + body, _ = sjson.Set(body, "settings.ippool.0.dhcpServerIps", values) + } + if !data.DnsServerIps.IsNull() { + var values []string + data.DnsServerIps.ElementsAs(ctx, &values, false) + body, _ = sjson.Set(body, "settings.ippool.0.dnsServerIps", values) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *IPPool) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("response.ipPoolName"); value.Exists() { + data.Name = types.StringValue(value.String()) + } else { + data.Name = types.StringNull() + } + if value := res.Get("response.ipPoolCidr"); value.Exists() { + data.IpSubnet = types.StringValue(value.String()) + } else { + data.IpSubnet = types.StringNull() + } + if value := res.Get("response.gateways.0"); value.Exists() { + data.Gateway = types.StringValue(value.String()) + } else { + data.Gateway = types.StringNull() + } + if value := res.Get("response.dhcpServerIps"); value.Exists() { + data.DhcpServerIps = helpers.GetStringList(value.Array()) + } else { + data.DhcpServerIps = types.ListNull(types.StringType) + } + if value := res.Get("response.dnsServerIps"); value.Exists() { + data.DnsServerIps = helpers.GetStringList(value.Array()) + } else { + data.DnsServerIps = types.ListNull(types.StringType) + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *IPPool) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("response.ipPoolName"); value.Exists() && !data.Name.IsNull() { + data.Name = types.StringValue(value.String()) + } else { + data.Name = types.StringNull() + } + if value := res.Get("response.ipPoolCidr"); value.Exists() && !data.IpSubnet.IsNull() { + data.IpSubnet = types.StringValue(value.String()) + } else { + data.IpSubnet = types.StringNull() + } + if value := res.Get("response.gateways.0"); value.Exists() && !data.Gateway.IsNull() { + data.Gateway = types.StringValue(value.String()) + } else { + data.Gateway = types.StringNull() + } + if value := res.Get("response.dhcpServerIps"); value.Exists() && !data.DhcpServerIps.IsNull() { + data.DhcpServerIps = helpers.GetStringList(value.Array()) + } else { + data.DhcpServerIps = types.ListNull(types.StringType) + } + if value := res.Get("response.dnsServerIps"); value.Exists() && !data.DnsServerIps.IsNull() { + data.DnsServerIps = helpers.GetStringList(value.Array()) + } else { + data.DnsServerIps = types.ListNull(types.StringType) + } +} + +//template:end updateFromBody diff --git a/internal/provider/model_catalystcenter_ip_pool_reservation.go b/internal/provider/model_catalystcenter_ip_pool_reservation.go new file mode 100644 index 00000000..f32e7a4b --- /dev/null +++ b/internal/provider/model_catalystcenter_ip_pool_reservation.go @@ -0,0 +1,164 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +//template:end imports + +//template:begin types +type IPPoolReservation struct { + Id types.String `tfsdk:"id"` + SiteId types.String `tfsdk:"site_id"` + Name types.String `tfsdk:"name"` + Type types.String `tfsdk:"type"` + Ipv6AddressSpace types.Bool `tfsdk:"ipv6_address_space"` + Ipv4GlobalPool types.String `tfsdk:"ipv4_global_pool"` + Ipv4Prefix types.Bool `tfsdk:"ipv4_prefix"` + Ipv4PrefixLength types.Int64 `tfsdk:"ipv4_prefix_length"` + Ipv4Subnet types.String `tfsdk:"ipv4_subnet"` + Ipv4Gateway types.String `tfsdk:"ipv4_gateway"` + Ipv4DhcpServers types.List `tfsdk:"ipv4_dhcp_servers"` + Ipv4DnsServers types.List `tfsdk:"ipv4_dns_servers"` + Ipv6GlobalPool types.String `tfsdk:"ipv6_global_pool"` + Ipv6Prefix types.Bool `tfsdk:"ipv6_prefix"` + Ipv6PrefixLength types.Int64 `tfsdk:"ipv6_prefix_length"` + Ipv6Subnet types.String `tfsdk:"ipv6_subnet"` + Ipv6Gateway types.String `tfsdk:"ipv6_gateway"` + Ipv6DhcpServers types.List `tfsdk:"ipv6_dhcp_servers"` + Ipv6DnsServers types.List `tfsdk:"ipv6_dns_servers"` + Ipv4TotalHost types.Int64 `tfsdk:"ipv4_total_host"` + Ipv6TotalHost types.Int64 `tfsdk:"ipv6_total_host"` + SlaacSupport types.Bool `tfsdk:"slaac_support"` +} + +//template:end types + +//template:begin getPath +func (data IPPoolReservation) getPath() string { + return "/dna/intent/api/v1/reserve-ip-subpool" +} + +//template:end getPath + +//template:begin toBody +func (data IPPoolReservation) toBody(ctx context.Context, state IPPoolReservation) string { + body := "" + if !data.Name.IsNull() { + body, _ = sjson.Set(body, "name", data.Name.ValueString()) + } + if !data.Type.IsNull() && data.Type != state.Type { + body, _ = sjson.Set(body, "type", data.Type.ValueString()) + } + if !data.Ipv6AddressSpace.IsNull() { + body, _ = sjson.Set(body, "ipv6AddressSpace", data.Ipv6AddressSpace.ValueBool()) + } + if !data.Ipv4GlobalPool.IsNull() && data.Ipv4GlobalPool != state.Ipv4GlobalPool { + body, _ = sjson.Set(body, "ipv4GlobalPool", data.Ipv4GlobalPool.ValueString()) + } + if !data.Ipv4Prefix.IsNull() && data.Ipv4Prefix != state.Ipv4Prefix { + body, _ = sjson.Set(body, "ipv4Prefix", data.Ipv4Prefix.ValueBool()) + } + if !data.Ipv4PrefixLength.IsNull() && data.Ipv4PrefixLength != state.Ipv4PrefixLength { + body, _ = sjson.Set(body, "ipv4PrefixLength", data.Ipv4PrefixLength.ValueInt64()) + } + if !data.Ipv4Subnet.IsNull() && data.Ipv4Subnet != state.Ipv4Subnet { + body, _ = sjson.Set(body, "ipv4Subnet", data.Ipv4Subnet.ValueString()) + } + if !data.Ipv4Gateway.IsNull() { + body, _ = sjson.Set(body, "ipv4GateWay", data.Ipv4Gateway.ValueString()) + } + if !data.Ipv4DhcpServers.IsNull() { + var values []string + data.Ipv4DhcpServers.ElementsAs(ctx, &values, false) + body, _ = sjson.Set(body, "ipv4DhcpServers", values) + } + if !data.Ipv4DnsServers.IsNull() { + var values []string + data.Ipv4DnsServers.ElementsAs(ctx, &values, false) + body, _ = sjson.Set(body, "ipv4DnsServers", values) + } + if !data.Ipv6GlobalPool.IsNull() { + body, _ = sjson.Set(body, "ipv6GlobalPool", data.Ipv6GlobalPool.ValueString()) + } + if !data.Ipv6Prefix.IsNull() { + body, _ = sjson.Set(body, "ipv6Prefix", data.Ipv6Prefix.ValueBool()) + } + if !data.Ipv6PrefixLength.IsNull() { + body, _ = sjson.Set(body, "ipv6PrefixLength", data.Ipv6PrefixLength.ValueInt64()) + } + if !data.Ipv6Subnet.IsNull() { + body, _ = sjson.Set(body, "ipv6Subnet", data.Ipv6Subnet.ValueString()) + } + if !data.Ipv6Gateway.IsNull() { + body, _ = sjson.Set(body, "ipv6GateWay", data.Ipv6Gateway.ValueString()) + } + if !data.Ipv6DhcpServers.IsNull() { + var values []string + data.Ipv6DhcpServers.ElementsAs(ctx, &values, false) + body, _ = sjson.Set(body, "ipv6DhcpServers", values) + } + if !data.Ipv6DnsServers.IsNull() { + var values []string + data.Ipv6DnsServers.ElementsAs(ctx, &values, false) + body, _ = sjson.Set(body, "ipv6DnsServers", values) + } + if !data.Ipv4TotalHost.IsNull() { + body, _ = sjson.Set(body, "ipv4TotalHost", data.Ipv4TotalHost.ValueInt64()) + } + if !data.Ipv6TotalHost.IsNull() { + body, _ = sjson.Set(body, "ipv6TotalHost", data.Ipv6TotalHost.ValueInt64()) + } + if !data.SlaacSupport.IsNull() { + body, _ = sjson.Set(body, "slaacSupport", data.SlaacSupport.ValueBool()) + } + return body +} + +//template:end toBody + +//template:begin fromBody +func (data *IPPoolReservation) fromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("response.0.groupName"); value.Exists() { + data.Name = types.StringValue(value.String()) + } else { + data.Name = types.StringNull() + } +} + +//template:end fromBody + +//template:begin updateFromBody +func (data *IPPoolReservation) updateFromBody(ctx context.Context, res gjson.Result) { + if value := res.Get("response.0.groupName"); value.Exists() && !data.Name.IsNull() { + data.Name = types.StringValue(value.String()) + } else { + data.Name = types.StringNull() + } +} + +//template:end updateFromBody diff --git a/internal/provider/provider.go b/internal/provider/provider.go new file mode 100644 index 00000000..5c01940a --- /dev/null +++ b/internal/provider/provider.go @@ -0,0 +1,281 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin provider +import ( + "context" + "os" + "strconv" + + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/provider" + "github.com/hashicorp/terraform-plugin-framework/provider/schema" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + cc "github.com/netascode/go-catalystcenter" +) + +// CcProvider defines the provider implementation. +type CcProvider struct { + // version is set to the provider version on release, "dev" when the + // provider is built and ran locally, and "test" when running acceptance + // testing. + version string +} + +// CcProviderModel describes the provider data model. +type CcProviderModel struct { + Username types.String `tfsdk:"username"` + Password types.String `tfsdk:"password"` + URL types.String `tfsdk:"url"` + Insecure types.Bool `tfsdk:"insecure"` + Retries types.Int64 `tfsdk:"retries"` +} + +// CcProviderData describes the data maintained by the provider. +type CcProviderData struct { + Client *cc.Client +} + +// Metadata returns the provider type name. +func (p *CcProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) { + resp.TypeName = "catalystcenter" + resp.Version = p.version +} + +func (p *CcProvider) Schema(ctx context.Context, req provider.SchemaRequest, resp *provider.SchemaResponse) { + resp.Schema = schema.Schema{ + Attributes: map[string]schema.Attribute{ + "username": schema.StringAttribute{ + MarkdownDescription: "Username for the Catalyst Center instance. This can also be set as the CC_USERNAME environment variable.", + Optional: true, + }, + "password": schema.StringAttribute{ + MarkdownDescription: "Password for the Catalyst Center instance. This can also be set as the CC_PASSWORD environment variable.", + Optional: true, + Sensitive: true, + }, + "url": schema.StringAttribute{ + MarkdownDescription: "URL of the Catalyst Center instance. This can also be set as the CC_URL environment variable.", + Optional: true, + }, + "insecure": schema.BoolAttribute{ + MarkdownDescription: "Allow insecure HTTPS client. This can also be set as the CC_INSECURE environment variable. Defaults to `true`.", + Optional: true, + }, + "retries": schema.Int64Attribute{ + MarkdownDescription: "Number of retries for REST API calls. This can also be set as the CC_RETRIES environment variable. Defaults to `3`.", + Optional: true, + Validators: []validator.Int64{ + int64validator.Between(0, 9), + }, + }, + }, + } +} + +func (p *CcProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { + // Retrieve provider data from configuration + var config CcProviderModel + diags := req.Config.Get(ctx, &config) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + // User must provide a username to the provider + var username string + if config.Username.IsUnknown() { + // Cannot connect to client with an unknown value + resp.Diagnostics.AddWarning( + "Unable to create client", + "Cannot use unknown value as username", + ) + return + } + + if config.Username.IsNull() { + username = os.Getenv("CC_USERNAME") + } else { + username = config.Username.ValueString() + } + + if username == "" { + // Error vs warning - empty value must stop execution + resp.Diagnostics.AddError( + "Unable to find username", + "Username cannot be an empty string", + ) + return + } + + // User must provide a password to the provider + var password string + if config.Password.IsUnknown() { + // Cannot connect to client with an unknown value + resp.Diagnostics.AddWarning( + "Unable to create client", + "Cannot use unknown value as password", + ) + return + } + + if config.Password.IsNull() { + password = os.Getenv("CC_PASSWORD") + } else { + password = config.Password.ValueString() + } + + if password == "" { + // Error vs warning - empty value must stop execution + resp.Diagnostics.AddError( + "Unable to find password", + "Password cannot be an empty string", + ) + return + } + + // User must provide a username to the provider + var url string + if config.URL.IsUnknown() { + // Cannot connect to client with an unknown value + resp.Diagnostics.AddWarning( + "Unable to create client", + "Cannot use unknown value as url", + ) + return + } + + if config.URL.IsNull() { + url = os.Getenv("CC_URL") + } else { + url = config.URL.ValueString() + } + + if url == "" { + // Error vs warning - empty value must stop execution + resp.Diagnostics.AddError( + "Unable to find url", + "URL cannot be an empty string", + ) + return + } + + var insecure bool + if config.Insecure.IsUnknown() { + // Cannot connect to client with an unknown value + resp.Diagnostics.AddWarning( + "Unable to create client", + "Cannot use unknown value as insecure", + ) + return + } + + if config.Insecure.IsNull() { + insecureStr := os.Getenv("CC_INSECURE") + if insecureStr == "" { + insecure = true + } else { + insecure, _ = strconv.ParseBool(insecureStr) + } + } else { + insecure = config.Insecure.ValueBool() + } + + var retries int64 + if config.Retries.IsUnknown() { + // Cannot connect to client with an unknown value + resp.Diagnostics.AddWarning( + "Unable to create client", + "Cannot use unknown value as retries", + ) + return + } + + if config.Retries.IsNull() { + retriesStr := os.Getenv("CC_RETRIES") + if retriesStr == "" { + retries = 3 + } else { + retries, _ = strconv.ParseInt(retriesStr, 0, 64) + } + } else { + retries = config.Retries.ValueInt64() + } + + // Create a new catalyst center client and set it to the provider client + c, err := cc.NewClient(url, username, password, cc.Insecure(insecure), cc.MaxRetries(int(retries))) + if err != nil { + resp.Diagnostics.AddError( + "Unable to create client", + "Unable to create catalyst center client:\n\n"+err.Error(), + ) + return + } + + data := CcProviderData{Client: &c} + resp.DataSourceData = &data + resp.ResourceData = &data +} + +func (p *CcProvider) Resources(ctx context.Context) []func() resource.Resource { + return []func() resource.Resource{ + NewAreaResource, + NewBuildingResource, + NewCredentialsCLIResource, + NewCredentialsHTTPSReadResource, + NewCredentialsHTTPSWriteResource, + NewCredentialsSNMPv2ReadResource, + NewCredentialsSNMPv2WriteResource, + NewCredentialsSNMPv3Resource, + NewFloorResource, + NewIPPoolResource, + NewIPPoolReservationResource, + } +} + +func (p *CcProvider) DataSources(ctx context.Context) []func() datasource.DataSource { + return []func() datasource.DataSource{ + NewAreaDataSource, + NewBuildingDataSource, + NewCredentialsCLIDataSource, + NewCredentialsHTTPSReadDataSource, + NewCredentialsHTTPSWriteDataSource, + NewCredentialsSNMPv2ReadDataSource, + NewCredentialsSNMPv2WriteDataSource, + NewCredentialsSNMPv3DataSource, + NewFloorDataSource, + NewIPPoolDataSource, + NewIPPoolReservationDataSource, + } +} + +func New(version string) func() provider.Provider { + return func() provider.Provider { + return &CcProvider{ + version: version, + } + } +} + +//template:end provider diff --git a/internal/provider/provider_test.go b/internal/provider/provider_test.go new file mode 100644 index 00000000..ed215199 --- /dev/null +++ b/internal/provider/provider_test.go @@ -0,0 +1,49 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +package provider + +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-framework/providerserver" + "github.com/hashicorp/terraform-plugin-go/tfprotov6" +) + +// testAccProtoV6ProviderFactories are used to instantiate a provider during +// acceptance testing. The factory function will be invoked for every Terraform +// CLI command executed to create a provider server to which the CLI can +// reattach. +var testAccProtoV6ProviderFactories = map[string]func() (tfprotov6.ProviderServer, error){ + "catalystcenter": providerserver.NewProtocol6WithError(New("test")()), +} + +func testAccPreCheck(t *testing.T) { + // You can add code here to run prior to any test case execution, for example assertions + // about the appropriate environment variables being set are common to see in a pre-check + // function. + if v := os.Getenv("CC_USERNAME"); v == "" { + t.Fatal("CC_USERNAME env variable must be set for acceptance tests") + } + if v := os.Getenv("CC_PASSWORD"); v == "" { + t.Fatal("CC_PASSWORD env variable must be set for acceptance tests") + } + if v := os.Getenv("CC_URL"); v == "" { + t.Fatal("CC_URL env variable must be set for acceptance tests") + } +} diff --git a/internal/provider/resource_catalystcenter_area.go b/internal/provider/resource_catalystcenter_area.go new file mode 100644 index 00000000..d95b0f69 --- /dev/null +++ b/internal/provider/resource_catalystcenter_area.go @@ -0,0 +1,226 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &AreaResource{} +var _ resource.ResourceWithImportState = &AreaResource{} + +func NewAreaResource() resource.Resource { + return &AreaResource{} +} + +type AreaResource struct { + client *cc.Client +} + +func (r *AreaResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_area" +} + +func (r *AreaResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage an Area.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "name": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The name of the area").String, + Required: true, + }, + "parent_name": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The path of the parent area, e.g. `Global/Area5`. `Global` in case of root area.").String, + Optional: true, + }, + }, + } +} + +func (r *AreaResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *AreaResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan Area + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, Area{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("siteId").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *AreaResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state Area + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + params += "?id=" + state.Id.ValueString() + res, err := r.client.Get("/dna/intent/api/v2/site" + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *AreaResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state Area + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + + res, err := r.client.Put(plan.getPath()+"/"+plan.Id.ValueString()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *AreaResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state Area + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *AreaResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_area_test.go b/internal/provider/resource_catalystcenter_area_test.go new file mode 100644 index 00000000..1c1d84bf --- /dev/null +++ b/internal/provider/resource_catalystcenter_area_test.go @@ -0,0 +1,83 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcArea(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_area.test", "name", "Area1")) + + var steps []resource.TestStep + if os.Getenv("SKIP_MINIMUM_TEST") == "" { + steps = append(steps, resource.TestStep{ + Config: testAccCcAreaConfig_minimum(), + }) + } + steps = append(steps, resource.TestStep{ + Config: testAccCcAreaConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_area.test", + ImportState: true, + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcAreaConfig_minimum() string { + config := `resource "catalystcenter_area" "test" {` + "\n" + config += ` name = "Area1"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcAreaConfig_all() string { + config := `resource "catalystcenter_area" "test" {` + "\n" + config += ` name = "Area1"` + "\n" + config += ` parent_name = "Global"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/internal/provider/resource_catalystcenter_building.go b/internal/provider/resource_catalystcenter_building.go new file mode 100644 index 00000000..162bb4e9 --- /dev/null +++ b/internal/provider/resource_catalystcenter_building.go @@ -0,0 +1,242 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &BuildingResource{} +var _ resource.ResourceWithImportState = &BuildingResource{} + +func NewBuildingResource() resource.Resource { + return &BuildingResource{} +} + +type BuildingResource struct { + client *cc.Client +} + +func (r *BuildingResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_building" +} + +func (r *BuildingResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage a Building.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "name": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The name of the building").String, + Required: true, + }, + "parent_name": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The path of the parent area, e.g. `Global/Area5`. `Global` in case of root area.").String, + Required: true, + }, + "country": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The country of the building").String, + Required: true, + }, + "address": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The address of the building").String, + Required: true, + }, + "latitude": schema.Float64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("Latitude").String, + Required: true, + }, + "longitude": schema.Float64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("Longitude").String, + Required: true, + }, + }, + } +} + +func (r *BuildingResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *BuildingResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan Building + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, Building{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("siteId").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *BuildingResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state Building + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + params += "?id=" + state.Id.ValueString() + res, err := r.client.Get("/dna/intent/api/v2/site" + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *BuildingResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state Building + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + + res, err := r.client.Put(plan.getPath()+"/"+plan.Id.ValueString()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *BuildingResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state Building + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *BuildingResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_building_test.go b/internal/provider/resource_catalystcenter_building_test.go new file mode 100644 index 00000000..22566a1e --- /dev/null +++ b/internal/provider/resource_catalystcenter_building_test.go @@ -0,0 +1,96 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcBuilding(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_building.test", "name", "Building1")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_building.test", "country", "United States")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_building.test", "address", "150 W Tasman Dr, San Jose")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_building.test", "latitude", "37.338")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_building.test", "longitude", "-121.832")) + + var steps []resource.TestStep + if os.Getenv("SKIP_MINIMUM_TEST") == "" { + steps = append(steps, resource.TestStep{ + Config: testAccCcBuildingConfig_minimum(), + }) + } + steps = append(steps, resource.TestStep{ + Config: testAccCcBuildingConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_building.test", + ImportState: true, + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcBuildingConfig_minimum() string { + config := `resource "catalystcenter_building" "test" {` + "\n" + config += ` name = "Building1"` + "\n" + config += ` parent_name = "Global"` + "\n" + config += ` country = "United States"` + "\n" + config += ` address = "150 W Tasman Dr, San Jose"` + "\n" + config += ` latitude = 37.338` + "\n" + config += ` longitude = -121.832` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcBuildingConfig_all() string { + config := `resource "catalystcenter_building" "test" {` + "\n" + config += ` name = "Building1"` + "\n" + config += ` parent_name = "Global"` + "\n" + config += ` country = "United States"` + "\n" + config += ` address = "150 W Tasman Dr, San Jose"` + "\n" + config += ` latitude = 37.338` + "\n" + config += ` longitude = -121.832` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/internal/provider/resource_catalystcenter_credentials_cli.go b/internal/provider/resource_catalystcenter_credentials_cli.go new file mode 100644 index 00000000..16b57011 --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_cli.go @@ -0,0 +1,243 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &CredentialsCLIResource{} +var _ resource.ResourceWithImportState = &CredentialsCLIResource{} + +func NewCredentialsCLIResource() resource.Resource { + return &CredentialsCLIResource{} +} + +type CredentialsCLIResource struct { + client *cc.Client +} + +func (r *CredentialsCLIResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_cli" +} + +func (r *CredentialsCLIResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage a Credentials CLI.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "description": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The description of the CLI credentials").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "username": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Username").String, + Required: true, + }, + "password": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Password").String, + Required: true, + }, + "enable_password": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Enable password").String, + Optional: true, + }, + }, + } +} + +func (r *CredentialsCLIResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *CredentialsCLIResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan CredentialsCLI + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, CredentialsCLI{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + params = "" + res, err = r.client.Get(plan.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("response.cliCredential.#(description==\"" + plan.Description.ValueString() + "\").id").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *CredentialsCLIResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state CredentialsCLI + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + res, err := r.client.Get(state.getPath() + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + res = res.Get("response.cliCredential.#(id==\"" + state.Id.ValueString() + "\")") + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *CredentialsCLIResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state CredentialsCLI + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + + res, err := r.client.Put(plan.getPath()+"/"+plan.Id.ValueString()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *CredentialsCLIResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state CredentialsCLI + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *CredentialsCLIResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_credentials_cli_test.go b/internal/provider/resource_catalystcenter_credentials_cli_test.go new file mode 100644 index 00000000..bdabd6e9 --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_cli_test.go @@ -0,0 +1,87 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcCredentialsCLI(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_cli.test", "description", "My CLI credentials")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_cli.test", "username", "user1")) + + var steps []resource.TestStep + if os.Getenv("SKIP_MINIMUM_TEST") == "" { + steps = append(steps, resource.TestStep{ + Config: testAccCcCredentialsCLIConfig_minimum(), + }) + } + steps = append(steps, resource.TestStep{ + Config: testAccCcCredentialsCLIConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_credentials_cli.test", + ImportState: true, + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcCredentialsCLIConfig_minimum() string { + config := `resource "catalystcenter_credentials_cli" "test" {` + "\n" + config += ` description = "My CLI credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` password = "password1"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcCredentialsCLIConfig_all() string { + config := `resource "catalystcenter_credentials_cli" "test" {` + "\n" + config += ` description = "My CLI credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` password = "password1"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/internal/provider/resource_catalystcenter_credentials_https_read.go b/internal/provider/resource_catalystcenter_credentials_https_read.go new file mode 100644 index 00000000..ec506171 --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_https_read.go @@ -0,0 +1,246 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &CredentialsHTTPSReadResource{} +var _ resource.ResourceWithImportState = &CredentialsHTTPSReadResource{} + +func NewCredentialsHTTPSReadResource() resource.Resource { + return &CredentialsHTTPSReadResource{} +} + +type CredentialsHTTPSReadResource struct { + client *cc.Client +} + +func (r *CredentialsHTTPSReadResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_https_read" +} + +func (r *CredentialsHTTPSReadResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage a Credentials HTTPS Read.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "description": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The description of the HTTPS credentials").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "username": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Username").String, + Required: true, + }, + "password": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Password").String, + Required: true, + }, + "port": schema.Int64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("HTTPS port").AddDefaultValueDescription("443").String, + Optional: true, + Computed: true, + Default: int64default.StaticInt64(443), + }, + }, + } +} + +func (r *CredentialsHTTPSReadResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *CredentialsHTTPSReadResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan CredentialsHTTPSRead + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, CredentialsHTTPSRead{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + params = "" + res, err = r.client.Get(plan.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("response.httpsRead.#(description==\"" + plan.Description.ValueString() + "\").id").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *CredentialsHTTPSReadResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state CredentialsHTTPSRead + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + res, err := r.client.Get(state.getPath() + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + res = res.Get("response.httpsRead.#(id==\"" + state.Id.ValueString() + "\")") + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *CredentialsHTTPSReadResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state CredentialsHTTPSRead + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + + res, err := r.client.Put(plan.getPath()+"/"+plan.Id.ValueString()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *CredentialsHTTPSReadResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state CredentialsHTTPSRead + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *CredentialsHTTPSReadResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_credentials_https_read_test.go b/internal/provider/resource_catalystcenter_credentials_https_read_test.go new file mode 100644 index 00000000..34f0feff --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_https_read_test.go @@ -0,0 +1,83 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcCredentialsHTTPSRead(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_https_read.test", "description", "My HTTPS read credentials")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_https_read.test", "username", "user1")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_https_read.test", "port", "444")) + + var steps []resource.TestStep + steps = append(steps, resource.TestStep{ + Config: testAccCcCredentialsHTTPSReadConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_credentials_https_read.test", + ImportState: true, + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcCredentialsHTTPSReadConfig_minimum() string { + config := `resource "catalystcenter_credentials_https_read" "test" {` + "\n" + config += ` description = "My HTTPS read credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` password = "password1"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcCredentialsHTTPSReadConfig_all() string { + config := `resource "catalystcenter_credentials_https_read" "test" {` + "\n" + config += ` description = "My HTTPS read credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` password = "password1"` + "\n" + config += ` port = 444` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/internal/provider/resource_catalystcenter_credentials_https_write.go b/internal/provider/resource_catalystcenter_credentials_https_write.go new file mode 100644 index 00000000..4b0e872e --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_https_write.go @@ -0,0 +1,246 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &CredentialsHTTPSWriteResource{} +var _ resource.ResourceWithImportState = &CredentialsHTTPSWriteResource{} + +func NewCredentialsHTTPSWriteResource() resource.Resource { + return &CredentialsHTTPSWriteResource{} +} + +type CredentialsHTTPSWriteResource struct { + client *cc.Client +} + +func (r *CredentialsHTTPSWriteResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_https_write" +} + +func (r *CredentialsHTTPSWriteResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage a Credentials HTTPS Write.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "description": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The description of the HTTPS credentials").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "username": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Username").String, + Required: true, + }, + "password": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Password").String, + Required: true, + }, + "port": schema.Int64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("HTTPS port").AddDefaultValueDescription("443").String, + Optional: true, + Computed: true, + Default: int64default.StaticInt64(443), + }, + }, + } +} + +func (r *CredentialsHTTPSWriteResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *CredentialsHTTPSWriteResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan CredentialsHTTPSWrite + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, CredentialsHTTPSWrite{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + params = "" + res, err = r.client.Get(plan.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("response.httpsWrite.#(description==\"" + plan.Description.ValueString() + "\").id").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *CredentialsHTTPSWriteResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state CredentialsHTTPSWrite + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + res, err := r.client.Get(state.getPath() + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + res = res.Get("response.httpsWrite.#(id==\"" + state.Id.ValueString() + "\")") + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *CredentialsHTTPSWriteResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state CredentialsHTTPSWrite + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + + res, err := r.client.Put(plan.getPath()+"/"+plan.Id.ValueString()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *CredentialsHTTPSWriteResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state CredentialsHTTPSWrite + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *CredentialsHTTPSWriteResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_credentials_https_write_test.go b/internal/provider/resource_catalystcenter_credentials_https_write_test.go new file mode 100644 index 00000000..7144b4d3 --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_https_write_test.go @@ -0,0 +1,83 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcCredentialsHTTPSWrite(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_https_write.test", "description", "My HTTPS write credentials")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_https_write.test", "username", "user1")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_https_write.test", "port", "444")) + + var steps []resource.TestStep + steps = append(steps, resource.TestStep{ + Config: testAccCcCredentialsHTTPSWriteConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_credentials_https_write.test", + ImportState: true, + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcCredentialsHTTPSWriteConfig_minimum() string { + config := `resource "catalystcenter_credentials_https_write" "test" {` + "\n" + config += ` description = "My HTTPS write credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` password = "password1"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcCredentialsHTTPSWriteConfig_all() string { + config := `resource "catalystcenter_credentials_https_write" "test" {` + "\n" + config += ` description = "My HTTPS write credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` password = "password1"` + "\n" + config += ` port = 444` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/internal/provider/resource_catalystcenter_credentials_snmpv2_read.go b/internal/provider/resource_catalystcenter_credentials_snmpv2_read.go new file mode 100644 index 00000000..0077d4c3 --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_snmpv2_read.go @@ -0,0 +1,235 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &CredentialsSNMPv2ReadResource{} +var _ resource.ResourceWithImportState = &CredentialsSNMPv2ReadResource{} + +func NewCredentialsSNMPv2ReadResource() resource.Resource { + return &CredentialsSNMPv2ReadResource{} +} + +type CredentialsSNMPv2ReadResource struct { + client *cc.Client +} + +func (r *CredentialsSNMPv2ReadResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_snmpv2_read" +} + +func (r *CredentialsSNMPv2ReadResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage a Credentials SNMPv2 Read.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "description": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The description of the SNMPv2 credentials").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "read_community": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Read community").String, + Required: true, + }, + }, + } +} + +func (r *CredentialsSNMPv2ReadResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *CredentialsSNMPv2ReadResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan CredentialsSNMPv2Read + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, CredentialsSNMPv2Read{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + params = "" + res, err = r.client.Get(plan.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("response.snmpV2cRead.#(description==\"" + plan.Description.ValueString() + "\").id").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *CredentialsSNMPv2ReadResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state CredentialsSNMPv2Read + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + res, err := r.client.Get(state.getPath() + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + res = res.Get("response.snmpV2cRead.#(id==\"" + state.Id.ValueString() + "\")") + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *CredentialsSNMPv2ReadResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state CredentialsSNMPv2Read + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + + res, err := r.client.Put(plan.getPath()+"/"+plan.Id.ValueString()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *CredentialsSNMPv2ReadResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state CredentialsSNMPv2Read + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *CredentialsSNMPv2ReadResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_credentials_snmpv2_read_test.go b/internal/provider/resource_catalystcenter_credentials_snmpv2_read_test.go new file mode 100644 index 00000000..0e9eec11 --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_snmpv2_read_test.go @@ -0,0 +1,84 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcCredentialsSNMPv2Read(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_snmpv2_read.test", "description", "My SNMPv2 read credentials")) + + var steps []resource.TestStep + if os.Getenv("SKIP_MINIMUM_TEST") == "" { + steps = append(steps, resource.TestStep{ + Config: testAccCcCredentialsSNMPv2ReadConfig_minimum(), + }) + } + steps = append(steps, resource.TestStep{ + Config: testAccCcCredentialsSNMPv2ReadConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_credentials_snmpv2_read.test", + ImportState: true, + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcCredentialsSNMPv2ReadConfig_minimum() string { + config := `resource "catalystcenter_credentials_snmpv2_read" "test" {` + "\n" + config += ` description = "My SNMPv2 read credentials"` + "\n" + config += ` read_community = "community1"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcCredentialsSNMPv2ReadConfig_all() string { + config := `resource "catalystcenter_credentials_snmpv2_read" "test" {` + "\n" + config += ` description = "My SNMPv2 read credentials"` + "\n" + config += ` read_community = "community1"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/internal/provider/resource_catalystcenter_credentials_snmpv2_write.go b/internal/provider/resource_catalystcenter_credentials_snmpv2_write.go new file mode 100644 index 00000000..855299a7 --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_snmpv2_write.go @@ -0,0 +1,235 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &CredentialsSNMPv2WriteResource{} +var _ resource.ResourceWithImportState = &CredentialsSNMPv2WriteResource{} + +func NewCredentialsSNMPv2WriteResource() resource.Resource { + return &CredentialsSNMPv2WriteResource{} +} + +type CredentialsSNMPv2WriteResource struct { + client *cc.Client +} + +func (r *CredentialsSNMPv2WriteResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_snmpv2_write" +} + +func (r *CredentialsSNMPv2WriteResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage a Credentials SNMPv2 Write.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "description": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The description of the SNMPv2 credentials").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "write_community": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Write community").String, + Required: true, + }, + }, + } +} + +func (r *CredentialsSNMPv2WriteResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *CredentialsSNMPv2WriteResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan CredentialsSNMPv2Write + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, CredentialsSNMPv2Write{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + params = "" + res, err = r.client.Get(plan.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("response.snmpV2cWrite.#(description==\"" + plan.Description.ValueString() + "\").id").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *CredentialsSNMPv2WriteResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state CredentialsSNMPv2Write + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + res, err := r.client.Get(state.getPath() + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + res = res.Get("response.snmpV2cWrite.#(id==\"" + state.Id.ValueString() + "\")") + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *CredentialsSNMPv2WriteResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state CredentialsSNMPv2Write + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + + res, err := r.client.Put(plan.getPath()+"/"+plan.Id.ValueString()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *CredentialsSNMPv2WriteResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state CredentialsSNMPv2Write + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *CredentialsSNMPv2WriteResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_credentials_snmpv2_write_test.go b/internal/provider/resource_catalystcenter_credentials_snmpv2_write_test.go new file mode 100644 index 00000000..19f334bb --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_snmpv2_write_test.go @@ -0,0 +1,84 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcCredentialsSNMPv2Write(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_snmpv2_write.test", "description", "My SNMPv2 write credentials")) + + var steps []resource.TestStep + if os.Getenv("SKIP_MINIMUM_TEST") == "" { + steps = append(steps, resource.TestStep{ + Config: testAccCcCredentialsSNMPv2WriteConfig_minimum(), + }) + } + steps = append(steps, resource.TestStep{ + Config: testAccCcCredentialsSNMPv2WriteConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_credentials_snmpv2_write.test", + ImportState: true, + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcCredentialsSNMPv2WriteConfig_minimum() string { + config := `resource "catalystcenter_credentials_snmpv2_write" "test" {` + "\n" + config += ` description = "My SNMPv2 write credentials"` + "\n" + config += ` write_community = "community1"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcCredentialsSNMPv2WriteConfig_all() string { + config := `resource "catalystcenter_credentials_snmpv2_write" "test" {` + "\n" + config += ` description = "My SNMPv2 write credentials"` + "\n" + config += ` write_community = "community1"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/internal/provider/resource_catalystcenter_credentials_snmpv3.go b/internal/provider/resource_catalystcenter_credentials_snmpv3.go new file mode 100644 index 00000000..7142bc75 --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_snmpv3.go @@ -0,0 +1,266 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &CredentialsSNMPv3Resource{} +var _ resource.ResourceWithImportState = &CredentialsSNMPv3Resource{} + +func NewCredentialsSNMPv3Resource() resource.Resource { + return &CredentialsSNMPv3Resource{} +} + +type CredentialsSNMPv3Resource struct { + client *cc.Client +} + +func (r *CredentialsSNMPv3Resource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_credentials_snmpv3" +} + +func (r *CredentialsSNMPv3Resource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage a Credentials SNMPv3.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "description": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The description of the SNMPv3 credentials").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "username": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Username").String, + Required: true, + }, + "privacy_type": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Privacy type").AddStringEnumDescription("AES128", "AES192", "AES256").String, + Optional: true, + Validators: []validator.String{ + stringvalidator.OneOf("AES128", "AES192", "AES256"), + }, + }, + "privacy_password": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Privacy password").String, + Optional: true, + }, + "auth_type": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Authentication type").AddStringEnumDescription("SHA", "MD5").String, + Optional: true, + Validators: []validator.String{ + stringvalidator.OneOf("SHA", "MD5"), + }, + }, + "auth_password": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Authentication password").String, + Optional: true, + }, + "snmp_mode": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("SNMP mode").AddStringEnumDescription("AUTHPRIV", "AUTHNOPRIV", "NOAUTHNOPRIV").String, + Required: true, + Validators: []validator.String{ + stringvalidator.OneOf("AUTHPRIV", "AUTHNOPRIV", "NOAUTHNOPRIV"), + }, + }, + }, + } +} + +func (r *CredentialsSNMPv3Resource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *CredentialsSNMPv3Resource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan CredentialsSNMPv3 + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, CredentialsSNMPv3{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + params = "" + res, err = r.client.Get(plan.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("response.snmpV3.#(description==\"" + plan.Description.ValueString() + "\").id").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *CredentialsSNMPv3Resource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state CredentialsSNMPv3 + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + res, err := r.client.Get(state.getPath() + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + res = res.Get("response.snmpV3.#(id==\"" + state.Id.ValueString() + "\")") + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *CredentialsSNMPv3Resource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state CredentialsSNMPv3 + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + + res, err := r.client.Put(plan.getPath()+"/"+plan.Id.ValueString()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *CredentialsSNMPv3Resource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state CredentialsSNMPv3 + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *CredentialsSNMPv3Resource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_credentials_snmpv3_test.go b/internal/provider/resource_catalystcenter_credentials_snmpv3_test.go new file mode 100644 index 00000000..568e2eee --- /dev/null +++ b/internal/provider/resource_catalystcenter_credentials_snmpv3_test.go @@ -0,0 +1,88 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcCredentialsSNMPv3(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_snmpv3.test", "description", "My SNMPv3 credentials")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_snmpv3.test", "username", "user1")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_snmpv3.test", "privacy_type", "AES128")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_snmpv3.test", "auth_type", "SHA")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_credentials_snmpv3.test", "snmp_mode", "AUTHPRIV")) + + var steps []resource.TestStep + steps = append(steps, resource.TestStep{ + Config: testAccCcCredentialsSNMPv3Config_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_credentials_snmpv3.test", + ImportState: true, + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcCredentialsSNMPv3Config_minimum() string { + config := `resource "catalystcenter_credentials_snmpv3" "test" {` + "\n" + config += ` description = "My SNMPv3 credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` snmp_mode = "AUTHPRIV"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcCredentialsSNMPv3Config_all() string { + config := `resource "catalystcenter_credentials_snmpv3" "test" {` + "\n" + config += ` description = "My SNMPv3 credentials"` + "\n" + config += ` username = "user1"` + "\n" + config += ` privacy_type = "AES128"` + "\n" + config += ` privacy_password = "password1"` + "\n" + config += ` auth_type = "SHA"` + "\n" + config += ` auth_password = "password1"` + "\n" + config += ` snmp_mode = "AUTHPRIV"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/internal/provider/resource_catalystcenter_floor.go b/internal/provider/resource_catalystcenter_floor.go new file mode 100644 index 00000000..73c60438 --- /dev/null +++ b/internal/provider/resource_catalystcenter_floor.go @@ -0,0 +1,247 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &FloorResource{} +var _ resource.ResourceWithImportState = &FloorResource{} + +func NewFloorResource() resource.Resource { + return &FloorResource{} +} + +type FloorResource struct { + client *cc.Client +} + +func (r *FloorResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_floor" +} + +func (r *FloorResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage a Floor.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "name": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The name of the floor").String, + Required: true, + }, + "parent_name": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The path of the parent building, e.g. `Global/Building1`").String, + Required: true, + }, + "rf_model": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The RF model").AddStringEnumDescription("Cubes And Walled Offices", "Drywall Office Only", "Indoor High Ceiling", "Outdoor Open Space").String, + Required: true, + Validators: []validator.String{ + stringvalidator.OneOf("Cubes And Walled Offices", "Drywall Office Only", "Indoor High Ceiling", "Outdoor Open Space"), + }, + }, + "width": schema.Float64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("Width").String, + Required: true, + }, + "length": schema.Float64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("Length").String, + Required: true, + }, + "height": schema.Float64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("Height").String, + Required: true, + }, + }, + } +} + +func (r *FloorResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *FloorResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan Floor + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, Floor{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("siteId").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *FloorResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state Floor + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + params += "/" + state.Id.ValueString() + res, err := r.client.Get("/api/v1/dna-maps-service/domains" + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *FloorResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state Floor + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + + res, err := r.client.Put(plan.getPath()+"/"+plan.Id.ValueString()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *FloorResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state Floor + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *FloorResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_floor_test.go b/internal/provider/resource_catalystcenter_floor_test.go new file mode 100644 index 00000000..9ff61b4f --- /dev/null +++ b/internal/provider/resource_catalystcenter_floor_test.go @@ -0,0 +1,107 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcFloor(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_floor.test", "name", "Floor1")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_floor.test", "width", "30.5")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_floor.test", "length", "50.5")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_floor.test", "height", "3.5")) + + var steps []resource.TestStep + if os.Getenv("SKIP_MINIMUM_TEST") == "" { + steps = append(steps, resource.TestStep{ + Config: testAccCcFloorPrerequisitesConfig + testAccCcFloorConfig_minimum(), + }) + } + steps = append(steps, resource.TestStep{ + Config: testAccCcFloorPrerequisitesConfig + testAccCcFloorConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_floor.test", + ImportState: true, + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +const testAccCcFloorPrerequisitesConfig = ` +resource "catalystcenter_building" "test" { + name = "Building1" + parent_name = "Global" + country = "United States" + address = "150 W Tasman Dr, San Jose" + latitude = 37.338 + longitude = -121.832 +} + +` + +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcFloorConfig_minimum() string { + config := `resource "catalystcenter_floor" "test" {` + "\n" + config += ` name = "Floor1"` + "\n" + config += ` parent_name = "${catalystcenter_building.test.parent_name}/${catalystcenter_building.test.name}"` + "\n" + config += ` rf_model = "Drywall Office Only"` + "\n" + config += ` width = 30.5` + "\n" + config += ` length = 50.5` + "\n" + config += ` height = 3.5` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcFloorConfig_all() string { + config := `resource "catalystcenter_floor" "test" {` + "\n" + config += ` name = "Floor1"` + "\n" + config += ` parent_name = "${catalystcenter_building.test.parent_name}/${catalystcenter_building.test.name}"` + "\n" + config += ` rf_model = "Drywall Office Only"` + "\n" + config += ` width = 30.5` + "\n" + config += ` length = 50.5` + "\n" + config += ` height = 3.5` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/internal/provider/resource_catalystcenter_ip_pool.go b/internal/provider/resource_catalystcenter_ip_pool.go new file mode 100644 index 00000000..b391449d --- /dev/null +++ b/internal/provider/resource_catalystcenter_ip_pool.go @@ -0,0 +1,270 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &IPPoolResource{} +var _ resource.ResourceWithImportState = &IPPoolResource{} + +func NewIPPoolResource() resource.Resource { + return &IPPoolResource{} +} + +type IPPoolResource struct { + client *cc.Client +} + +func (r *IPPoolResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_ip_pool" +} + +func (r *IPPoolResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage an IP Pool.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "name": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The name of the IP pool").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "ip_address_space": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("IP address version").AddStringEnumDescription("IPv4", "IPv6").AddDefaultValueDescription("IPv4").String, + Optional: true, + Computed: true, + Validators: []validator.String{ + stringvalidator.OneOf("IPv4", "IPv6"), + }, + Default: stringdefault.StaticString("IPv4"), + }, + "type": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Choose `Tunnel` to assign IP addresses to site-to-site VPN for IPSec tunneling. Choose `Generic` for all other network types.").AddStringEnumDescription("Generic", "Tunnel").AddDefaultValueDescription("Generic").String, + Optional: true, + Computed: true, + Validators: []validator.String{ + stringvalidator.OneOf("Generic", "Tunnel"), + }, + Default: stringdefault.StaticString("Generic"), + }, + "ip_subnet": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The IP subnet of the IP pool").String, + Required: true, + }, + "gateway": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The gateway for the IP pool").String, + Optional: true, + }, + "dhcp_server_ips": schema.ListAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("List of DHCP Server IPs").String, + ElementType: types.StringType, + Optional: true, + }, + "dns_server_ips": schema.ListAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("List of DNS Server IPs").String, + ElementType: types.StringType, + Optional: true, + }, + }, + } +} + +func (r *IPPoolResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *IPPoolResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan IPPool + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, IPPool{}) + + params := "" + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + params = "" + res, err = r.client.Get("/api/v2/ippool" + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("response.#(ipPoolName==\"" + plan.Name.ValueString() + "\").id").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *IPPoolResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state IPPool + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + params += "/" + state.Id.ValueString() + res, err := r.client.Get("/api/v2/ippool" + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *IPPoolResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state IPPool + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + + res, err := r.client.Put(plan.getPath()+"/"+plan.Id.ValueString()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *IPPoolResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state IPPool + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *IPPoolResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_ip_pool_reservation.go b/internal/provider/resource_catalystcenter_ip_pool_reservation.go new file mode 100644 index 00000000..32771da0 --- /dev/null +++ b/internal/provider/resource_catalystcenter_ip_pool_reservation.go @@ -0,0 +1,327 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + cc "github.com/netascode/go-catalystcenter" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider/helpers" +) + +//template:end imports + +//template:begin model + +// Ensure provider defined types fully satisfy framework interfaces +var _ resource.Resource = &IPPoolReservationResource{} +var _ resource.ResourceWithImportState = &IPPoolReservationResource{} + +func NewIPPoolReservationResource() resource.Resource { + return &IPPoolReservationResource{} +} + +type IPPoolReservationResource struct { + client *cc.Client +} + +func (r *IPPoolReservationResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_ip_pool_reservation" +} + +func (r *IPPoolReservationResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + // This description is used by the documentation generator and the language server. + MarkdownDescription: helpers.NewAttributeDescription("This resource can manage an IP Pool Reservation.").String, + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + MarkdownDescription: "The id of the object", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "site_id": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The site ID").String, + Optional: true, + }, + "name": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The name of the IP pool reservation").String, + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "type": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The type of the IP pool reservation").AddStringEnumDescription("Generic", "LAN", "WAN", "management", "service").String, + Required: true, + Validators: []validator.String{ + stringvalidator.OneOf("Generic", "LAN", "WAN", "management", "service"), + }, + }, + "ipv6_address_space": schema.BoolAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("If the value is `false` only IPv4 input are required, otherwise both IPv6 and IPv4 are required").AddDefaultValueDescription("false").String, + Optional: true, + Computed: true, + Default: booldefault.StaticBool(false), + }, + "ipv4_global_pool": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("IPv4 Global pool address with cidr, example: 175.175.0.0/16").String, + Required: true, + }, + "ipv4_prefix": schema.BoolAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("If this value is `true`, the `ipv4_prefix_length` attribute must be provided, if it is `false`, the `ipv4_total_host` attribute must be provided").String, + Required: true, + }, + "ipv4_prefix_length": schema.Int64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("The IPv4 prefix length is required when `ipv4_prefix` value is `true`.").String, + Optional: true, + }, + "ipv4_subnet": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The IPv4 subnet").String, + Optional: true, + }, + "ipv4_gateway": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The gateway for the IP pool reservation").String, + Optional: true, + }, + "ipv4_dhcp_servers": schema.ListAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("List of DHCP Server IPs").String, + ElementType: types.StringType, + Optional: true, + }, + "ipv4_dns_servers": schema.ListAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("List of DNS Server IPs").String, + ElementType: types.StringType, + Optional: true, + }, + "ipv6_global_pool": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("IPv6 Global pool address with cidr, example: 2001:db8:85a3::/64").String, + Optional: true, + }, + "ipv6_prefix": schema.BoolAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("If this value is `true`, the `ipv6_prefix_length` attribute must be provided, if it is `false`, the `ipv6_total_host` attribute must be provided").String, + Optional: true, + }, + "ipv6_prefix_length": schema.Int64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("The IPv6 prefix length is required when `ipv6_prefix` value is `true`.").String, + Optional: true, + }, + "ipv6_subnet": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The IPv6 subnet, for example `2001:db8:85a3:0:100::`").String, + Optional: true, + }, + "ipv6_gateway": schema.StringAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("The gateway for the IP pool reservation").String, + Optional: true, + }, + "ipv6_dhcp_servers": schema.ListAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("List of DHCP Server IPs").String, + ElementType: types.StringType, + Optional: true, + }, + "ipv6_dns_servers": schema.ListAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("List of DNS Server IPs").String, + ElementType: types.StringType, + Optional: true, + }, + "ipv4_total_host": schema.Int64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("The total number of IPv4 hosts").String, + Optional: true, + }, + "ipv6_total_host": schema.Int64Attribute{ + MarkdownDescription: helpers.NewAttributeDescription("The total number of IPv6 hosts").String, + Optional: true, + }, + "slaac_support": schema.BoolAttribute{ + MarkdownDescription: helpers.NewAttributeDescription("Enable SLAAC support").String, + Optional: true, + }, + }, + } +} + +func (r *IPPoolReservationResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) { + if req.ProviderData == nil { + return + } + + r.client = req.ProviderData.(*CcProviderData).Client +} + +//template:end model + +//template:begin create +func (r *IPPoolReservationResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan IPPoolReservation + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Create", plan.Id.ValueString())) + + // Create object + body := plan.toBody(ctx, IPPoolReservation{}) + + params := "" + params += "/" + plan.SiteId.ValueString() + res, err := r.client.Post(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (POST), got error: %s, %s", err, res.String())) + return + } + params = "" + params += "?siteId=" + plan.SiteId.ValueString() + res, err = r.client.Get(plan.getPath() + params) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + plan.Id = types.StringValue(res.Get("response.#(groupName==\"" + plan.Name.ValueString() + "\").id").String()) + + tflog.Debug(ctx, fmt.Sprintf("%s: Create finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end create + +//template:begin read +func (r *IPPoolReservationResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state IPPoolReservation + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Read", state.Id.String())) + + params := "" + params += "?siteId=" + state.SiteId.ValueString() + res, err := r.client.Get(state.getPath() + params) + if err != nil && strings.Contains(err.Error(), "StatusCode 404") { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to retrieve object (GET), got error: %s, %s", err, res.String())) + return + } + + state.updateFromBody(ctx, res) + + tflog.Debug(ctx, fmt.Sprintf("%s: Read finished successfully", state.Id.ValueString())) + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) +} + +//template:end read + +//template:begin update +func (r *IPPoolReservationResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var plan, state IPPoolReservation + + // Read plan + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + // Read state + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Update", plan.Id.ValueString())) + + body := plan.toBody(ctx, state) + params := "" + params += "/" + plan.SiteId.ValueString() + params += "?id=" + plan.Id.ValueString() + + res, err := r.client.Put(plan.getPath()+params, body) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to configure object (PUT), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Update finished successfully", plan.Id.ValueString())) + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) +} + +//template:end update + +//template:begin delete +func (r *IPPoolReservationResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state IPPoolReservation + + // Read state + diags := req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Beginning Delete", state.Id.ValueString())) + res, err := r.client.Delete(state.getPath() + "/" + state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to delete object (DELETE), got error: %s, %s", err, res.String())) + return + } + + tflog.Debug(ctx, fmt.Sprintf("%s: Delete finished successfully", state.Id.ValueString())) + + resp.State.RemoveResource(ctx) +} + +//template:end delete + +//template:begin import +func (r *IPPoolReservationResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +//template:end import diff --git a/internal/provider/resource_catalystcenter_ip_pool_reservation_test.go b/internal/provider/resource_catalystcenter_ip_pool_reservation_test.go new file mode 100644 index 00000000..295f6eb6 --- /dev/null +++ b/internal/provider/resource_catalystcenter_ip_pool_reservation_test.go @@ -0,0 +1,108 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcIPPoolReservation(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_ip_pool_reservation.test", "name", "MyRes1")) + + var steps []resource.TestStep + if os.Getenv("SKIP_MINIMUM_TEST") == "" { + steps = append(steps, resource.TestStep{ + Config: testAccCcIPPoolReservationPrerequisitesConfig + testAccCcIPPoolReservationConfig_minimum(), + }) + } + steps = append(steps, resource.TestStep{ + Config: testAccCcIPPoolReservationPrerequisitesConfig + testAccCcIPPoolReservationConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +const testAccCcIPPoolReservationPrerequisitesConfig = ` +resource "catalystcenter_area" "test" { + name = "Area1" + parent_name = "Global" + depends_on = [catalystcenter_ip_pool.test] +} + +resource "catalystcenter_ip_pool" "test" { + name = "MyPool1" + ip_subnet = "172.32.0.0/16" +} + +` + +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcIPPoolReservationConfig_minimum() string { + config := `resource "catalystcenter_ip_pool_reservation" "test" {` + "\n" + config += ` site_id = catalystcenter_area.test.id` + "\n" + config += ` name = "MyRes1"` + "\n" + config += ` type = "Generic"` + "\n" + config += ` ipv4_global_pool = "172.32.0.0/16"` + "\n" + config += ` ipv4_prefix = true` + "\n" + config += ` ipv4_prefix_length = 24` + "\n" + config += ` ipv4_subnet = "172.32.1.0"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcIPPoolReservationConfig_all() string { + config := `resource "catalystcenter_ip_pool_reservation" "test" {` + "\n" + config += ` site_id = catalystcenter_area.test.id` + "\n" + config += ` name = "MyRes1"` + "\n" + config += ` type = "Generic"` + "\n" + config += ` ipv6_address_space = false` + "\n" + config += ` ipv4_global_pool = "172.32.0.0/16"` + "\n" + config += ` ipv4_prefix = true` + "\n" + config += ` ipv4_prefix_length = 24` + "\n" + config += ` ipv4_subnet = "172.32.1.0"` + "\n" + config += ` ipv4_gateway = "172.32.1.1"` + "\n" + config += ` ipv4_dhcp_servers = ["1.2.3.4"]` + "\n" + config += ` ipv4_dns_servers = ["2.3.4.5"]` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/internal/provider/resource_catalystcenter_ip_pool_test.go b/internal/provider/resource_catalystcenter_ip_pool_test.go new file mode 100644 index 00000000..ce623dcc --- /dev/null +++ b/internal/provider/resource_catalystcenter_ip_pool_test.go @@ -0,0 +1,93 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +// Code generated by "gen/generator.go"; DO NOT EDIT. + +package provider + +//template:begin imports +import ( + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" +) + +//template:end imports + +//template:begin testAcc +func TestAccCcIPPool(t *testing.T) { + var checks []resource.TestCheckFunc + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_ip_pool.test", "name", "MyPool1")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_ip_pool.test", "ip_subnet", "21.1.1.0/24")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_ip_pool.test", "gateway", "21.1.1.1")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_ip_pool.test", "dhcp_server_ips.0", "1.2.3.4")) + checks = append(checks, resource.TestCheckResourceAttr("catalystcenter_ip_pool.test", "dns_server_ips.0", "2.3.4.5")) + + var steps []resource.TestStep + if os.Getenv("SKIP_MINIMUM_TEST") == "" { + steps = append(steps, resource.TestStep{ + Config: testAccCcIPPoolConfig_minimum(), + }) + } + steps = append(steps, resource.TestStep{ + Config: testAccCcIPPoolConfig_all(), + Check: resource.ComposeTestCheckFunc(checks...), + }) + steps = append(steps, resource.TestStep{ + ResourceName: "catalystcenter_ip_pool.test", + ImportState: true, + }) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: steps, + }) +} + +//template:end testAcc + +//template:begin testPrerequisites +//template:end testPrerequisites + +//template:begin testAccConfigMinimal +func testAccCcIPPoolConfig_minimum() string { + config := `resource "catalystcenter_ip_pool" "test" {` + "\n" + config += ` name = "MyPool1"` + "\n" + config += ` ip_subnet = "21.1.1.0/24"` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigMinimal + +//template:begin testAccConfigAll +func testAccCcIPPoolConfig_all() string { + config := `resource "catalystcenter_ip_pool" "test" {` + "\n" + config += ` name = "MyPool1"` + "\n" + config += ` ip_address_space = "IPv4"` + "\n" + config += ` type = "Generic"` + "\n" + config += ` ip_subnet = "21.1.1.0/24"` + "\n" + config += ` gateway = "21.1.1.1"` + "\n" + config += ` dhcp_server_ips = ["1.2.3.4"]` + "\n" + config += ` dns_server_ips = ["2.3.4.5"]` + "\n" + config += `}` + "\n" + return config +} + +//template:end testAccConfigAll diff --git a/main.go b/main.go new file mode 100644 index 00000000..10a62c7f --- /dev/null +++ b/main.go @@ -0,0 +1,66 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +package main + +import ( + "context" + "log" + + "github.com/hashicorp/terraform-plugin-framework/providerserver" + "github.com/netascode/terraform-provider-catalystcenter/internal/provider" +) + +// Run "go generate" to format example terraform files and generate the docs for the registry/website + +// Run the resource and datasource generation tool. +//go:generate go run gen/generator.go + +// Format code and cleanup imports +//go:generate go run golang.org/x/tools/cmd/goimports -w internal/provider/ + +// If you do not have terraform installed, you can remove the formatting command, but its suggested to +// ensure the documentation is formatted properly. +//go:generate terraform fmt -recursive ./examples/ + +// Run the docs generation tool, check its repository for more information on how it works and how docs +// can be customized. +//go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs + +// Update documentation categories. +//go:generate go run gen/doc_category.go + +var ( + // these will be set by the goreleaser configuration + // to appropriate values for the compiled binary + version string = "dev" + + // goreleaser can also pass the specific commit if you want + // commit string = "" +) + +func main() { + opts := providerserver.ServeOpts{ + Address: "registry.terraform.io/netascode/catalystcenter", + } + + err := providerserver.Serve(context.Background(), provider.New(version), opts) + + if err != nil { + log.Fatal(err.Error()) + } +} diff --git a/templates/guides/changelog.md.tmpl b/templates/guides/changelog.md.tmpl new file mode 100644 index 00000000..bd96b81d --- /dev/null +++ b/templates/guides/changelog.md.tmpl @@ -0,0 +1,13 @@ +--- +subcategory: "Guides" +page_title: "Changelog" +description: |- + Changelog +--- + +# Changelog + +## 0.1.0 (unreleased) + +- Initial Release + diff --git a/templates/index.md.tmpl b/templates/index.md.tmpl new file mode 100644 index 00000000..5cc0851c --- /dev/null +++ b/templates/index.md.tmpl @@ -0,0 +1,23 @@ + +--- +layout: "" +page_title: "Provider: Catalyst Center" +description: |- + The Catalyst Center provider provides resources to interact with a Cisco Catalyst Center instance. +--- + +# Cisco Catalyst Center Provider + +The Catalyst Center provider provides resources to interact with a Cisco Catalyst Center instance. It communicates with Catalyst Center via the REST API. + +All resources and data sources have been tested with the following releases. + +| Platform | Version | +| --------------- | ------- | +| Catalyst Center | 2.3.7 | + +## Example Usage + +{{tffile "examples/provider/provider.tf"}} + +{{ .SchemaMarkdown | trimspace }} diff --git a/terraform-registry-manifest.json b/terraform-registry-manifest.json new file mode 100644 index 00000000..fec2a569 --- /dev/null +++ b/terraform-registry-manifest.json @@ -0,0 +1,6 @@ +{ + "version": 1, + "metadata": { + "protocol_versions": ["6.0"] + } +} diff --git a/tools/tools.go b/tools/tools.go new file mode 100644 index 00000000..4e0dc37a --- /dev/null +++ b/tools/tools.go @@ -0,0 +1,28 @@ +// Copyright © 2023 Cisco Systems, Inc. and its affiliates. +// All rights reserved. +// +// Licensed under the Mozilla Public License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://mozilla.org/MPL/2.0/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// SPDX-License-Identifier: MPL-2.0 + +//go:build tools + +package tools + +import ( + // Documentation generation + _ "github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs" + // Code generation + _ "golang.org/x/tools/cmd/goimports" + _ "gopkg.in/yaml.v3" +)