diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..1c8292d --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,27 @@ +# Contributor Code of Conduct + +As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic addresses, without explicit permission +* Submitting contributions or comments that you know to violate the intellectual property or privacy rights of others +* Other unethical or unprofessional conduct + +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. +By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer. Complaints will result in a response and be reviewed and investigated in a way that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/3/0/ \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..33f952a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,24 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: alexhung + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**Requirements for and issue** +- [ ] A description of the bug +- [ ] A fully functioning terraform snippet that can be copy&pasted (no outside files or ENV vars unless that's part of the issue). **If this is not supplied, this issue will likely be closed without any effort expended.** +- [ ] Your version of artifactory (you can `curl` it at `$host/artifactory/api/system/version` +- [ ] Your version of terraform +- [ ] Your version of terraform provider + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..e25e7c8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: feature-request +assignees: alexhung + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..98d7f5e --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: gomod + directory: / + schedule: + interval: "daily" diff --git a/.github/jfrog-logo-2022.svg b/.github/jfrog-logo-2022.svg new file mode 100644 index 0000000..ff99033 --- /dev/null +++ b/.github/jfrog-logo-2022.svg @@ -0,0 +1,3 @@ + + + diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 0000000..65cf221 --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,21 @@ +changelog: + exclude: + labels: + - ignore-for-release + categories: + - title: Breaking Changes 🛠 + labels: + - breaking-change + - title: Improvements/Enhancements 🎉 + labels: + - enhancement + - new-feature + - title: Bug Fixes 🛠 + labels: + - bug + - title: 👒 Dependencies + labels: + - dependencies + - title: Other Changes 📚 + labels: + - "*" \ No newline at end of file diff --git a/.github/workflows/acceptance-tests.yml b/.github/workflows/acceptance-tests.yml new file mode 100644 index 0000000..2503fc9 --- /dev/null +++ b/.github/workflows/acceptance-tests.yml @@ -0,0 +1,157 @@ +on: + pull_request: + branches: + - main + types: [opened,synchronize] + paths: + - '**.go' + workflow_dispatch: + +name: Terraform & OpenTofu Acceptance Tests + +jobs: + acceptance-tests-matrix: + name: ${{ matrix.cli }} + runs-on: ubuntu-latest + continue-on-error: false + environment: development + strategy: + fail-fast: true + matrix: + cli: [terraform, tofu] + outputs: + tf_version: ${{ steps.get_terraform_cli_version.outputs.version }} + tofu_version: ${{ steps.get_opentofu_cli_version.outputs.version }} + artifactory_version: ${{ steps.get_artifactory_version.outputs.version }} + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Unshallow + run: git fetch --prune --unshallow + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: 1.21 + - name: Install Terraform CLI + uses: hashicorp/setup-terraform@v3 + if: ${{ matrix.cli == 'terraform' }} + - name: Get Terraform CLI version + id: get_terraform_cli_version + if: ${{ matrix.cli == 'terraform' }} + run: | + TF_VERSION=$(terraform -v -json | jq -r .terraform_version) + echo $TF_VERSION + echo "version=$TF_VERSION" >> "$GITHUB_OUTPUT" + - name: Install OpenTofu CLI + uses: opentofu/setup-opentofu@v1 + if: ${{ matrix.cli == 'tofu' }} + with: + tofu_wrapper: false + - name: Get OpenTofu CLI version + id: get_opentofu_cli_version + if: ${{ matrix.cli == 'tofu' }} + run: | + echo "TF_ACC_TERRAFORM_PATH=$(which tofu)" >> "$GITHUB_ENV" + echo "TF_ACC_PROVIDER_NAMESPACE=hashicorp" >> "$GITHUB_ENV" + echo "TF_ACC_PROVIDER_HOST=registry.opentofu.org" >> "$GITHUB_ENV" + TOFU_VERSION=$(tofu -v -json | jq -r .terraform_version) + echo $TOFU_VERSION + echo "version=$TOFU_VERSION" >> "$GITHUB_OUTPUT" + - name: Install GoReleaser + uses: goreleaser/goreleaser-action@v6 + with: + install-only: true + - name: Get Artifactory version + id: get_artifactory_version + env: + JFROG_URL: ${{ secrets.JFROG_URL }} + JFROG_ACCESS_TOKEN: ${{ secrets.JFROG_ACCESS_TOKEN }} + run: | + RT_VERSION=$(curl -s -L "${JFROG_URL}/artifactory/api/system/version" -H "Authorization: Bearer ${JFROG_ACCESS_TOKEN}" | jq -r .version) + echo $RT_VERSION + echo "version=$RT_VERSION" >> "$GITHUB_OUTPUT" + - name: Execute acceptance tests + env: + JFROG_URL: ${{ secrets.JFROG_URL }} + JFROG_ACCESS_TOKEN: ${{ secrets.JFROG_ACCESS_TOKEN }} + run: make acceptance + - name: Install provider + run: | + export PROVIDER_VERSION=$(git describe --tags --abbrev=0 | sed -n 's/v\([0-9]*\).\([0-9]*\).\([0-9]*\)/\1.\2.\3/p') + cat sample.tf | sed -e "s/version =.*/version = \"${PROVIDER_VERSION}\"/g" > sample.tf.tmp + cp sample.tf.tmp sample.tf && rm sample.tf.tmp + TERRAFORM_CLI=${{ matrix.cli }} make install + - name: Send workflow status to Slack + uses: slackapi/slack-github-action@v1.26.0 + with: + payload: | + { + "text": "${{ github.workflow }} https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}/job/${{ github.job }} ${{ matrix.cli }} GitHub Action result: ${{ job.status == 'success' && ':white_check_mark:' || ':x:' }}\n${{ github.event.pull_request.html_url || github.event.head_commit.url }}", + "blocks": [ + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "${{ github.workflow }} : ${{ job.status == 'success' && ':white_check_mark:' || ':x:' }}\n${{ github.event.pull_request.html_url || github.event.head_commit.url }}" + } + } + ] + } + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_PR_WEBHOOK }} + SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK + + update-changelog: + runs-on: ubuntu-latest + needs: acceptance-tests-matrix + if: ${{ github.event_name == 'pull_request' }} && ${{ needs.acceptance-tests-matrix.result == 'success' }} + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.ref }} + - name: Update CHANGELOG and push commit + env: + ARTIFACTORY_VERSION: ${{ needs.acceptance-tests-matrix.outputs.artifactory_version }} + TERRAFORM_VERSION: ${{ needs.acceptance-tests-matrix.outputs.tf_version }} + OPENTOFU_VERSION: ${{ needs.acceptance-tests-matrix.outputs.tofu_version }} + run: | + echo "Adding Artifactory version to CHANGELOG.md" + sed -i -E "0,/(##\s.+\..+\..+\s\(.+\)).*/ s/(##\s.+\..+\..+\s\(.+\)).*/\1. Tested on Artifactory $ARTIFACTORY_VERSION with Terraform $TERRAFORM_VERSION and OpenTofu $OPENTOFU_VERSION/" CHANGELOG.md + head -10 CHANGELOG.md + git add CHANGELOG.md + export REGEX="Changes to be committed*" + export GIT_STATUS=$(git status) + if [[ ${GIT_STATUS} =~ ${REGEX} ]]; then + echo "Commiting changes" + git config --global user.name 'JFrog CI' + git config --global user.email 'jfrog-solutions-ci+1@jfrog.com' + git config --get user.name + git config --get user.email + git commit --author="JFrog CI " -m "JFrog Pipelines - Add Artifactory version to CHANGELOG.md" + git push + else + echo "There is nothing to commit: Artifactory version hadn't changed." + fi + - name: Send workflow status to Slack + uses: slackapi/slack-github-action@v1.26.0 + if: success() + with: + payload: | + { + "text": "Terraform Provider Distribution. A new PR was submitted by ${{ github.event.pull_request.user.login }} - ${{ github.event.pull_request.html_url }}, branch ${{ github.event.pull_request.base.ref }}. Changes tested successfully. <@U01H1SLSPA8> or <@UNDRUL1EU> please, review and merge.", + "blocks": [ + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": ". A new PR was submitted by *${{ github.event.pull_request.user.login }}* - <${{ github.event.pull_request.html_url }}|${{ github.event.pull_request.title }}>, branch *${{ github.event.pull_request.base.ref }}*. Changes tested successfully. <@U01H1SLSPA8> or <@UNDRUL1EU> please, review and merge." + } + } + ] + } + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_PR_WEBHOOK }} + SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml new file mode 100644 index 0000000..e5867be --- /dev/null +++ b/.github/workflows/changelog.yml @@ -0,0 +1,19 @@ +name: "CHANGELOG check" +on: + pull_request: + types: [opened, synchronize, reopened, labeled, unlabeled] + +jobs: + build: + name: Check Actions + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - name: Changelog check + uses: Zomzog/changelog-checker@v1.2.0 + with: + fileName: CHANGELOG.md + noChangelogLabel: "no changelog" + checkNotification: Detailed + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml new file mode 100644 index 0000000..6e6c87d --- /dev/null +++ b/.github/workflows/cla.yml @@ -0,0 +1,35 @@ +name: "CLA Assistant" +on: + # issue_comment triggers this action on each comment on issues and pull requests + issue_comment: + types: [created] + pull_request_target: + types: [opened,synchronize] + +jobs: + CLAssistant: + runs-on: ubuntu-latest + steps: + - uses: actions-ecosystem/action-regex-match@v2 + id: sign-or-recheck + with: + text: ${{ github.event.comment.body }} + regex: '\s*(I have read the CLA Document and I hereby sign the CLA)|(recheckcla)\s*' + + - name: "CLA Assistant" + if: ${{ steps.sign-or-recheck.outputs.match != '' || github.event_name == 'pull_request_target' }} + # Alpha Release + uses: cla-assistant/github-action@v2.1.1-beta + env: + # Generated and maintained by github + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # JFrog organization secret + PERSONAL_ACCESS_TOKEN : ${{ secrets.CLA_SIGN_TOKEN }} + with: + path-to-signatures: 'signed_clas.json' + path-to-document: 'https://jfrog.com/cla/' + remote-organization-name: 'jfrog' + remote-repository-name: 'jfrog-signed-clas' + # branch should not be protected + branch: 'master' + allowlist: bot* \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..92244bf --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,49 @@ +# This GitHub action can publish assets for release when a tag is created. +# Currently its setup to run on any tag that matches the pattern "v*" (ie. v0.1.0). +# +# This uses an action (paultyng/ghaction-import-gpg) that assumes you set your +# private key in the `GPG_PRIVATE_KEY` secret and passphrase in the `PASSPHRASE` +# secret. If you would rather own your own GPG handling, please fork this action +# or use an alternative one for key handling. +# +# You will need to pass the `--batch` flag to `gpg` in your signing step +# in `goreleaser` to indicate this is being used in a non-interactive mode. +# +name: release +on: + push: + tags: + - v* +jobs: + goreleaser: + runs-on: ubuntu-latest + if: | + (startsWith(github.ref, 'refs/tags/') && github.event.base_ref == 'refs/heads/main') + steps: + - + name: Checkout + uses: actions/checkout@v3 + - + name: Unshallow + run: git fetch --prune --unshallow + - + name: Set up Go + uses: actions/setup-go@v3 + with: + go-version: 1.21 + - + name: Import GPG key + id: import_gpg + uses: crazy-max/ghaction-import-gpg@v5.0.0 + with: + gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }} + passphrase: ${{ secrets.GPG_PASSPHRASE }} + - + name: Run GoReleaser + uses: goreleaser/goreleaser-action@v4 + with: + version: ${{ github.event.inputs.tag }} + args: release --clean + env: + GPG_FINGERPRINT: ${{ steps.import_gpg.outputs.fingerprint }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/slack-notify-issues.yml b/.github/workflows/slack-notify-issues.yml new file mode 100644 index 0000000..6f1bd2e --- /dev/null +++ b/.github/workflows/slack-notify-issues.yml @@ -0,0 +1,20 @@ +on: + issues: + types: [opened, reopened, deleted, closed] +name: Slack Issue Notification +jobs: + slackNotification: + name: Slack Notification Issue + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Slack Notification Issue + uses: rtCamp/action-slack-notify@master + env: + SLACK_CHANNEL: partnereng-issues + SLACK_COLOR: '#00A86B' + SLACK_ICON: https://pbs.twimg.com/profile_images/978188446178082817/86ulJdF0.jpg + SLACK_TITLE: "[${{ github.event.issue.state}}] ${{ github.event.issue.title }} on ${{ github.repository }} :rocket:" + SLACK_MESSAGE: 'Link: ${{ github.event.issue.html_url }}' + SLACK_USERNAME: PartnerEngineers + SLACK_WEBHOOK: ${{ secrets.SLACK_ISSUE_WEBHOOK }} diff --git a/.github/workflows/slack-notify-pr.yml b/.github/workflows/slack-notify-pr.yml new file mode 100644 index 0000000..b405506 --- /dev/null +++ b/.github/workflows/slack-notify-pr.yml @@ -0,0 +1,22 @@ +on: + pull_request_target: + branches: + - main + types: [opened, reopened, closed] +name: Slack Pull Request Notification +jobs: + slackNotification: + name: Slack Notification PR + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Slack Notification PR + uses: rtCamp/action-slack-notify@master + env: + SLACK_CHANNEL: partnereng-pullrequest + SLACK_COLOR: '#00A86B' + SLACK_ICON: https://pbs.twimg.com/profile_images/978188446178082817/86ulJdF0.jpg + SLACK_TITLE: "[${{ github.event.pull_request.state}}] ${{ github.event.pull_request.title }} on ${{ github.repository }} :rocket:" + SLACK_MESSAGE: 'Merging from ${{ github.head_ref }} to ${{ github.base_ref }} by ${{ github.actor }}. Link: ${{ github.event.pull_request._links.html.href }}' + SLACK_USERNAME: PartnerEngineers + SLACK_WEBHOOK: ${{ secrets.SLACK_PR_WEBHOOK }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1f5636c --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +dist/ +vendor/ +.idea/ +.modules/ +.terraform* +terraform.d/ +terraform.tfstate +terraform.tfstate.backup +lib/ +*.lic +/resources/ +.DS_Store +*.crt +*.backup +coverage.txt +.scannerwork +*.code-workspace +scripts/artifactory*/ \ No newline at end of file diff --git a/.goreleaser.yml b/.goreleaser.yml new file mode 100644 index 0000000..08afdd8 --- /dev/null +++ b/.goreleaser.yml @@ -0,0 +1,62 @@ +version: 2 + +# 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 github.com/jfrog/terraform-provider-distribution/pkg/distribution.Version={{.Version}}' + 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 is 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: + use: github-native diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..7b6c795 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,9 @@ +## 1.0.0 (August 16, 2024). Tested on Artifactory 7.92.1 with Terraform 1.9.4 and OpenTofu 1.8.1 + +FEATURES: + +**New Resource:** +* `distribution_signing_key` +* `distribution_vault_signing_key` + +PR: [#2](https://github.com/jfrog/terraform-provider-distribution/pull/2) \ No newline at end of file diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..7d008d1 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,2 @@ +* @alexhung +* @danielmkn diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0c5037c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,78 @@ +# JFrog welcomes community contribution! + +Before we can accept your contribution, process your GitHub pull requests, and thank you full-heartedly, we request that you will fill out and submit JFrog's Contributor License Agreement (CLA). + +[Click here](https://gist.github.com/jfrog-ecosystem/7d4fbeaac18edbd3cfc38831125acbb3) to view the JFrog CLA. + +Please comment in your pull request to mark your acceptance for now until CLA assistant is fixed. + +"I have read the CLA Document and I hereby sign the CLA" + +This should only take a minute to complete and is a one-time process. + +*Thanks for Your Contribution to the Community!* :-) + +## Pull Request Process ## + +- Fork this repository. +- Clone the forked repository to your local machine and perform the proposed changes. +- Test the changes in your own K8s environment and confirm everything works end to end. +- Update the CHANGELOG.md +- Submit a PR with the relevant information and check the applicable boxes and fill out the questions. + +## Acceptance Criteria ## + +- Pull requests must pass all automated checks +- CHANGELOG.md has relevant changes +- README.md has been updated if required +- One approval from JFrog reviewers + +Upon the success of the above the pull request will be mergable into master branch. Upon merge the source branch will be removed. + +Increase the version numbers in any examples files and the README.md to the new version that this Pull Request would represent. The versioning scheme we use is SemVer. +You may merge the Pull Request in once you have the sign-off of one other developer. + +## 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 a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, 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 company + Showing empathy towards other colleagues + ```` + +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, 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. Examples of representing a project 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 contacting the project team at Slack #xray_splunk . 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, version 1.4, available at http://contributor-covenant.org/version/1/4 diff --git a/CONTRIBUTIONS.md b/CONTRIBUTIONS.md new file mode 100644 index 0000000..23cb1b2 --- /dev/null +++ b/CONTRIBUTIONS.md @@ -0,0 +1,94 @@ +# Contribution Guide + +## Contributors + +Pull requests, issues and comments are welcomed. For pull requests: + +* Add tests for new features and bug fixes +* Follow the existing style +* Separate unrelated changes into multiple pull requests + +See the existing issues for things to start contributing. + +For bigger changes, make sure you start a discussion first by creating an issue and explaining the intended change. + +JFrog requires contributors to sign a Contributor License Agreement, known as a CLA. This serves as a record stating that the contributor is entitled to contribute the code/documentation/translation to the project and is willing to have it used in distributions and derivative works (or is willing to transfer ownership). + +## Building + +Simply run `make install` - this will compile the provider and install it to `~/.terraform.d`. When running this, it will take the current tag and bump it 1 patch version. It does not actually create a new tag. If you wish to use the locally installed provider, make sure your TF script refers to the new version number. + +Requirements: +- [Terraform](https://www.terraform.io/downloads.html) 1.7+ +- [Go](https://golang.org/doc/install) 1.21+ (to build the provider plugin) + +## Debugging + +See [debugging wiki](https://github.com/jfrog/terraform-provider-artifactory/wiki/Debugging). + +## Testing + +First, you need a running instance of the JFrog Artifactory. + +You can ask for an instance to test against it as part of your PR. Alternatively, you can run the file [scripts/run-artifactory.sh](scripts/run-artifactory.sh). + +The script requires a valid license of a [supported type](https://github.com/jfrog/terraform-provider-artifactory#license-requirements), license should be saved in the file called `artifactory.lic` in the same directory as a script. + +With the script you can start one or two Artifactory instances using docker compose. + +The license is not supplied but is required for local development. Make sure the license saved as a multi line text file. + +Currently, acceptance tests **require an access key**. To generate an access key, please refer to the [official documentation](https://jfrog.com/help/r/jfrog-platform-administration-documentation/generate-admin-tokens) + +Then, you have to set some environment variables as this is how the acceptance tests pick up their config. + +```sh +ARTIFACTORY_URL=http://localhost:8082 +ARTIFACTORY_USERNAME=admin +ARTIFACTORY_ACCESS_TOKEN= +TF_ACC=true +``` + +`ARTIFACTORY_USERNAME` is not used in authentication, but used in several tests, related to replication functionality. It should be hardcoded to `admin`, because it's a default user created in the Artifactory instance from the start. + +A crucial env var to set is `TF_ACC=true` - you can literally set `TF_ACC` to anything you want, so long as it's set. The acceptance tests use terraform testing libraries that, if this flag isn't set, will skip all tests. + +You can then run the tests as + +```sh +$ go test -v -p 1 ./pkg/... +``` + +Or + +```sh +$ make acceptance +``` + +**DO NOT** remove the `-v` - terraform testing needs this. This will recursively run all tests, including acceptance tests. + +#### Setup Artifactory instances + +The [scripts/run-artifactory.sh](scripts/run-artifactory.sh) starts two Artifactory instances for testing using the file [scripts/docker-compose.yml](scripts/docker-compose.yml). + +`artifactory-1` is on the usual 8080/8081/8082 ports while `artifactory-2` is on 9080/9081/9082 + +You can also run one instance of artifactory using `./run-artifactory-container.sh` which doesn't use docker-compose. + +#### Enable acceptance tests + +Set the env var to the second Artifactory instance URL. This is the URL that will be accessible from `artifactory-1` container (not the URL from the Docker host): +```sh +$ export ARTIFACTORY_URL_2=http://artifactory-2:8081 +``` + +Run all the acceptance tests as usual +```sh +$ make acceptance +``` + +## Releasing + +Please create a pull request against the master branch. Each pull request will be reviewed by a member of the JFrog team. + +#### Thank you for contributing! diff --git a/GNUmakefile b/GNUmakefile new file mode 100644 index 0000000..37132ae --- /dev/null +++ b/GNUmakefile @@ -0,0 +1,86 @@ +TEST?=./... +PRODUCT=distribution +GO_ARCH=$(shell go env GOARCH) +TARGET_ARCH=$(shell go env GOOS)_${GO_ARCH} +GORELEASER_ARCH=${TARGET_ARCH} + +ifeq ($(GO_ARCH), amd64) +GORELEASER_ARCH=${TARGET_ARCH}_$(shell go env GOAMD64) +endif + +PKG_NAME=pkg/${PRODUCT} +# if this path ever changes, you need to also update the 'ldflags' value in .goreleaser.yml +PKG_VERSION_PATH=github.com/jfrog/terraform-provider-${PRODUCT}/${PKG_NAME} +VERSION := $(shell git tag --sort=-creatordate | head -1 | sed -n 's/v\([0-9]*\).\([0-9]*\).\([0-9]*\)/\1.\2.\3/p') + +ifeq ($(VERSION),) +VERSION := "0.0.0" +endif + +NEXT_VERSION?=$(shell echo ${VERSION}| awk -F '.' '{print $$1 "." $$2 "." $$3 +1 }') + +TERRAFORM_CLI?=terraform + +REGISTRY_HOST=registry.terraform.io + +ifeq ($(TERRAFORM_CLI), tofu) +REGISTRY_HOST=registry.opentofu.org +endif + +BUILD_PATH=terraform.d/plugins/${REGISTRY_HOST}/jfrog/${PRODUCT}/${NEXT_VERSION}/${TARGET_ARCH} + +SONAR_SCANNER_VERSION?=4.7.0.2747 +SONAR_SCANNER_HOME?=${HOME}/.sonar/sonar-scanner-${SONAR_SCANNER_VERSION}-macosx + +default: build + +install: clean build + mkdir -p ${BUILD_PATH} && \ + mv -v dist/terraform-provider-${PRODUCT}_${GORELEASER_ARCH}/terraform-provider-${PRODUCT}_v${NEXT_VERSION}* ${BUILD_PATH} && \ + rm -f .terraform.lock.hcl && \ + sed -i.bak '0,/version = ".*"/s//version = "${NEXT_VERSION}"/' sample.tf && rm sample.tf.bak && \ + ${TERRAFORM_CLI} init + +clean: + rm -fR dist terraform.d/ .terraform terraform.tfstate* .terraform.lock.hcl + +release: + @git tag ${NEXT_VERSION} && git push --mirror + @echo "Pushed ${NEXT_VERSION}" + GOPROXY=https://proxy.golang.org GO111MODULE=on go get github.com/jfrog/terraform-provider-${PRODUCT}@v${NEXT_VERSION} + @echo "Updated pkg cache" + +update_pkg_cache: + GOPROXY=https://proxy.golang.org GO111MODULE=on go get github.com/jfrog/terraform-provider-${PRODUCT}@v${VERSION} + +build: fmt + GORELEASER_CURRENT_TAG=${NEXT_VERSION} goreleaser build --single-target --clean --snapshot + +test: + @echo "==> Starting unit tests" + go test $(TEST) -timeout=30s -parallel=4 + +attach: + dlv --listen=:2345 --headless=true --api-version=2 --accept-multiclient attach $$(pgrep terraform-provider-${PRODUCT}) + +acceptance: fmt + export TF_ACC=true && \ + go test -cover -coverprofile=coverage.txt -ldflags="-X '${PKG_VERSION_PATH}.Version=${NEXT_VERSION}-test'" -v -p 1 -parallel 20 -timeout 20m ./pkg/... + +# To generate coverage.txt run `make acceptance` first +coverage: + go tool cover -html=coverage.txt + +# SONAR_TOKEN (project token) must be set to run `make scan`. Check file sonar-project.properties for the configuration. +scan: + ${SONAR_SCANNER_HOME}/bin/sonar-scanner -Dsonar.projectVersion=${VERSION} -Dsonar.go.coverage.reportPaths=coverage.txt + +fmt: + @echo "==> Fixing source code with gofmt..." + @go fmt ./pkg/... + +doc: + rm -rfv docs/* + go generate + +.PHONY: build fmt diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8821a5f --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020 JFrog Ltd + + Licensed under the Apache 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 + + http://www.apache.org/licenses/LICENSE-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. diff --git a/README.md b/README.md index e69de29..f539cd7 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,95 @@ +[![Terraform & OpenTofu Acceptance Tests](https://github.com/jfrog/terraform-provider-distribution/actions/workflows/acceptance-tests.yml/badge.svg)](https://github.com/jfrog/terraform-provider-distribution/actions/workflows/acceptance-tests.yml) + +# Terraform Provider for JFrog Platform + +## Quick Start + +Create a new Terraform file with `distribution` resource. + +### HCL Example + +```terraform +terraform { + required_providers { + distribution = { + source = "jfrog/distribution" + version = "1.0.0" + } + } +} + +variable "jfrog_url" { + type = string + default = "http://localhost:8081" +} + +provider "distribution" { + url = "${var.jfrog_url}" + // supply JFROG_ACCESS_TOKEN as env var +} + +resource "distribution_signing_key" "my-gpg-signing-key" { + protocol = "gpg" + alias = "my-gpg-signing-key" + + private_key = < +## Schema + +### Optional + +- `access_token` (String, Sensitive) This is a access token that can be given to you by your admin under `Platform Configuration -> User Management -> Access Tokens`. This can also be sourced from the `JFROG_ACCESS_TOKEN` environment variable. +- `oidc_provider_name` (String) OIDC provider name. See [Configure an OIDC Integration](https://jfrog.com/help/r/jfrog-platform-administration-documentation/configure-an-oidc-integration) for more details. +- `url` (String) JFrog Platform URL. This can also be sourced from the `JFROG_URL` environment variable. \ No newline at end of file diff --git a/docs/resources/signing_key.md b/docs/resources/signing_key.md new file mode 100644 index 0000000..571fdbc --- /dev/null +++ b/docs/resources/signing_key.md @@ -0,0 +1,65 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "distribution_signing_key Resource - terraform-provider-distribution" +subcategory: "" +description: |- + This resource enables you to upload and distribute GPG keys to sign Release Bundle V1. For more information, see GPG Signing https://jfrog.com/help/r/jfrog-distribution-documentation/gpg-signing and REST API https://jfrog.com/help/r/jfrog-rest-apis/signing-keys. +--- + +# distribution_signing_key (Resource) + +This resource enables you to upload and distribute GPG keys to sign Release Bundle V1. For more information, see [GPG Signing](https://jfrog.com/help/r/jfrog-distribution-documentation/gpg-signing) and [REST API](https://jfrog.com/help/r/jfrog-rest-apis/signing-keys). + +## Example Usage + +```terraform +resource "distribution_signing_key" "my-gpg-signing-key" { + protocol = "gpg" + alias = "my-gpg-signing-key" + + private_key = < +## Schema + +### Required + +- `alias` (String) Alias of the signing key +- `private_key` (String, Sensitive) Private key +- `protocol` (String) Type of the signing key. Valid value: `gpg` or `pgp` +- `public_key` (String) Public key + +### Optional + +- `fail_on_propagation_failure` (Boolean) When set to `true`, the public key will be automatically propagated to the Edge Node just once. +- `passphrase` (String, Sensitive) Passphrase for key +- `propagate_to_edge_nodes` (Boolean) When set to `true`, the public key will be automatically propagated to the Edge Node just once. +- `set_as_default` (Boolean) Set this to `true` if this is the first key that is set or if there is no default key in Artifactory. diff --git a/docs/resources/vault_signing_key.md b/docs/resources/vault_signing_key.md new file mode 100644 index 0000000..3318461 --- /dev/null +++ b/docs/resources/vault_signing_key.md @@ -0,0 +1,71 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "distribution_vault_signing_key Resource - terraform-provider-distribution" +subcategory: "" +description: |- + This resource enables you to distribute GPG keys (store in HashiCorp Vault) to sign Release Bundle V1. For more information, see GPG Signing https://jfrog.com/help/r/jfrog-distribution-documentation/gpg-signing, Vault integration https://jfrog.com/help/r/jfrog-platform-administration-documentation/vault, and REST API https://jfrog.com/help/r/jfrog-rest-apis/signing-keys. +--- + +# distribution_vault_signing_key (Resource) + +This resource enables you to distribute GPG keys (store in HashiCorp Vault) to sign Release Bundle V1. For more information, see [GPG Signing](https://jfrog.com/help/r/jfrog-distribution-documentation/gpg-signing), [Vault integration](https://jfrog.com/help/r/jfrog-platform-administration-documentation/vault), and [REST API](https://jfrog.com/help/r/jfrog-rest-apis/signing-keys). + +## Example Usage + +```terraform +resource "distribution_vault_signing_key" "my-vault-gpg-signing-key" { + protocol = "gpg" + vault_id = "my-vault-integration" + + public_key = { + path = "kv/public/path" + key = "public" + } + + private_key = { + path = "kv/private/path" + key = "private" + } + + propagate_to_edge_nodes = true + fail_on_propagation_failure = true + set_as_default = true +} +``` + + +## Schema + +### Required + +- `private_key` (Attributes) (see [below for nested schema](#nestedatt--private_key)) +- `protocol` (String) Type of the signing key. Valid value: `gpg` or `pgp` +- `public_key` (Attributes) (see [below for nested schema](#nestedatt--public_key)) +- `vault_id` (String) Name of the Vault integration in Artifactory + +### Optional + +- `fail_on_propagation_failure` (Boolean) When set to `true`, the public key will be automatically propagated to the Edge Node just once. +- `propagate_to_edge_nodes` (Boolean) When set to `true`, the public key will be automatically propagated to the Edge Node just once. +- `set_as_default` (Boolean) Set this to `true` if this is the first key that is set or if there is no default key in Artifactory. + +### Read-Only + +- `alias` (String) + + +### Nested Schema for `private_key` + +Required: + +- `key` (String) Field name of the key, e.g. `private` +- `path` (String) Path to the key, e.g. `secret/my-key` + + + +### Nested Schema for `public_key` + +Required: + +- `key` (String) Field name of the key, e.g. `public` +- `path` (String) Path to the key, e.g. `secret/my-key` diff --git a/examples/example.tf b/examples/example.tf new file mode 100644 index 0000000..6bb66cb --- /dev/null +++ b/examples/example.tf @@ -0,0 +1,51 @@ +terraform { + required_providers { + distribution = { + source = "jfrog/distribution" + version = "1.0.0" + } + } +} + +variable "jfrog_url" { + type = string + default = "http://localhost:8081" +} + +provider "distribution" { + url = "${var.jfrog_url}" + // supply JFROG_ACCESS_TOKEN as env var +} + +resource "distribution_signing_key" "my-gpg-signing-key" { + protocol = "gpg" + alias = "my-gpg-signing-key" + + private_key = < 0 { + _, err = client.AddAuth(platformClient, "", accessToken) + if err != nil { + resp.Diagnostics.AddError( + "Error adding Auth to Resty client", + err.Error(), + ) + return + } + + version, err := util.GetArtifactoryVersion(platformClient) + if err != nil { + resp.Diagnostics.AddWarning( + "Error getting Artifactory version", + fmt.Sprintf("Provider functionality might be affected by the absence of Artifactory version. %v", err), + ) + } + + artifactoryVersion = version + + featureUsage := fmt.Sprintf("Terraform/%s", req.TerraformVersion) + go util.SendUsage(ctx, platformClient.R(), productId, featureUsage) + } + + meta := util.ProviderMetadata{ + Client: platformClient, + ArtifactoryVersion: artifactoryVersion, + ProductId: productId, + } + + p.Meta = meta + + resp.DataSourceData = meta + resp.ResourceData = meta +} + +func (p *DistributionProvider) Metadata(ctx context.Context, req provider.MetadataRequest, resp *provider.MetadataResponse) { + resp.TypeName = "distribution" + resp.Version = Version +} + +func (p *DistributionProvider) DataSources(ctx context.Context) []func() datasource.DataSource { + return []func() datasource.DataSource{ + // NewDataSource, + } +} + +func (p *DistributionProvider) Resources(ctx context.Context) []func() resource.Resource { + return []func() resource.Resource{ + NewSigningKeyResource, + NewVaultSigningKeyResource, + } +} + +func (p *DistributionProvider) Schema(ctx context.Context, req provider.SchemaRequest, resp *provider.SchemaResponse) { + resp.Schema = schema.Schema{ + Attributes: map[string]schema.Attribute{ + "url": schema.StringAttribute{ + Optional: true, + Validators: []validator.String{ + validator_string.IsURLHttpOrHttps(), + }, + MarkdownDescription: "JFrog Platform URL. This can also be sourced from the `JFROG_URL` environment variable.", + }, + "access_token": schema.StringAttribute{ + Optional: true, + Sensitive: true, + Validators: []validator.String{ + stringvalidator.LengthAtLeast(1), + }, + MarkdownDescription: "This is a access token that can be given to you by your admin under `Platform Configuration -> User Management -> Access Tokens`. This can also be sourced from the `JFROG_ACCESS_TOKEN` environment variable.", + }, + "oidc_provider_name": schema.StringAttribute{ + Optional: true, + Validators: []validator.String{ + stringvalidator.LengthAtLeast(1), + }, + MarkdownDescription: "OIDC provider name. See [Configure an OIDC Integration](https://jfrog.com/help/r/jfrog-platform-administration-documentation/configure-an-oidc-integration) for more details.", + }, + }, + } +} diff --git a/pkg/distribution/resource_signing_key.go b/pkg/distribution/resource_signing_key.go new file mode 100644 index 0000000..e33cb64 --- /dev/null +++ b/pkg/distribution/resource_signing_key.go @@ -0,0 +1,274 @@ +package distribution + +import ( + "context" + "net/http" + + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/diag" + "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/jfrog/terraform-provider-shared/util" + utilfw "github.com/jfrog/terraform-provider-shared/util/fw" + "github.com/samber/lo" +) + +func NewSigningKeyResource() resource.Resource { + return &SigningKeyResource{ + TypeName: "distribution_signing_key", + } +} + +type SigningKeyResource struct { + ProviderData util.ProviderMetadata + TypeName string +} + +type SigningKeyResourceModel struct { + SigningKeyCommmonResourceModel + PublicKey types.String `tfsdk:"public_key"` + PrivateKey types.String `tfsdk:"private_key"` + Passphrase types.String `tfsdk:"passphrase"` +} + +func (m SigningKeyResourceModel) toAPIModel(_ context.Context, apiModel *SigningKeyPostRequestAPIModel) (diags diag.Diagnostics) { + apiModel.Key = SigningKeyKeyPostRequestAPIModel{ + Alias: m.Alias.ValueString(), + PublicKey: m.PublicKey.ValueString(), + PrivateKey: m.PrivateKey.ValueString(), + Passphrase: m.Passphrase.ValueString(), + } + apiModel.PropagateToEdgeNode = m.PropagateToEdgeNode.ValueBool() + apiModel.FailOnPropagationFailure = m.FailOnPropagationFailure.ValueBool() + apiModel.SetAsDefault = m.SetAsDefault.ValueBool() + + return +} + +type SigningKeyPostRequestAPIModel struct { + SigningKeyCommonPostRequestAPIModel + Key SigningKeyKeyPostRequestAPIModel `json:"key"` +} + +type SigningKeyKeyPostRequestAPIModel struct { + Alias string `json:"alias"` + PublicKey string `json:"public_key"` + PrivateKey string `json:"private_key"` + Passphrase string `json:"passphrase"` +} + +func (r *SigningKeyResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = r.TypeName +} + +func (r *SigningKeyResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + Attributes: lo.Assign( + commonSchemaAttributes, + map[string]schema.Attribute{ + "public_key": schema.StringAttribute{ + Required: true, + Validators: []validator.String{ + stringvalidator.LengthAtLeast(1), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + Description: "Public key", + }, + "private_key": schema.StringAttribute{ + Required: true, + Sensitive: true, + Validators: []validator.String{ + stringvalidator.LengthAtLeast(1), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + Description: "Private key", + }, + "passphrase": schema.StringAttribute{ + Optional: true, + Sensitive: true, + Validators: []validator.String{ + stringvalidator.LengthAtLeast(1), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + Description: "Passphrase for key", + }, + }, + ), + MarkdownDescription: "This resource enables you to upload and distribute GPG keys to sign Release Bundle V1. For more information, see [GPG Signing](https://jfrog.com/help/r/jfrog-distribution-documentation/gpg-signing) and [REST API](https://jfrog.com/help/r/jfrog-rest-apis/signing-keys).", + } +} + +func (r *SigningKeyResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + r.ProviderData = req.ProviderData.(util.ProviderMetadata) +} + +func (r *SigningKeyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + go util.SendUsageResourceCreate(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName) + + var plan SigningKeyResourceModel + + // Read Terraform plan data into the model + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + var signingKey SigningKeyPostRequestAPIModel + resp.Diagnostics.Append(plan.toAPIModel(ctx, &signingKey)...) + if resp.Diagnostics.HasError() { + return + } + + var result SigningKeyPostResponseAPIModel + var postErr SigningKeyPostErrorAPIModel + + response, err := r.ProviderData.Client.R(). + SetPathParam("protocol", plan.Protocol.ValueString()). + SetBody(signingKey). + SetResult(&result). + SetError(&postErr). + Post(SigningKeysEndpoint) + if err != nil { + utilfw.UnableToCreateResourceError(resp, err.Error()) + return + } + + if response.IsError() { + utilfw.UnableToCreateResourceError(resp, postErr.String()) + return + } + + tflog.Info(ctx, "Signing Key Create", map[string]interface{}{ + "report": result.Report.String(), + }) + + // Save data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *SigningKeyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + go util.SendUsageResourceRead(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName) + + var state SigningKeyResourceModel + + // Read Terraform state data into the model + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + + var signingKey SigningKeyGetAPIModel + + response, err := r.ProviderData.Client.R(). + SetPathParams(map[string]string{ + "protocol": state.Protocol.ValueString(), + "alias": state.Alias.ValueString(), + }). + SetResult(&signingKey). + Get(SigningKeyEndpoint) + if err != nil { + utilfw.UnableToRefreshResourceError(resp, err.Error()) + return + } + + if response.StatusCode() == http.StatusNotFound { + resp.State.RemoveResource(ctx) + return + } + + if response.IsError() { + utilfw.UnableToRefreshResourceError(resp, response.String()) + return + } + + // Save data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *SigningKeyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + go util.SendUsageResourceUpdate(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName) + + var plan SigningKeyResourceModel + + // Read Terraform plan data into the model + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + var state SigningKeyResourceModel + + // Read Terraform state data into the model + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + + signingKey := SigningKeyPutRequestAPIModel{ + NewAlias: plan.Alias.ValueString(), + } + + response, err := r.ProviderData.Client.R(). + SetPathParams(map[string]string{ + "protocol": state.Protocol.ValueString(), + "alias": state.Alias.ValueString(), + }). + SetBody(signingKey). + Put(SigningKeyEndpoint) + if err != nil { + utilfw.UnableToUpdateResourceError(resp, err.Error()) + return + } + + if response.IsError() { + utilfw.UnableToUpdateResourceError(resp, response.String()) + return + } + + // Save data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *SigningKeyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + go util.SendUsageResourceDelete(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName) + + var state SigningKeyResourceModel + + // Read Terraform prior state data into the model + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + + response, err := r.ProviderData.Client.R(). + SetPathParams(map[string]string{ + "protocol": state.Protocol.ValueString(), + "alias": state.Alias.ValueString(), + }). + Delete(SigningKeyEndpoint) + + if err != nil { + utilfw.UnableToDeleteResourceError(resp, err.Error()) + return + } + + if response.IsError() { + utilfw.UnableToDeleteResourceError(resp, response.String()) + return + } + + // If the logic reaches here, it implicitly succeeded and will remove + // the resource from state if there are no other errors. +} diff --git a/pkg/distribution/resource_signing_key_test.go b/pkg/distribution/resource_signing_key_test.go new file mode 100644 index 0000000..ca06e90 --- /dev/null +++ b/pkg/distribution/resource_signing_key_test.go @@ -0,0 +1,346 @@ +package distribution_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/jfrog/terraform-provider-shared/testutil" + "github.com/jfrog/terraform-provider-shared/util" +) + +func TestAccSigningKey_gpg_full(t *testing.T) { + _, fqrn, resourceName := testutil.MkNames("test-signing-key", "distribution_signing_key") + + const template = ` + resource "distribution_signing_key" "{{ .name }}" { + protocol = "gpg" + alias = "{{ .alias }}" + + private_key = < +// +// See https://github.com/jfrog/terraform-provider-distribution/wiki/How-to-setup-environment-for-testing-signing-key-from-Vault +func TestAccVaultSigningKey_full(t *testing.T) { + vaultID := os.Getenv("JFROG_VAULT_ID") + if vaultID == "" { + t.Skipf("env var JFROG_VAULT_ID is not set.") + } + + _, fqrn, resourceName := testutil.MkNames("test-vault-signing-key", "distribution_vault_signing_key") + + const template = ` + resource "distribution_vault_signing_key" "{{ .name }}" { + protocol = "gpg" + vault_id = "{{ .vault_id }}" + + public_key = { + path = "{{ .vault_secret_path }}" + key = "public" + } + + private_key = { + path = "{{ .vault_secret_path }}" + key = "private" + } + + propagate_to_edge_nodes = true + fail_on_propagation_failure = true + set_as_default = true + }` + + testData := map[string]string{ + "name": resourceName, + "vault_id": vaultID, + "vault_secret_path": "secret/signing_key", + } + + config := util.ExecuteTemplate("TestAccVaultSigningKey_gpg_full", template, testData) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProviders(), + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(fqrn, "protocol", "gpg"), + resource.TestCheckResourceAttrSet(fqrn, "alias"), + resource.TestCheckResourceAttr(fqrn, "public_key.path", testData["vault_secret_path"]), + resource.TestCheckResourceAttr(fqrn, "public_key.key", "public"), + resource.TestCheckResourceAttr(fqrn, "private_key.path", testData["vault_secret_path"]), + resource.TestCheckResourceAttr(fqrn, "private_key.key", "private"), + resource.TestCheckResourceAttr(fqrn, "propagate_to_edge_nodes", "true"), + resource.TestCheckResourceAttr(fqrn, "fail_on_propagation_failure", "true"), + resource.TestCheckResourceAttr(fqrn, "set_as_default", "true"), + ), + }, + }, + }) +} diff --git a/pkg/distribution/signing_key.go b/pkg/distribution/signing_key.go new file mode 100644 index 0000000..ae67fd0 --- /dev/null +++ b/pkg/distribution/signing_key.go @@ -0,0 +1,121 @@ +package distribution + +import ( + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/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/samber/lo" +) + +const ( + SigningKeysEndpoint = "distribution/api/v1/keys/{protocol}" + SigningKeyEndpoint = "distribution/api/v1/keys/{protocol}/{alias}" +) + +type SigningKeyCommmonResourceModel struct { + Protocol types.String `tfsdk:"protocol"` + Alias types.String `tfsdk:"alias"` + PropagateToEdgeNode types.Bool `tfsdk:"propagate_to_edge_nodes"` + FailOnPropagationFailure types.Bool `tfsdk:"fail_on_propagation_failure"` + SetAsDefault types.Bool `tfsdk:"set_as_default"` +} + +type SigningKeyCommonPostRequestAPIModel struct { + PropagateToEdgeNode bool `json:"propagate_to_edge_nodes"` + FailOnPropagationFailure bool `json:"fail_on_propagation_failure"` + SetAsDefault bool `json:"set_as_default"` +} + +type SigningKeyPostResponseAPIModel struct { + Report SigningKeyReportPostResponseAPIModel `json:"report"` +} + +type SigningKeyReportPostResponseAPIModel struct { + Message string `json:"message"` + Status string `json:"status"` + Details []SigningKeyReportDetailPostResponseAPIModel `json:"details"` +} + +type SigningKeyReportDetailPostResponseAPIModel struct { + JPDID string `json:"jpd_id"` + Name string `json:"name"` + KeyAlias string `json:"key_alias"` + Status string `json:"status"` +} + +func (m SigningKeyReportPostResponseAPIModel) String() string { + details := lo.Map( + m.Details, + func(detail SigningKeyReportDetailPostResponseAPIModel, _ int) string { + return fmt.Sprintf("JPD ID: %s, Name: %s, Key alias: %s, Status: %s", detail.JPDID, detail.Name, detail.KeyAlias, detail.Status) + }, + ) + return fmt.Sprintf("%s: %s - %s", m.Status, m.Message, strings.Join(details, ",\n")) +} + +type SigningKeyPostErrorAPIModel struct { + StatusCode int `json:"status_code"` + Message string `json:"message"` + Detail string `json:"detail"` +} + +func (m SigningKeyPostErrorAPIModel) String() string { + return fmt.Sprintf("%d - %s: %s", m.StatusCode, m.Message, m.Detail) +} + +type SigningKeyGetAPIModel struct { + Alias string `json:"alias"` + PublicKey string `json:"public_key"` +} + +type SigningKeyPutRequestAPIModel struct { + NewAlias string `json:"new_alias"` +} + +var commonSchemaAttributes = map[string]schema.Attribute{ + "alias": schema.StringAttribute{ + Required: true, + Validators: []validator.String{ + stringvalidator.LengthAtLeast(1), + }, + Description: "Alias of the signing key", + }, + "protocol": schema.StringAttribute{ + Required: true, + Validators: []validator.String{ + stringvalidator.OneOf("gpg", "pgp"), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + Description: "Type of the signing key. Valid value: `gpg` or `pgp`", + }, + "propagate_to_edge_nodes": schema.BoolAttribute{ + Optional: true, + PlanModifiers: []planmodifier.Bool{ + boolplanmodifier.RequiresReplace(), + }, + MarkdownDescription: "When set to `true`, the public key will be automatically propagated to the Edge Node just once.", + }, + "fail_on_propagation_failure": schema.BoolAttribute{ + Optional: true, + PlanModifiers: []planmodifier.Bool{ + boolplanmodifier.RequiresReplace(), + }, + MarkdownDescription: "When set to `true`, the public key will be automatically propagated to the Edge Node just once.", + }, + "set_as_default": schema.BoolAttribute{ + Optional: true, + PlanModifiers: []planmodifier.Bool{ + boolplanmodifier.RequiresReplace(), + }, + MarkdownDescription: "Set this to `true` if this is the first key that is set or if there is no default key in Artifactory.", + }, +} diff --git a/pkg/distribution/util_test.go b/pkg/distribution/util_test.go new file mode 100644 index 0000000..cd0a15d --- /dev/null +++ b/pkg/distribution/util_test.go @@ -0,0 +1,84 @@ +package distribution_test + +import ( + "os" + "sync" + "testing" + + "github.com/go-resty/resty/v2" + "github.com/hashicorp/terraform-plugin-framework/provider" + "github.com/hashicorp/terraform-plugin-framework/providerserver" + "github.com/hashicorp/terraform-plugin-go/tfprotov6" + "github.com/jfrog/terraform-provider-distribution/pkg/distribution" + "github.com/jfrog/terraform-provider-shared/client" +) + +// TestProvider PreCheck(t) must be called before using this provider instance. +var TestProvider provider.Provider + +// testAccProviderConfigure ensures Provider is only configured once +// +// The PreCheck(t) function is invoked for every test and this prevents +// extraneous reconfiguration to the same values each time. However, this does +// not prevent reconfiguration that may happen should the address of +// Provider be errantly reused in ProviderFactories. +var testAccProviderConfigure sync.Once + +// testAccPreCheck This function should be present in every acceptance test. +func testAccPreCheck(t *testing.T) { + // Since we are outside the scope of the Terraform configuration we must + // call Configure() to properly initialize the provider configuration. + testAccProviderConfigure.Do(func() { + restyClient := getTestResty(t) + + platformUrl := getPlatformUrl(t) + // Set custom base URL so repos that relies on it will work + // https://www.jfrog.com/confluence/display/JFROG/Artifactory+REST+API#ArtifactoryRESTAPI-UpdateCustomURLBase + _, err := restyClient.R(). + SetBody(platformUrl). + SetHeader("Content-Type", "text/plain"). + Put("/artifactory/api/system/configuration/baseUrl") + if err != nil { + t.Fatalf("failed to set custom base URL: %v", err) + } + }) +} + +func getTestResty(t *testing.T) *resty.Client { + var ok bool + + platformUrl := getPlatformUrl(t) + + restyClient, err := client.Build(platformUrl, "") + if err != nil { + t.Fatal(err) + } + + var accessToken string + if accessToken, ok = os.LookupEnv("JFROG_ACCESS_TOKEN"); !ok { + t.Fatal("JFROG_ACCESS_TOKEN must be set for acceptance tests") + } + restyClient, err = client.AddAuth(restyClient, "", accessToken) + if err != nil { + t.Fatal(err) + } + + return restyClient +} + +func getPlatformUrl(t *testing.T) string { + platformUrl, ok := os.LookupEnv("JFROG_URL") + if !ok { + t.Fatal("JFROG_URL must be set for acceptance tests") + } + + return platformUrl +} + +func testAccProviders() map[string]func() (tfprotov6.ProviderServer, error) { + TestProvider = distribution.NewProvider()() + + return map[string]func() (tfprotov6.ProviderServer, error){ + "distribution": providerserver.NewProtocol6WithError(TestProvider), + } +} diff --git a/templates/index.md.tmpl b/templates/index.md.tmpl new file mode 100644 index 0000000..6680528 --- /dev/null +++ b/templates/index.md.tmpl @@ -0,0 +1,88 @@ +--- +layout: "" +page_title: "JFrog Distribution Provider" +description: |- + The JFrog Distribution provider provides resources to interact with features from JFrog distribution. +--- + +# JFrog Distribution Provider + +The [JFrog](https://jfrog.com/) Distribution provider is used to interact with the features from [JFrog Distribution REST API](https://jfrog.com/help/r/jfrog-rest-apis/distribution-rest-apis). The provider needs to be configured with the proper credentials before it can be used. + +Links to documentation for specific resources can be found in the table of contents to the left. + +## Example Usage + +{{tffile "examples/example.tf"}} + +## Authentication + +The JFrog Distribution provider supports for the following types of authentication: +* Scoped token +* Terraform Cloud OIDC provider + +### Scoped Token + +JFrog scoped tokens may be used via the HTTP Authorization header by providing the `access_token` field to the provider block. Getting this value from the environment is supported with the `JFROG_ACCESS_TOKEN` environment variable. + +Usage: +```terraform +provider "distribution" { + url = "myinstance.jfrog.io" + access_token = "abc...xy" +} +``` + +### Terraform Cloud OIDC Provider + +If you are using this provider on Terraform Cloud and wish to use dynamic credentials instead of static access token for authentication with JFrog platform, you can leverage Terraform as the OIDC provider. + +To setup dynamic credentials, follow these steps: +1. Configure Terraform Cloud as a generic OIDC provider +2. Set environment variable in your Terraform Workspace +3. Setup Terraform Cloud in your configuration + +During the provider start up, if it finds env var `TFC_WORKLOAD_IDENTITY_TOKEN` it will use this token with your JFrog instance to exchange for a short-live access token. If that is successful, the provider will the access token for all subsequent API requests with the JFrog instance. + +#### Configure Terraform Cloud as generic OIDC provider + +Follow [confgure an OIDC integration](https://jfrog.com/help/r/jfrog-platform-administration-documentation/configure-an-oidc-integration). Enter a name for the provider, e.g. `terraform-cloud`. Use `https://app.terraform.io` for "Provider URL". Choose your own value for "Audience", e.g. `jfrog-terraform-cloud`. + +Then [configure an identity mapping](https://jfrog.com/help/r/jfrog-platform-administration-documentation/configure-identity-mappings) with an empty "Claims JSON" (`{}`), and select the "Token scope", "User", and "Service" as desired. + +#### Set environment variable in your Terraform Workspace + +In your workspace, add an environment variable `TFC_WORKLOAD_IDENTITY_AUDIENCE` with audience value (e.g. `jfrog-terraform-cloud`) from JFrog OIDC integration above. See [Manually Generating Workload Identity Tokens](https://developer.hashicorp.com/terraform/cloud-docs/workspaces/dynamic-provider-credentials/manual-generation) for more details. + +When a run starts on Terraform Cloud, it will create a workload identity token with the specified audience and assigns it to the environment variable `TFC_WORKLOAD_IDENTITY_TOKEN` for the provider to consume. + +#### Setup Terraform Cloud in your configuration + +Add `cloud` block to `terraform` block, and add `oidc_provider_name` attribute (from JFrog OIDC integration) to provider block: + +```terraform +terraform { + cloud { + organization = "my-org" + workspaces { + name = "my-workspace" + } + } + + required_providers { + platform = { + source = "jfrog/distribution" + version = "1.0.0" + } + } +} + +provider "platform" { + url = "https://myinstance.jfrog.io" + oidc_provider_name = "terraform-cloud" +} +``` + +**Note:** Ensure `access_token` attribute is not set + +{{ .SchemaMarkdown | trimspace }} \ No newline at end of file diff --git a/terraform-registry-manifest.json b/terraform-registry-manifest.json new file mode 100644 index 0000000..295001a --- /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 0000000..2844b66 --- /dev/null +++ b/tools/tools.go @@ -0,0 +1,8 @@ +//go:build tools + +package tools + +import ( + // document generation + _ "github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs" +)