Compare commits

...
35 Commits
Author SHA1 Message Date
dependabot[bot]andAndrei Ciobanu 072b9103f4 chore(deps): Bump semver from 7.8.5 to 7.8.6 (#144)
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
2026-11-10 11:37:58 +02:00
Andrei Ciobanu 96ef8e8ef7 Update dependencies to fix high severity security issues (#145)
Signed-off-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
2026-11-10 11:28:10 +02:00
Andrei Ciobanu d1e6b1026d Upgrade dependencies to fix high severity issues (#142)
Signed-off-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
2026-10-02 14:48:49 +03:00
dependabot[bot] 44508bff04 chore(deps-dev): Bump jest from 30.5.1 to 30.5.2 (#141)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-02 12:41:15 +03:00
dependabot[bot] 1ecf18781e chore(deps-dev): Bump jest from 30.5.0 to 30.5.1 (#139)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-16 08:05:52 +03:00
James Humphriesandgithub-actions[bot] fd1f729ebf [Org] Sync AI usage policy (#136)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-09-15 10:47:37 +01:00
Andrei Ciobanu fb72d0a2d4 Bump dependency to fix security issue (#138)
Signed-off-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
2026-09-09 12:17:50 +01:00
dependabot[bot] 3dc45c9802 chore(deps-dev): Bump jest from 30.4.2 to 30.5.0 (#137)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-08 12:47:35 +03:00
dependabot[bot]andAndrei Ciobanu b648b1c29e chore(deps-dev): Bump @vercel/ncc from 0.44.1 to 0.45.0 (#135)
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
2026-08-25 08:51:52 +03:00
Andrei Ciobanu 94ffd00999 Upgrade vulnerable packages (#134)
Signed-off-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
2026-08-04 14:18:19 +03:00
dependabot[bot] 22f847ff73 chore(deps): Bump actions/checkout from 7.0.0 to 7.0.1 (#133)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-03 09:38:17 +03:00
somaz 37a417e5ae feat: support .tool-versions (asdf format) in tofu_version_file (#131)
Signed-off-by: somaz <genius5711@gmail.com>
2026-07-10 18:37:53 +03:00
dependabot[bot] 7f68c568ed chore(deps-dev): Bump @vercel/ncc from 0.44.0 to 0.44.1 (#132)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-07 07:16:53 +03:00
dependabot[bot] cf87c0adc1 chore(deps-dev): Bump @vercel/ncc from 0.38.4 to 0.44.0 (#126)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-06 10:09:47 +03:00
dependabot[bot]andAndrei Ciobanu cb2c66ad3c chore(deps): Bump semver from 7.8.3 to 7.8.5 (#128)
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
2026-06-30 10:00:12 -03:00
Andrei CiobanuandDiógenes Fernandes 19d3fc38c4 Upgrade undici dependency to fix multiple vulnerabilities (#130)
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
Signed-off-by: Andrei Ciobanu <andrei.ciobanu@opentofu.org>
Co-authored-by: Diógenes Fernandes <diofeher@gmail.com>
2026-06-30 15:34:34 +03:00
dependabot[bot] 698c415dcd chore(deps): Bump actions/checkout from 6.0.3 to 7.0.0 (#129)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-30 11:04:57 +03:00
Diógenes Fernandes a1320f8929 release docs and bump to 2.0.2 (#127)
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
2026-06-29 08:51:33 -03:00
somaz d3dc77de53 feat: verify download against published SHA256SUMS by default (#121)
Signed-off-by: somaz <genius5711@gmail.com>
2026-06-26 12:42:14 -03:00
dependabot[bot]andDiogenes Fernandes 56007213a1 chore(deps): Bump semver from 7.8.1 to 7.8.3 (#123)
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Diogenes Fernandes <diofeher@gmail.com>
2026-06-16 08:54:54 -03:00
dependabot[bot] 7051243a57 chore(deps): Bump actions/checkout from 6.0.2 to 6.0.3 (#124)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-15 21:00:46 -03:00
dependabot[bot] 50e079f741 chore(deps): Bump actions/checkout from 6 to 6.0.2
Bumps [actions/checkout](https://github.com/actions/checkout) from 6 to 6.0.2.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v6...v6.0.2)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 6.0.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-05 08:40:43 -07:00
dependabot[bot]andDiogenes Fernandes 0c73a96b62 chore(deps): Bump semver from 7.8.0 to 7.8.1 (#119)
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Diogenes Fernandes <diofeher@gmail.com>
2026-06-03 12:02:29 -03:00
dependabot[bot]andMartin Atkins 7526f4bce4 chore(deps): Bump semver from 7.7.4 to 7.8.0
Bumps [semver](https://github.com/npm/node-semver) from 7.7.4 to 7.8.0.
- [Release notes](https://github.com/npm/node-semver/releases)
- [Changelog](https://github.com/npm/node-semver/blob/main/CHANGELOG.md)
- [Commits](https://github.com/npm/node-semver/compare/v7.7.4...v7.8.0)

---
updated-dependencies:
- dependency-name: semver
  dependency-version: 7.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Co-authored-by: Martin Atkins <mart@degeneration.co.uk>
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Martin Atkins <mart@degeneration.co.uk>
2026-05-19 13:45:38 -07:00
dependabot[bot] a630d3b887 chore(deps-dev): Bump jest from 30.3.0 to 30.4.2
Bumps [jest](https://github.com/jestjs/jest/tree/HEAD/packages/jest) from 30.3.0 to 30.4.2.
- [Release notes](https://github.com/jestjs/jest/releases)
- [Changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jestjs/jest/commits/v30.4.2/packages/jest)

---
updated-dependencies:
- dependency-name: jest
  dependency-version: 30.4.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-19 13:31:53 -07:00
dependabot[bot] 7e2b8769cc chore(deps): Bump @actions/core from 3.0.0 to 3.0.1
Bumps [@actions/core](https://github.com/actions/toolkit/tree/HEAD/packages/core) from 3.0.0 to 3.0.1.
- [Changelog](https://github.com/actions/toolkit/blob/main/packages/core/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/core)

---
updated-dependencies:
- dependency-name: "@actions/core"
  dependency-version: 3.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-19 13:30:44 -07:00
dependabot[bot]andDiogenes Fernandes 847eaa4afe chore(deps): Bump @actions/http-client from 4.0.0 to 4.0.1 (#114)
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Diogenes Fernandes <diofeher@gmail.com>
2026-05-05 06:34:17 -03:00
Anthony Hoivik 34bf4e3161 feat(acc): Add provider_acceptance_tests input for automated acceptance test setup (#97)
Signed-off-by: hoivikaj <github@hoivik.co>
Signed-off-by: Anthony Hoivik <38190936+hoivikaj@users.noreply.github.com>
2026-04-15 23:08:57 -03:00
Kim Wagner 4bcfe8cded feat: added support for providing optional checksums for ZIP validation (#107)
Signed-off-by: Kim <kim.peter.wagner@gmail.com>
2026-04-13 16:46:38 -03:00
Diógenes Fernandes 03a9076efe deps: picomatch in npm audit (#103)
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
2026-03-26 16:00:33 -03:00
Anthony HoivikandDiógenes Fernandes ba1f8b8e04 chore(ci): dependabot actions ecosystem, conventional commits (#98)
Signed-off-by: hoivikaj <github@hoivik.co>
Signed-off-by: Diógenes Fernandes <diofeher@gmail.com>
Co-authored-by: Diógenes Fernandes <diofeher@gmail.com>
2026-03-26 14:10:12 -03:00
Andy Brody 26ccb9be2d Update README with latest action versions. (#99)
Signed-off-by: Andy Brody <git@abrody.com>
2026-03-20 11:23:02 -04:00
Anthony Hoivik b572e07b01 feat(error-handling): error notification for network failures (#94)
Signed-off-by: hoivikaj <github@hoivik.co>
2026-03-17 15:23:28 -03:00
Diogenes Fernandes 4959f8f18c fix: npm audit
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
2026-03-17 15:13:56 -03:00
fc711fa910 Update Node.js runtime to 24 (#91)
Signed-off-by: Dawid Jóźwiak <5508474+Operativ@users.noreply.github.com>
Signed-off-by: James Humphries <james@james-humphries.co.uk>
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
Co-authored-by: Dawid Jóźwiak <5508474+Operativ@users.noreply.github.com>
Co-authored-by: Diogenes Fernandes <diofeher@gmail.com>
2026-03-12 09:19:16 +00:00
26 changed files with 48524 additions and 43810 deletions

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
## Releasing
Releases are made on a reasonably regular basis by the maintainers. The following notes are only relevant to maintainers.
Release process:
1. Create a PR against `main` with the following changes:
- Update the version in `package.json`:
```shell
npm version patch|minor|major --no-git-tag-version
```
- Run the build to update the `dist/` directory:
```shell
npm run build
```
2. Review and merge the PR.
3. [Create and publish a GitHub release](https://github.com/opentofu/setup-opentofu/releases/new) with tag `vX.Y.Z`, using the auto-generated release notes as the release body.
4. Update the rolling major version tag to point to the new release:
```shell
git tag -f v2 vX.Y.Z
git push --force origin v2
```
This allows users to pin to `opentofu/setup-opentofu@v2` and always get the latest version of the rolling tag.
+6
View File
@@ -6,3 +6,9 @@ updates:
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "github-actions"
cooldown:
default-days: 7
directory: "/"
schedule:
interval: "weekly"
+2 -2
View File
@@ -11,9 +11,9 @@ jobs:
name: Check dist/ directory
uses: actions/reusable-workflows/.github/workflows/check-dist.yml@2826fb8353263a138210fc017301ce5767a9c0d4
with:
node-version: "20.19.1"
node-version: "24.14.0"
test:
name: Test
uses: actions/reusable-workflows/.github/workflows/basic-validation.yml@2826fb8353263a138210fc017301ce5767a9c0d4
with:
node-version: "20.19.1"
node-version: "24.14.0"
-21
View File
@@ -1,21 +0,0 @@
name: Retag
on:
push:
tags:
- 'v[1-2].[0-9]+.[0-9]+*'
defaults:
run:
shell: bash
jobs:
tag:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: |
set -o pipefail
git tag --force "$(grep '^v[1-2]\.[0-9]\+\.[0-9]\+\(.*\)\?$' <<< ${GITHUB_REF#refs/*/} | sed 's/^v\([1-2]\)\..*/v\1/')"
git push --tag --force
+7 -7
View File
@@ -23,7 +23,7 @@ jobs:
tofu-version-files: ['./.github/workflows/data/local/.opentofu-version']
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7.0.1
- name: Setup OpenTofu - ${{ matrix['tofu-version-files'] }}
uses: ./
@@ -43,7 +43,7 @@ jobs:
tofu-wrapper: [true, false]
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7.0.1
- name: Setup OpenTofu - ${{ matrix['tofu-versions'] }}
uses: ./
@@ -66,7 +66,7 @@ jobs:
tofu-wrapper: [true, false]
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7.0.1
- name: Setup OpenTofu
uses: ./
@@ -103,7 +103,7 @@ jobs:
working-directory: ./.github/workflows/data/local
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7.0.1
- name: Setup OpenTofu
uses: ./
@@ -133,7 +133,7 @@ jobs:
TF_CLOUD_API_TOKEN: 'XXXXXXXXXXXXXX.atlasv1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7.0.1
- name: Setup OpenTofu
uses: ./
@@ -162,7 +162,7 @@ jobs:
TF_CLOUD_API_TOKEN: 'XXXXXXXXXXXXXX.atlasv1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7.0.1
- name: Setup OpenTofu
uses: ./
@@ -190,7 +190,7 @@ jobs:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7.0.1
- name: Setup OpenTofu
uses: ./
-3
View File
@@ -1,6 +1,3 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint || (npm install && npm run lint)
npm run test
npm audit --audit-level=high
+75
View File
@@ -0,0 +1,75 @@
> [!NOTE]
> All revisions to this document must be handwritten and cannot use AI in either assistance or ideation.
Each repository in the OpenTofu org has its own AI policy, which is determined on a case-by-case basis. This policy applies solely to this repository.
### Reason for this policy
Automated tooling, whether using LLMs or other static analysis, is easy to scale. We have yet to determine a way to scale our maintainers' attention. The quality standards for code merged into this repository have not changed because AI tools exist. We have seen a rise in AI-generated pull requests across the open source community as a whole including patches that authors cannot explain, fixes for problems that do not exist and “improvements” that break working code.
Beyond quality, the OpenTofu maintainers cannot verify the origins of any given model’s training data. A model may reproduce code from a license-incompatible source, most notably the BUSL-licensed codebase of HashiCorp’s Terraform, from which OpenTofu at its core was forked. Because we are unable to audit this, we have decided that the risk is too high.
This policy is purposely stricter than the [Linux Foundation's Generative AI Policy](https://www.linuxfoundation.org/legal/generative-ai), which explicitly permits individual projects to set their own rules. OpenTofu's situation as a fork from a now-proprietary codebase warrants additional caution.
### Rules for community contributors
OpenTofu welcomes human-written contributions from the open source community. We are happy to review pull requests that you wrote yourself, line by line.
**We do not accept AI-generated code from community contributors.** This applies to any code generated, completed or rewritten by an AI tool. If an AI wrote part of your contribution, we cannot accept it.
**If you discover a bug or possible improvement using AI tools**, feel free to open an issue instead of a pull request. Describe the problem in your own words and a maintainer or other community member may discuss this, pick it up, and implement a fix under the same rules of this policy and contributing guidelines. We emphasize that no code generated or suggested by an AI tool used for analysis should be included in the description of these issues.
Pull requests identified as AI-generated will be closed without further review.
### Rules for Maintainers
The rules below apply to OpenTofu maintainers who are using AI tooling when contributing to this repository. These rules sit alongside the existing review and quality standards and not in place of them. AI does not change what is expected from a maintainer’s pull request, the standards bar is still the same.
#### Class B-specific: Maintainer discretion
Whether AI tooling may be used for a contribution is decided by OpenTofu maintainers on a case-by-case basis. If its use is permitted, only the tooling approved below may be used, and all remaining rules in this policy apply.
#### Approved Tooling
Github Copilot Enterprise is the only approved AI tool on this repository as of 25th June 2026. Other tools may be evaluated and added to this list in the future, but until then, all other AI coding assistants are not permitted on this codebase.
#### Disclosure
If you did use AI tooling in any part of this contribution, you must disclose this in the pull request description. “Any part” here includes generated code, AI suggested edits, AI assisted refactoring, and documentation. See Commit attribution below.
#### Author responsibility
You must be able to understand and explain every line you submit. Maintainers remain fully responsible for the quality, correctness, and provenance of the code they contribute. The standards for pull requests have not changed because AI tooling exists.
If you as the author of a contribution cannot explain a line of code on your own pull request during review then you should not be submitting it.
#### Commit messages
Commit messages must be human-written. The commit message is a description of your intent as a human. As this is a critical part of conveying understanding of the contribution it is important to ensure that AI tooling is not used to create commit messages.
#### Commit attribution
Every commit that uses AI assistance must include an `Assisted-by` trailer at the end of the commit message.
Format :
```
Assisted-by: Github Copilot (Model: <modelname>)
```
For example:
```
Assisted-by: GitHub Copilot (Model: Claude Opus 4.7)
```
**Do not use `Co-authored-by:` for AI tools.**
> [!IMPORTANT] Squash merging
> When merging a pull request into its target branch, GitHub may not carry individual commit trailers into the squashed commit message. The maintainer performing the merge must ensure that a copy of the `Assisted-by:` trailer (or trailers) is made into the final squashed commit message.
#### Reviewing contributions
When reviewing a pull request, your review must be human-written. AI may be used to **assist** a review, for example as a second pass after you have formed your own opinion, but this cannot replace your judgement as a maintainer. Form your own initial view first and then use AI assistance to check it against AI input.
The human review is always accountable for the review they post as if it was a contribution. AI usage here should be purely additive and never a replacement.
+48 -12
View File
@@ -16,14 +16,14 @@ The default configuration installs the latest version of OpenTofu CLI and instal
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
```
A specific version of OpenTofu CLI can be installed:
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
tofu_version: 1.6.0
```
@@ -32,18 +32,23 @@ You can also specify the version in a file (e.g., `.opentofu-version`):
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
tofu_version_file: .opentofu-version
```
`tofu_version_file` accepts two formats:
- A single-line file containing just the version (e.g., `.opentofu-version` with `1.9.0`).
- An asdf-format `.tool-versions` file containing an `opentofu <version>` line. Other tool entries in the same file are ignored.
Supported version syntax is the same as for the `tofu_version` input. If both `tofu_version` and `tofu_version_file` are provided, the version number in the file takes precedence.
Credentials for Terraform Cloud ([app.terraform.io](https://app.terraform.io/)) can be configured:
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
```
@@ -52,7 +57,7 @@ Credentials for Terraform Enterprise (TFE) can be configured:
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
cli_config_credentials_hostname: 'tofu.example.com'
cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
@@ -62,7 +67,7 @@ The wrapper script installation can be skipped by setting the `tofu_wrapper` var
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
tofu_wrapper: false
```
@@ -71,16 +76,42 @@ Caching can be enabled to reduce download time on subsequent workflow runs by st
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
cache: true
```
Provider acceptance test environment variables can be configured automatically by setting `provider_acceptance_tests` to `true`. This exports `TF_ACC`, `TF_ACC_PROVIDER_NAMESPACE`, `TF_ACC_PROVIDER_HOST`, and `TF_ACC_TERRAFORM_PATH` so you don't need to set them manually:
```yaml
steps:
- uses: opentofu/setup-opentofu@v2
with:
tofu_wrapper: false
provider_acceptance_tests: true
- run: go mod download
- run: go test -v -cover ./...
timeout-minutes: 10
```
By default, the action verifies the downloaded OpenTofu CLI ZIP against the SHA-256 checksum published in the release's `SHA256SUMS` file, so the default install path is verified out of the box. Verification is skipped (with a warning) only when the published checksum cannot be retrieved.
To pin the expected hashes yourself instead, pass a newline-delimited list of checksums. When set, this list takes precedence over the published `SHA256SUMS`:
```yaml
steps:
- uses: opentofu/setup-opentofu@v2
with:
checksums: |
933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad
d3d29f51e75a701fc7cf67c0644a8c883a85f36cf1621461988baffd88e7f361
```
Subsequent steps can access outputs when the wrapper script is installed:
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
- run: tofu init
@@ -107,8 +138,8 @@ defaults:
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v3
- uses: opentofu/setup-opentofu@v1
- uses: actions/checkout@v6
- uses: opentofu/setup-opentofu@v2
- name: OpenTofu fmt
id: fmt
@@ -175,8 +206,8 @@ defaults:
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v3
- uses: opentofu/setup-opentofu@v1
- uses: actions/checkout@v6
- uses: opentofu/setup-opentofu@v2
- name: OpenTofu fmt
id: fmt
@@ -274,7 +305,12 @@ The action supports the following inputs:
the `tofu` binary and expose its STDOUT, STDERR, and exit code as outputs
named `stdout`, `stderr`, and `exitcode` respectively. Defaults to `true`.
- `cache` - (optional) Whether to use GitHub Actions tool-cache to store and reuse downloaded OpenTofu binaries. Defaults to `false`.
- `provider_acceptance_tests` - (optional) Whether to automatically set environment variables for running
OpenTofu provider acceptance tests. When set to `true`, the following environment variables are exported:
`TF_ACC=1`, `TF_ACC_PROVIDER_NAMESPACE=hashicorp`, `TF_ACC_PROVIDER_HOST=registry.opentofu.org`, and
`TF_ACC_TERRAFORM_PATH=<path to tofu binary>`. Defaults to `false`.
- `github_token` - (optional) Override the GitHub token read from the environment variable. Defaults to the value of the `GITHUB_TOKEN` environment variable unless running on Forgejo or Gitea.
- `checksums` - (optional) A newline-delimited list of valid checksums (SHA256) for the downloaded OpenTofu CLI ZIP. When set, the action will verify the ZIP matches one of the checksums before proceeding. When unset, the action verifies the ZIP against the SHA-256 checksum published in the release's `SHA256SUMS` file by default. Defaults to `[]`
## Outputs
+8 -1
View File
@@ -28,6 +28,13 @@ inputs:
description: 'API token for GitHub to increase the rate limit. Defaults to the GITHUB_TOKEN environment variable unless running on Forgejo/Gitea.'
default: ''
required: false
provider_acceptance_tests:
description: 'Whether to automatically set environment variables for running OpenTofu provider acceptance tests (TF_ACC, TF_ACC_PROVIDER_NAMESPACE, TF_ACC_PROVIDER_HOST, TF_ACC_TERRAFORM_PATH). Defaults to `false`.'
default: 'false'
required: false
checksums:
description: Newline-delimited list of valid checksums (SHA256 hashes) for the downloaded OpenTofu binary. When set, the action verifies the binary matches one of these checksums before proceeding. When unset, the action verifies the binary against the SHA-256 checksum published in the release's SHA256SUMS file by default.
required: false
outputs:
stdout:
description: 'The STDOUT stream of the call to the `tofu` binary.'
@@ -43,5 +50,5 @@ branding:
icon: 'box'
color: 'yellow'
runs:
using: 'node20'
using: 'node24'
main: 'dist/index.js'
+20820 -21091
View File
File diff suppressed because it is too large. Load diff
+18847 -15115
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
{
"type": "module"
}
+7 -3
View File
@@ -1,16 +1,20 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
const core = require('@actions/core');
import { setFailed, debug } from '@actions/core';
const setup = require('./lib/setup-tofu');
import setup from './lib/setup-tofu.js';
import { getErrorMessage, getErrorDetail } from './lib/error-utils.js';
(async () => {
try {
await setup();
} catch (error) {
core.setFailed(error.message);
const message = getErrorMessage(error);
debug(getErrorDetail(error));
setFailed(message);
}
})();
+75
View File
@@ -0,0 +1,75 @@
/**
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*
* Normalizes errors (including AggregateError from fetch/undici) into
* a single, actionable message for GitHub Actions logs.
*/
/**
* Get a user-friendly message from any error.
* - AggregateError: flattens error.errors so network/download causes are visible.
* - Standard Error: returns message; includes cause if present (Node 16+).
*
* @param {unknown} error - Caught value (Error, AggregateError, or other).
* @returns {string} Single-line message suitable for core.setFailed().
*/
function getErrorMessage (error) {
if (error instanceof AggregateError && Array.isArray(error.errors)) {
if (error.errors.length === 0) {
return 'AggregateError (one or more operations failed)';
}
const parts = error.errors.map((e) => (e && typeof e.message === 'string' ? e.message : String(e)));
const combined = parts.join('; ');
return combined || 'AggregateError (one or more operations failed)';
}
if (error instanceof Error) {
if (error.cause instanceof Error) {
return `${error.message}: ${error.cause.message}`;
}
return error.message;
}
return String(error);
}
/**
* Get a detailed string for logging (e.g. core.debug or core.error).
* Includes stack and, for AggregateError, each nested error.
*
* @param {unknown} error - Caught value.
* @returns {string} Multi-line detail string.
*/
function getErrorDetail (error) {
const lines = [];
if (error instanceof AggregateError && Array.isArray(error.errors)) {
lines.push(`AggregateError (${error.errors.length} error(s)):`);
error.errors.forEach((e, i) => {
lines.push(` [${i + 1}] ${e instanceof Error ? e.message : String(e)}`);
if (e instanceof Error && e.stack) {
lines.push(e.stack.split('\n').map((l) => ' ' + l).join('\n'));
}
});
if (error.stack) {
lines.push('Outer stack:');
lines.push(error.stack);
}
return lines.join('\n');
}
if (error instanceof Error) {
lines.push(error.message);
if (error.stack) lines.push(error.stack);
if (error.cause) {
lines.push('Caused by:');
lines.push(getErrorDetail(error.cause));
}
return lines.join('\n');
}
return String(error);
}
export { getErrorMessage, getErrorDetail };
+146 -29
View File
@@ -1,24 +1,31 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { HttpClient, HttpCodes } from '@actions/http-client';
import semver from 'semver';
import { getErrorMessage } from './error-utils.js';
class Build {
constructor (version, name) {
this.name = name;
this.url = 'https://github.com/opentofu/opentofu/releases/download/v' + version + '/' + name;
this.url = `https://github.com/opentofu/opentofu/releases/download/v${version}/${name}`;
}
}
class Release {
constructor (releaseMeta) {
this.version = releaseMeta.id.replace('v', '');
this.builds = releaseMeta.files.map(asset => new Build(this.version, asset));
this.builds = releaseMeta.files.map(
(asset) => new Build(this.version, asset)
);
}
getBuild (platform, arch) {
const requiredName = `tofu_${this.version}_${platform}_${arch}.zip`;
return this.builds.find(build => build.name === requiredName);
return this.builds.find((build) => build.name === requiredName);
}
}
@@ -28,10 +35,9 @@ class Release {
* @return {Array<Release>} Releases.
*/
async function fetchReleases (githubToken) {
const hc = require('@actions/http-client');
const userAgent = 'opentofu/setup-opentofu';
const http = new hc.HttpClient(userAgent);
const http = new HttpClient(userAgent);
const url = 'https://get.opentofu.org/tofu/api.json';
@@ -39,31 +45,135 @@ async function fetchReleases (githubToken) {
Accept: 'application/json'
};
const resp = await http.get(url, headers);
if (resp.message.statusCode !== hc.HttpCodes.OK) {
throw new Error('failed fetching releases (' + resp.message.statusCode + ')');
let resp;
try {
resp = await http.get(url, headers);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to fetch OpenTofu releases from ${url}: ${cause}`);
}
const body = await resp.readBody();
const releasesMeta = JSON.parse(body);
if (resp.message.statusCode !== HttpCodes.OK) {
throw new Error(
'failed fetching releases (' + resp.message.statusCode + ')'
);
}
let body;
try {
body = await resp.readBody();
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to read releases response: ${cause}`);
}
let releasesMeta;
try {
releasesMeta = JSON.parse(body);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Invalid releases JSON from ${url}: ${cause}`);
}
/**
* @type {Array}
*/
* @type {Array}
*/
const versions = releasesMeta.versions;
return versions.map(releaseMeta => new Release(releaseMeta));
return versions.map((releaseMeta) => new Release(releaseMeta));
}
const semver = require('semver');
/**
* Fetches the raw SHA256SUMS file published alongside an OpenTofu release.
*
* @param {string} version: Release version (without the leading `v`).
* @return {string} Raw SHA256SUMS file body.
*/
async function fetchSHA256SUMS (version) {
const userAgent = 'opentofu/setup-opentofu';
const http = new HttpClient(userAgent);
const url = `https://github.com/opentofu/opentofu/releases/download/v${version}/tofu_${version}_SHA256SUMS`;
let resp;
try {
resp = await http.get(url);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to fetch SHA256SUMS from ${url}: ${cause}`);
}
if (resp.message.statusCode !== HttpCodes.OK) {
throw new Error(
`failed fetching SHA256SUMS for ${url} (${resp.message.statusCode})`
);
}
return resp.readBody();
}
/**
* Parses a SHA256SUMS file body and returns the checksum for a given file name.
*
* Each line follows the `sha256sum` format: a lowercase hex digest, whitespace,
* then the file name (binary-mode lines prefix the name with `*`).
*
* @param {string} body: Raw SHA256SUMS file body.
* @param {string} fileName: Asset file name to look up.
* @return {string|null} Lowercase hex SHA-256 checksum, or null when not found.
*/
function parseChecksum (body, fileName) {
for (const line of body.split('\n')) {
const trimmed = line.trim();
if (trimmed === '') {
continue;
}
const separatorIndex = trimmed.search(/\s/);
if (separatorIndex === -1) {
continue;
}
const checksum = trimmed.slice(0, separatorIndex);
const name = trimmed.slice(separatorIndex).trim().replace(/^\*/, '');
if (name === fileName) {
return checksum.toLowerCase();
}
}
return null;
}
/**
* Resolves the published SHA-256 checksum for a release asset by fetching the
* release's SHA256SUMS file and looking up the asset's file name.
*
* @param {string} version: Release version (without the leading `v`).
* @param {string} fileName: Asset file name to look up.
* @param {function} fetchSumsFn: Optional fetcher for the SHA256SUMS body (for testing).
* @return {string|null} Lowercase hex SHA-256 checksum, or null when not found.
*/
async function getDownloadChecksum (
version,
fileName,
fetchSumsFn = fetchSHA256SUMS
) {
const body = await fetchSumsFn(version);
return parseChecksum(body, fileName);
}
async function findLatestVersion (versions) {
return versions.filter((v) => semver.prerelease(v) === null).sort((a, b) => semver.rcompare(a, b))[0];
return versions
.filter((v) => semver.prerelease(v) === null)
.sort((a, b) => semver.rcompare(a, b))[0];
}
async function findLatestVersionInRange (versions, range) {
return semver.maxSatisfying(versions, range, { prerelease: true, loose: true });
return semver.maxSatisfying(versions, range, {
prerelease: true,
loose: true
});
}
/**
@@ -74,12 +184,21 @@ async function findLatestVersionInRange (versions, range) {
* @param {function} fetchReleasesFn: Optional function to fetch releases.
* @return {Release} Release.
*/
async function getRelease (version, githubToken, fetchReleasesFn = fetchReleases) {
async function getRelease (
version,
githubToken,
fetchReleasesFn = fetchReleases
) {
const latestVersionLabel = 'latest';
const versionsRange = semver.validRange(version, { prerelease: true, loose: true });
const versionsRange = semver.validRange(version, {
prerelease: true,
loose: true
});
if (versionsRange === null && version !== latestVersionLabel) {
throw new Error('Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html');
throw new Error(
'Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html'
);
}
const releases = await fetchReleasesFn(githubToken);
@@ -88,24 +207,22 @@ async function getRelease (version, githubToken, fetchReleasesFn = fetchReleases
throw new Error('No tofu releases found, please contact OpenTofu');
}
const versionsFound = releases.map(release => release.version);
const versionsFound = releases.map((release) => release.version);
let versionSelected;
if (version === latestVersionLabel) {
versionSelected = await findLatestVersion(versionsFound);
} else {
versionSelected = await findLatestVersionInRange(versionsFound, versionsRange);
versionSelected = await findLatestVersionInRange(
versionsFound,
versionsRange
);
}
if (versionSelected === null) {
throw new Error('No matching version found');
}
return releases.find(release => release.version === versionSelected);
return releases.find((release) => release.version === versionSelected);
}
// Note that the export is defined as adaptor to replace hashicorp/js-releases
// See: https://github.com/hashicorp/setup-terraform/blob/e192cfcbae6c6ed207c277ed7624131996c9bf13/lib/setup-terraform.js#L15
module.exports = {
getRelease,
Release
};
export { getRelease, getDownloadChecksum, parseChecksum, Release };
+178 -74
View File
@@ -5,15 +5,29 @@
*/
// Node.js core
const fs = require('fs').promises;
const os = require('os');
const path = require('path');
import { promises as fs } from 'fs';
import { platform, arch } from 'os';
import { sep, join, resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
// External
const core = require('@actions/core');
const tc = require('@actions/tool-cache');
const io = require('@actions/io');
const releases = require('./releases');
import {
debug,
error as logError,
exportVariable,
getInput,
getMultilineInput,
warning,
addPath
} from '@actions/core';
import { downloadTool, extractZip, find, cacheDir } from '@actions/tool-cache';
import { mv, cp, mkdirP } from '@actions/io';
import { getRelease, getDownloadChecksum } from './releases.js';
import { getErrorMessage } from './error-utils.js';
import { fileSHA256 } from './util.js';
// __dirname is not available in ES modules, so we need to construct it ourselves
const __dirname = dirname(fileURLToPath(import.meta.url));
// arch in [arm, x32, x64...] (https://nodejs.org/api/os.html#os_os_arch)
// return value in [amd64, 386, arm]
@@ -34,9 +48,29 @@ function mapOS (os) {
return os;
}
async function downloadAndExtractCLI (url) {
core.debug(`Downloading OpenTofu CLI from ${url}`);
const pathToCLIZip = await tc.downloadTool(url);
async function downloadAndExtractCLI (url, checksums) {
debug(`Downloading OpenTofu CLI from ${url}`);
let pathToCLIZip;
try {
pathToCLIZip = await downloadTool(url);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to download OpenTofu from ${url}: ${cause}`);
}
if (checksums.length > 0) {
let checksum;
try {
checksum = await fileSHA256(pathToCLIZip);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to calculate the checksum for the OpenTofu CLI zip: ${cause}`);
}
if (!checksums.includes(checksum)) {
throw new Error(`Failed to validate OpenTofu CLI zip checksum. Received: ${checksum}. Valid checksums: ${checksums.join(', ')}`);
}
}
if (!pathToCLIZip) {
throw new Error(`Unable to download OpenTofu from ${url}`);
@@ -44,18 +78,23 @@ async function downloadAndExtractCLI (url) {
let pathToCLI;
core.debug('Extracting OpenTofu CLI zip file');
if (os.platform().startsWith('win')) {
core.debug(`OpenTofu CLI Download Path is ${pathToCLIZip}`);
const fixedPathToCLIZip = `${pathToCLIZip}.zip`;
await io.mv(pathToCLIZip, fixedPathToCLIZip);
core.debug(`Moved download to ${fixedPathToCLIZip}`);
pathToCLI = await tc.extractZip(fixedPathToCLIZip);
} else {
pathToCLI = await tc.extractZip(pathToCLIZip);
debug('Extracting OpenTofu CLI zip file');
try {
if (platform().startsWith('win')) {
debug(`OpenTofu CLI Download Path is ${pathToCLIZip}`);
const fixedPathToCLIZip = `${pathToCLIZip}.zip`;
await mv(pathToCLIZip, fixedPathToCLIZip);
debug(`Moved download to ${fixedPathToCLIZip}`);
pathToCLI = await extractZip(fixedPathToCLIZip);
} else {
pathToCLI = await extractZip(pathToCLIZip);
}
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to extract OpenTofu archive: ${cause}`);
}
core.debug(`OpenTofu CLI path is ${pathToCLI}.`);
debug(`OpenTofu CLI path is ${pathToCLI}.`);
if (!pathToCLI) {
throw new Error('Unable to unzip OpenTofu');
@@ -64,36 +103,74 @@ async function downloadAndExtractCLI (url) {
return pathToCLI;
}
// Resolve the checksums to validate the downloaded archive against. An explicit
// `checksums` input always wins. Otherwise the action falls back to the SHA-256
// checksum published in the release's SHA256SUMS file, so the default install
// path is verified rather than left unchecked. Verification is skipped (with a
// warning) only when no published checksum can be retrieved.
async function resolveChecksums (checksums, version, fileName) {
if (checksums.length > 0) {
return checksums;
}
debug(
`No checksums input provided; fetching published SHA256SUMS for ${fileName}`
);
let publishedChecksum;
try {
publishedChecksum = await getDownloadChecksum(version, fileName);
} catch (error) {
warning(
`Failed to fetch published SHA256SUMS for OpenTofu ${version}: ${getErrorMessage(
error
)}. Proceeding without checksum verification.`
);
return [];
}
if (!publishedChecksum) {
warning(
`Could not find a published SHA256 checksum for ${fileName}. Proceeding without checksum verification.`
);
return [];
}
return [publishedChecksum];
}
async function installWrapper (pathToCLI) {
let source, target;
// If we're on Windows, then the executable ends with .exe
const exeSuffix = os.platform().startsWith('win') ? '.exe' : '';
const exeSuffix = platform().startsWith('win') ? '.exe' : '';
// Rename tofu(.exe) to tofu-bin(.exe)
try {
source = [pathToCLI, `tofu${exeSuffix}`].join(path.sep);
target = [pathToCLI, `tofu-bin${exeSuffix}`].join(path.sep);
core.debug(`Moving ${source} to ${target}.`);
await io.mv(source, target);
source = [pathToCLI, `tofu${exeSuffix}`].join(sep);
target = [pathToCLI, `tofu-bin${exeSuffix}`].join(sep);
debug(`Moving ${source} to ${target}.`);
await mv(source, target);
} catch (e) {
core.error(`Unable to move ${source} to ${target}.`);
logError(`Unable to move ${source} to ${target}.`);
throw e;
}
// Install our wrapper as tofu
try {
source = path.resolve([__dirname, '..', 'wrapper', 'dist', 'index.js'].join(path.sep));
target = [pathToCLI, 'tofu'].join(path.sep);
core.debug(`Copying ${source} to ${target}.`);
await io.cp(source, target);
source = resolve(
[__dirname, '..', 'wrapper', 'dist', 'index.js'].join(sep)
);
target = [pathToCLI, 'tofu'].join(sep);
debug(`Copying ${source} to ${target}.`);
await cp(source, target);
} catch (e) {
core.error(`Unable to copy ${source} to ${target}.`);
logError(`Unable to copy ${source} to ${target}.`);
throw e;
}
// Export a new environment variable, so our wrapper can locate the binary
core.exportVariable('TOFU_CLI_PATH', pathToCLI);
exportVariable('TOFU_CLI_PATH', pathToCLI);
}
// Add credentials to CLI Configuration File
@@ -105,37 +182,45 @@ async function addCredentials (credentialsHostname, credentialsToken, osPlat) {
credentials "${credentialsHostname}" {
token = "${credentialsToken}"
}`.trim();
// eslint-enable
// eslint-enable
// default to OS-specific path
let credsFile = osPlat === 'win32'
? `${process.env.APPDATA}/tofu.rc`
: `${process.env.HOME}/.tofurc`;
let credsFile =
osPlat === 'win32'
? `${process.env.APPDATA}/tofu.rc`
: `${process.env.HOME}/.tofurc`;
// override with TF_CLI_CONFIG_FILE environment variable
credsFile = process.env.TF_CLI_CONFIG_FILE ? process.env.TF_CLI_CONFIG_FILE : credsFile;
credsFile = process.env.TF_CLI_CONFIG_FILE
? process.env.TF_CLI_CONFIG_FILE
: credsFile;
// get containing folder
const credsFolder = path.dirname(credsFile);
const credsFolder = dirname(credsFile);
core.debug(`Creating ${credsFolder}`);
await io.mkdirP(credsFolder);
debug(`Creating ${credsFolder}`);
await mkdirP(credsFolder);
core.debug(`Adding credentials to ${credsFile}`);
debug(`Adding credentials to ${credsFile}`);
await fs.writeFile(credsFile, creds);
}
async function run () {
try {
// Gather GitHub Actions inputs
let version = core.getInput('tofu_version');
const versionFile = core.getInput('tofu_version_file');
const credentialsHostname = core.getInput('cli_config_credentials_hostname');
const credentialsToken = core.getInput('cli_config_credentials_token');
const wrapper = core.getInput('tofu_wrapper') === 'true';
const useCache = core.getInput('cache') === 'true';
let githubToken = core.getInput('github_token');
if (githubToken === '' && !(process.env.FORGEJO_ACTIONS || process.env.GITEA_ACTIONS)) {
let version = getInput('tofu_version');
const versionFile = getInput('tofu_version_file');
const credentialsHostname = getInput('cli_config_credentials_hostname');
const credentialsToken = getInput('cli_config_credentials_token');
const wrapper = getInput('tofu_wrapper') === 'true';
const providerAcceptanceTest = getInput('provider_acceptance_tests') === 'true';
const useCache = getInput('cache') === 'true';
const checksums = getMultilineInput('checksums');
let githubToken = getInput('github_token');
if (
githubToken === '' &&
!(process.env.FORGEJO_ACTIONS || process.env.GITEA_ACTIONS)
) {
// Only default to the environment variable when running in GitHub Actions. Don't do this for other CI systems
// that may set the GITHUB_TOKEN environment variable.
githubToken = process.env.GITHUB_TOKEN;
@@ -144,52 +229,61 @@ async function run () {
// If tofu_version_file is provided, read the version from the file
if (versionFile) {
try {
core.debug(`Reading OpenTofu version from file: ${versionFile}`);
debug(`Reading OpenTofu version from file: ${versionFile}`);
const fileVersion = await fs.readFile(versionFile, 'utf8');
const trimmedVersion = fileVersion.trim();
if (trimmedVersion) {
version = trimmedVersion;
core.debug(`Using version from file: ${version}`);
// .tool-versions (asdf format): use the version from the `opentofu <version>`
// line and ignore other tool entries. Otherwise (e.g. a single-line
// `.opentofu-version` file): use the whole trimmed file content.
// Spec: https://asdf-vm.com/manage/configuration.html#tool-versions
const asdfMatch = fileVersion.match(/^\s*opentofu\s+([^\s#]+)/m);
const parsedVersion = asdfMatch ? asdfMatch[1] : fileVersion.trim();
if (parsedVersion) {
version = parsedVersion;
debug(`Using version from file: ${version}`);
} else {
core.warning(
warning(
`Version file ${versionFile} is empty, using tofu_version input: ${version}`
);
}
} catch (error) {
core.warning(
warning(
`Failed to read version from file ${versionFile}: ${error.message}. Using tofu_version input: ${version}`
);
}
}
// Gather OS details
const osPlatform = os.platform();
const osArch = os.arch();
const osPlatform = platform();
const osArch = arch();
core.debug(`Finding releases for OpenTofu version ${version}`);
const release = await releases.getRelease(version, githubToken);
const platform = mapOS(osPlatform);
const arch = mapArch(osArch);
const build = release.getBuild(platform, arch);
debug(`Finding releases for OpenTofu version ${version}`);
const release = await getRelease(version, githubToken);
const buildPlatform = mapOS(osPlatform);
const buildArch = mapArch(osArch);
const build = release.getBuild(buildPlatform, buildArch);
if (!build) {
throw new Error(`OpenTofu version ${version} not available for ${platform} and ${arch}`);
throw new Error(
`OpenTofu version ${version} not available for ${buildPlatform} and ${buildArch}`
);
}
// Download requested version if not cached
let pathToCLI;
if (useCache) {
const cachedPath = tc.find('tofu', release.version, arch);
const cachedPath = find('tofu', release.version, buildArch);
if (cachedPath) {
core.debug(`Using cached OpenTofu version ${release.version} from ${cachedPath}`);
debug(`Using cached OpenTofu version ${release.version} from ${cachedPath}`);
pathToCLI = cachedPath;
} else {
core.debug(`OpenTofu version ${release.version} not found in cache, downloading...`);
const extractedPath = await downloadAndExtractCLI(build.url);
core.debug(`Caching OpenTofu version ${release.version} to tool cache`);
pathToCLI = await tc.cacheDir(extractedPath, 'tofu', release.version, arch);
debug(`OpenTofu version ${release.version} not found in cache, downloading...`);
const effectiveChecksums = await resolveChecksums(checksums, release.version, build.name);
const extractedPath = await downloadAndExtractCLI(build.url, effectiveChecksums);
debug(`Caching OpenTofu version ${release.version} to tool cache`);
pathToCLI = await cacheDir(extractedPath, 'tofu', release.version, buildArch);
}
} else {
pathToCLI = await downloadAndExtractCLI(build.url);
const effectiveChecksums = await resolveChecksums(checksums, release.version, build.name);
pathToCLI = await downloadAndExtractCLI(build.url, effectiveChecksums);
}
// Install our wrapper
@@ -198,7 +292,17 @@ async function run () {
}
// Add to path
core.addPath(pathToCLI);
addPath(pathToCLI);
// Set up provider acceptance test environment variables
if (providerAcceptanceTest) {
const exeSuffix = platform().startsWith('win') ? '.exe' : '';
const binaryName = wrapper ? `tofu-bin${exeSuffix}` : `tofu${exeSuffix}`;
exportVariable('TF_ACC', '1');
exportVariable('TF_ACC_PROVIDER_NAMESPACE', 'hashicorp');
exportVariable('TF_ACC_PROVIDER_HOST', 'registry.opentofu.org');
exportVariable('TF_ACC_TERRAFORM_PATH', join(pathToCLI, binaryName));
}
// Add credentials to file if they are provided
if (credentialsHostname && credentialsToken) {
@@ -206,9 +310,9 @@ async function run () {
}
return release;
} catch (error) {
core.error(error);
logError(getErrorMessage(error));
throw error;
}
}
module.exports = run;
export default run;
+62
View File
@@ -0,0 +1,62 @@
/**
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { getErrorMessage, getErrorDetail } from '../error-utils.js';
describe('error-utils', () => {
describe('getErrorMessage', () => {
it('returns message for standard Error', () => {
expect(getErrorMessage(new Error('Something failed'))).toBe('Something failed');
});
it('includes cause for Error with cause (Node 16+)', () => {
const cause = new Error('Network timeout');
const err = new Error('Download failed');
err.cause = cause;
expect(getErrorMessage(err)).toBe('Download failed: Network timeout');
});
it('flattens AggregateError into a single message', () => {
const err = new AggregateError(
[new Error('ECONNREFUSED'), new Error('getaddrinfo ENOTFOUND')],
'AggregateError'
);
const msg = getErrorMessage(err);
expect(msg).toContain('ECONNREFUSED');
expect(msg).toContain('getaddrinfo ENOTFOUND');
expect(msg).not.toBe('AggregateError');
});
it('returns fallback for AggregateError with empty errors', () => {
const err = new AggregateError([], 'AggregateError');
expect(getErrorMessage(err)).toBe('AggregateError (one or more operations failed)');
});
it('coerces non-Error to string', () => {
expect(getErrorMessage('oops')).toBe('oops');
expect(getErrorMessage(123)).toBe('123');
});
});
describe('getErrorDetail', () => {
it('includes stack for Error', () => {
const err = new Error('test');
const detail = getErrorDetail(err);
expect(detail).toContain('test');
expect(detail).toContain('Error');
});
it('includes each nested error for AggregateError', () => {
const err = new AggregateError(
[new Error('A'), new Error('B')],
'AggregateError'
);
const detail = getErrorDetail(err);
expect(detail).toContain('A');
expect(detail).toContain('B');
expect(detail).toContain('2 error(s)');
});
});
});
+250 -159
View File
@@ -1,175 +1,266 @@
const pkg = require('../releases');
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { Release, getRelease, getDownloadChecksum, parseChecksum } from '../releases.js';
describe('getRelease', () => {
function mockFetchReleases () {
const mockReleasesMeta = [{
id: 'v1.7.0-alpha2',
files: [
'tofu_1.7.0-alpha2_386.apk',
'tofu_1.7.0-alpha2_386.deb',
'tofu_1.7.0-alpha2_386.rpm',
'tofu_1.7.0-alpha2_amd64.apk',
'tofu_1.7.0-alpha2_amd64.deb',
'tofu_1.7.0-alpha2_amd64.rpm',
'tofu_1.7.0-alpha2_arm.apk',
'tofu_1.7.0-alpha2_arm.deb',
'tofu_1.7.0-alpha2_arm.rpm',
'tofu_1.7.0-alpha2_arm64.apk',
'tofu_1.7.0-alpha2_arm64.deb',
'tofu_1.7.0-alpha2_arm64.rpm',
'tofu_1.7.0-alpha2_darwin_arm64.zip',
'tofu_1.7.0-alpha2_freebsd_386.zip',
'tofu_1.7.0-alpha2_freebsd_amd64.zip',
'tofu_1.7.0-alpha2_freebsd_arm.zip',
'tofu_1.7.0-alpha2_linux_386.zip',
'tofu_1.7.0-alpha2_linux_amd64.zip',
'tofu_1.7.0-alpha2_linux_arm.zip',
'tofu_1.7.0-alpha2_linux_arm64.zip',
'tofu_1.7.0-alpha2_openbsd_386.zip',
'tofu_1.7.0-alpha2_openbsd_amd64.zip',
'tofu_1.7.0-alpha2_SHA256SUMS',
'tofu_1.7.0-alpha2_SHA256SUMS.pem',
'tofu_1.7.0-alpha2_SHA256SUMS.sig',
'tofu_1.7.0-alpha2_solaris_amd64.zip',
'tofu_1.7.0-alpha2_windows_386.zip',
'tofu_1.7.0-alpha2_windows_amd64.zip'
]
}, {
id: 'v1.6.0',
files: [
'tofu_1.6.0_386.apk',
'tofu_1.6.0_386.deb',
'tofu_1.6.0_386.rpm',
'tofu_1.6.0_amd64.apk',
'tofu_1.6.0_amd64.deb',
'tofu_1.6.0_amd64.rpm',
'tofu_1.6.0_arm.apk',
'tofu_1.6.0_arm.deb',
'tofu_1.6.0_arm.rpm',
'tofu_1.6.0_arm64.apk',
'tofu_1.6.0_arm64.deb',
'tofu_1.6.0_arm64.rpm',
'tofu_1.6.0_darwin_arm64.zip',
'tofu_1.6.0_freebsd_386.zip',
'tofu_1.6.0_freebsd_amd64.zip',
'tofu_1.6.0_freebsd_arm.zip',
'tofu_1.6.0_linux_386.zip',
'tofu_1.6.0_linux_amd64.zip',
'tofu_1.6.0_linux_arm.zip',
'tofu_1.6.0_linux_arm64.zip',
'tofu_1.6.0_openbsd_386.zip',
'tofu_1.6.0_openbsd_amd64.zip',
'tofu_1.6.0_SHA256SUMS',
'tofu_1.6.0_SHA256SUMS.pem',
'tofu_1.6.0_SHA256SUMS.sig',
'tofu_1.6.0_solaris_amd64.zip',
'tofu_1.6.0_windows_386.zip',
'tofu_1.6.0_windows_amd64.zip']
}, {
id: 'v1.6.0-alpha2',
files: [
'tofu_1.6.0-alpha2_386.apk',
'tofu_1.6.0-alpha2_386.deb',
'tofu_1.6.0-alpha2_386.rpm',
'tofu_1.6.0-alpha2_amd64.apk',
'tofu_1.6.0-alpha2_amd64.deb',
'tofu_1.6.0-alpha2_amd64.rpm',
'tofu_1.6.0-alpha2_arm.apk',
'tofu_1.6.0-alpha2_arm.deb',
'tofu_1.6.0-alpha2_arm.rpm',
'tofu_1.6.0-alpha2_arm64.apk',
'tofu_1.6.0-alpha2_arm64.deb',
'tofu_1.6.0-alpha2_arm64.rpm',
'tofu_1.6.0-alpha2_darwin_arm64.zip',
'tofu_1.6.0-alpha2_freebsd_386.zip',
'tofu_1.6.0-alpha2_freebsd_amd64.zip',
'tofu_1.6.0-alpha2_freebsd_arm.zip',
'tofu_1.6.0-alpha2_linux_386.zip',
'tofu_1.6.0-alpha2_linux_amd64.zip',
'tofu_1.6.0-alpha2_linux_arm.zip',
'tofu_1.6.0-alpha2_linux_arm64.zip',
'tofu_1.6.0-alpha2_openbsd_386.zip',
'tofu_1.6.0-alpha2_openbsd_amd64.zip',
'tofu_1.6.0-alpha2_SHA256SUMS',
'tofu_1.6.0-alpha2_SHA256SUMS.pem',
'tofu_1.6.0-alpha2_SHA256SUMS.sig',
'tofu_1.6.0-alpha2_solaris_amd64.zip',
'tofu_1.6.0-alpha2_windows_386.zip',
'tofu_1.6.0-alpha2_windows_amd64.zip'
]
}, {
id: 'v1.6.0-alpha1',
files: [
'tofu_1.6.0-alpha1_386.apk',
'tofu_1.6.0-alpha1_386.deb',
'tofu_1.6.0-alpha1_386.rpm',
'tofu_1.6.0-alpha1_amd64.apk',
'tofu_1.6.0-alpha1_amd64.deb',
'tofu_1.6.0-alpha1_amd64.rpm',
'tofu_1.6.0-alpha1_arm.apk',
'tofu_1.6.0-alpha1_arm.deb',
'tofu_1.6.0-alpha1_arm.rpm',
'tofu_1.6.0-alpha1_arm64.apk',
'tofu_1.6.0-alpha1_arm64.deb',
'tofu_1.6.0-alpha1_arm64.rpm',
'tofu_1.6.0-alpha1_darwin_amd64.zip',
'tofu_1.6.0-alpha1_darwin_arm64.zip',
'tofu_1.6.0-alpha1_freebsd_386.zip',
'tofu_1.6.0-alpha1_freebsd_amd64.zip',
'tofu_1.6.0-alpha1_freebsd_arm.zip',
'tofu_1.6.0-alpha1_linux_386.zip',
'tofu_1.6.0-alpha1_linux_amd64.zip',
'tofu_1.6.0-alpha1_linux_arm.zip',
'tofu_1.6.0-alpha1_linux_arm64.zip',
'tofu_1.6.0-alpha1_openbsd_386.zip',
'tofu_1.6.0-alpha1_openbsd_amd64.zip',
'tofu_1.6.0-alpha1_SHA256SUMS',
'tofu_1.6.0-alpha1_SHA256SUMS.pem',
'tofu_1.6.0-alpha1_SHA256SUMS.sig',
'tofu_1.6.0-alpha1_solaris_amd64.zip',
'tofu_1.6.0-alpha1_windows_386.zip',
'tofu_1.6.0-alpha1_windows_amd64.zip'
]
}];
const mockReleasesMeta = [
{
id: 'v1.7.0-alpha2',
files: [
'tofu_1.7.0-alpha2_386.apk',
'tofu_1.7.0-alpha2_386.deb',
'tofu_1.7.0-alpha2_386.rpm',
'tofu_1.7.0-alpha2_amd64.apk',
'tofu_1.7.0-alpha2_amd64.deb',
'tofu_1.7.0-alpha2_amd64.rpm',
'tofu_1.7.0-alpha2_arm.apk',
'tofu_1.7.0-alpha2_arm.deb',
'tofu_1.7.0-alpha2_arm.rpm',
'tofu_1.7.0-alpha2_arm64.apk',
'tofu_1.7.0-alpha2_arm64.deb',
'tofu_1.7.0-alpha2_arm64.rpm',
'tofu_1.7.0-alpha2_darwin_arm64.zip',
'tofu_1.7.0-alpha2_freebsd_386.zip',
'tofu_1.7.0-alpha2_freebsd_amd64.zip',
'tofu_1.7.0-alpha2_freebsd_arm.zip',
'tofu_1.7.0-alpha2_linux_386.zip',
'tofu_1.7.0-alpha2_linux_amd64.zip',
'tofu_1.7.0-alpha2_linux_arm.zip',
'tofu_1.7.0-alpha2_linux_arm64.zip',
'tofu_1.7.0-alpha2_openbsd_386.zip',
'tofu_1.7.0-alpha2_openbsd_amd64.zip',
'tofu_1.7.0-alpha2_SHA256SUMS',
'tofu_1.7.0-alpha2_SHA256SUMS.pem',
'tofu_1.7.0-alpha2_SHA256SUMS.sig',
'tofu_1.7.0-alpha2_solaris_amd64.zip',
'tofu_1.7.0-alpha2_windows_386.zip',
'tofu_1.7.0-alpha2_windows_amd64.zip'
]
},
{
id: 'v1.6.0',
files: [
'tofu_1.6.0_386.apk',
'tofu_1.6.0_386.deb',
'tofu_1.6.0_386.rpm',
'tofu_1.6.0_amd64.apk',
'tofu_1.6.0_amd64.deb',
'tofu_1.6.0_amd64.rpm',
'tofu_1.6.0_arm.apk',
'tofu_1.6.0_arm.deb',
'tofu_1.6.0_arm.rpm',
'tofu_1.6.0_arm64.apk',
'tofu_1.6.0_arm64.deb',
'tofu_1.6.0_arm64.rpm',
'tofu_1.6.0_darwin_arm64.zip',
'tofu_1.6.0_freebsd_386.zip',
'tofu_1.6.0_freebsd_amd64.zip',
'tofu_1.6.0_freebsd_arm.zip',
'tofu_1.6.0_linux_386.zip',
'tofu_1.6.0_linux_amd64.zip',
'tofu_1.6.0_linux_arm.zip',
'tofu_1.6.0_linux_arm64.zip',
'tofu_1.6.0_openbsd_386.zip',
'tofu_1.6.0_openbsd_amd64.zip',
'tofu_1.6.0_SHA256SUMS',
'tofu_1.6.0_SHA256SUMS.pem',
'tofu_1.6.0_SHA256SUMS.sig',
'tofu_1.6.0_solaris_amd64.zip',
'tofu_1.6.0_windows_386.zip',
'tofu_1.6.0_windows_amd64.zip'
]
},
{
id: 'v1.6.0-alpha2',
files: [
'tofu_1.6.0-alpha2_386.apk',
'tofu_1.6.0-alpha2_386.deb',
'tofu_1.6.0-alpha2_386.rpm',
'tofu_1.6.0-alpha2_amd64.apk',
'tofu_1.6.0-alpha2_amd64.deb',
'tofu_1.6.0-alpha2_amd64.rpm',
'tofu_1.6.0-alpha2_arm.apk',
'tofu_1.6.0-alpha2_arm.deb',
'tofu_1.6.0-alpha2_arm.rpm',
'tofu_1.6.0-alpha2_arm64.apk',
'tofu_1.6.0-alpha2_arm64.deb',
'tofu_1.6.0-alpha2_arm64.rpm',
'tofu_1.6.0-alpha2_darwin_arm64.zip',
'tofu_1.6.0-alpha2_freebsd_386.zip',
'tofu_1.6.0-alpha2_freebsd_amd64.zip',
'tofu_1.6.0-alpha2_freebsd_arm.zip',
'tofu_1.6.0-alpha2_linux_386.zip',
'tofu_1.6.0-alpha2_linux_amd64.zip',
'tofu_1.6.0-alpha2_linux_arm.zip',
'tofu_1.6.0-alpha2_linux_arm64.zip',
'tofu_1.6.0-alpha2_openbsd_386.zip',
'tofu_1.6.0-alpha2_openbsd_amd64.zip',
'tofu_1.6.0-alpha2_SHA256SUMS',
'tofu_1.6.0-alpha2_SHA256SUMS.pem',
'tofu_1.6.0-alpha2_SHA256SUMS.sig',
'tofu_1.6.0-alpha2_solaris_amd64.zip',
'tofu_1.6.0-alpha2_windows_386.zip',
'tofu_1.6.0-alpha2_windows_amd64.zip'
]
},
{
id: 'v1.6.0-alpha1',
files: [
'tofu_1.6.0-alpha1_386.apk',
'tofu_1.6.0-alpha1_386.deb',
'tofu_1.6.0-alpha1_386.rpm',
'tofu_1.6.0-alpha1_amd64.apk',
'tofu_1.6.0-alpha1_amd64.deb',
'tofu_1.6.0-alpha1_amd64.rpm',
'tofu_1.6.0-alpha1_arm.apk',
'tofu_1.6.0-alpha1_arm.deb',
'tofu_1.6.0-alpha1_arm.rpm',
'tofu_1.6.0-alpha1_arm64.apk',
'tofu_1.6.0-alpha1_arm64.deb',
'tofu_1.6.0-alpha1_arm64.rpm',
'tofu_1.6.0-alpha1_darwin_amd64.zip',
'tofu_1.6.0-alpha1_darwin_arm64.zip',
'tofu_1.6.0-alpha1_freebsd_386.zip',
'tofu_1.6.0-alpha1_freebsd_amd64.zip',
'tofu_1.6.0-alpha1_freebsd_arm.zip',
'tofu_1.6.0-alpha1_linux_386.zip',
'tofu_1.6.0-alpha1_linux_amd64.zip',
'tofu_1.6.0-alpha1_linux_arm.zip',
'tofu_1.6.0-alpha1_linux_arm64.zip',
'tofu_1.6.0-alpha1_openbsd_386.zip',
'tofu_1.6.0-alpha1_openbsd_amd64.zip',
'tofu_1.6.0-alpha1_SHA256SUMS',
'tofu_1.6.0-alpha1_SHA256SUMS.pem',
'tofu_1.6.0-alpha1_SHA256SUMS.sig',
'tofu_1.6.0-alpha1_solaris_amd64.zip',
'tofu_1.6.0-alpha1_windows_386.zip',
'tofu_1.6.0-alpha1_windows_amd64.zip'
]
}
];
return mockReleasesMeta.map(el => new pkg.Release(el));
return mockReleasesMeta.map((el) => new Release(el));
}
it.each(
[
['latest', '1.6.0'],
['<1.6.0-beta', '1.6.0-alpha2'],
['>1.6.0-alpha1', '1.6.0'],
['>1.6.0-alpha1 <1.6.0', '1.6.0-alpha2'],
['~1.6.0-alpha', '1.6.0'],
['<=1.6.0-alpha1', '1.6.0-alpha1'],
['>1.5.0', '1.6.0'],
['>1.5.0', '1.6.0'],
['>1.7.0-alpha', '1.7.0-alpha2']
]
)('happy path: getRelease(\'%s\') -> \'%s\'', async (input, wantVersion) => {
const want = mockFetchReleases().find(el => el.version === wantVersion);
const gotRelease = await pkg.getRelease(input, '', mockFetchReleases);
it.each([
['latest', '1.6.0'],
['<1.6.0-beta', '1.6.0-alpha2'],
['>1.6.0-alpha1', '1.6.0'],
['>1.6.0-alpha1 <1.6.0', '1.6.0-alpha2'],
['~1.6.0-alpha', '1.6.0'],
['<=1.6.0-alpha1', '1.6.0-alpha1'],
['>1.5.0', '1.6.0'],
['>1.5.0', '1.6.0'],
['>1.7.0-alpha', '1.7.0-alpha2']
])("happy path: getRelease('%s') -> '%s'", async (input, wantVersion) => {
const want = mockFetchReleases().find((el) => el.version === wantVersion);
const gotRelease = await getRelease(input, '', mockFetchReleases);
expect(gotRelease).toEqual(want);
});
it.each(
it.each([
[
['foo', 'Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html', mockFetchReleases],
['2.0', 'No matching version found', mockFetchReleases],
['latest', 'No tofu releases found, please contact OpenTofu', async () => {
'foo',
'Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html',
mockFetchReleases
],
['2.0', 'No matching version found', mockFetchReleases],
[
'latest',
'No tofu releases found, please contact OpenTofu',
async () => {
return null;
}],
['latest', 'No tofu releases found, please contact OpenTofu', async () => {
}
],
[
'latest',
'No tofu releases found, please contact OpenTofu',
async () => {
return [];
}]
}
]
)('unhappy path: getRelease(\'%s\') -> throw Error(\'%s\')', async (input, wantErrorMessage, mockFetchReleasesFn) => {
try {
await pkg.getRelease(input, '', mockFetchReleasesFn);
expect(true).toBe(false);
} catch (e) {
expect(e.message).toBe(wantErrorMessage);
])(
"unhappy path: getRelease('%s') -> throw Error('%s')",
async (input, wantErrorMessage, mockFetchReleasesFn) => {
try {
await getRelease(input, '', mockFetchReleasesFn);
expect(true).toBe(false);
} catch (e) {
expect(e.message).toBe(wantErrorMessage);
}
}
);
});
describe('parseChecksum', () => {
const sums = [
'933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad tofu_1.6.0_linux_amd64.zip',
'd3d29f51e75a701fc7cf67c0644a8c883a85f36cf1621461988baffd88e7f361 tofu_1.6.0_darwin_arm64.zip'
].join('\n') + '\n';
it('returns the lowercase checksum for a matching file name', () => {
expect(parseChecksum(sums, 'tofu_1.6.0_darwin_arm64.zip')).toBe(
'd3d29f51e75a701fc7cf67c0644a8c883a85f36cf1621461988baffd88e7f361'
);
});
it('returns null when the file name is not listed', () => {
expect(parseChecksum(sums, 'tofu_1.6.0_windows_amd64.zip')).toBeNull();
});
it('ignores blank lines and binary-mode "*" prefixes', () => {
const body = '\nABCDEF0123456789 *tofu_1.6.0_linux_arm64.zip\n\n';
expect(parseChecksum(body, 'tofu_1.6.0_linux_arm64.zip')).toBe(
'abcdef0123456789'
);
});
it('returns null for an empty body', () => {
expect(parseChecksum('', 'tofu_1.6.0_linux_amd64.zip')).toBeNull();
});
});
describe('getDownloadChecksum', () => {
it('fetches the SHA256SUMS and returns the matching checksum', async () => {
const fetchSumsFn = async (version) => {
expect(version).toBe('1.6.0');
return '933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad tofu_1.6.0_linux_amd64.zip\n';
};
const got = await getDownloadChecksum(
'1.6.0',
'tofu_1.6.0_linux_amd64.zip',
fetchSumsFn
);
expect(got).toBe(
'933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad'
);
});
it('returns null when the asset is absent from the SHA256SUMS', async () => {
const fetchSumsFn = async () =>
'933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad tofu_1.6.0_linux_amd64.zip\n';
const got = await getDownloadChecksum(
'1.6.0',
'tofu_1.6.0_windows_amd64.zip',
fetchSumsFn
);
expect(got).toBeNull();
});
it('propagates fetch errors', async () => {
const fetchSumsFn = async () => {
throw new Error('boom');
};
await expect(
getDownloadChecksum('1.6.0', 'tofu_1.6.0_linux_amd64.zip', fetchSumsFn)
).rejects.toThrow('boom');
});
});
+274 -44
View File
@@ -1,31 +1,59 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { jest } from '@jest/globals';
// Node.js core
const fs = require('fs').promises;
const os = require('os');
const path = require('path');
import { promises as fs } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
// External
const core = require('@actions/core');
// Set up mocks BEFORE dynamic imports
jest.unstable_mockModule('@actions/core', () => ({
getInput: jest.fn(),
getMultilineInput: jest.fn(),
setOutput: jest.fn(),
setFailed: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
warning: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn()
}));
// First party
const releases = require('../releases');
const setup = require('../setup-tofu');
// Mock dependencies
jest.mock('@actions/core');
jest.mock('@actions/io', () => ({
jest.unstable_mockModule('@actions/io', () => ({
mv: jest.fn(),
cp: jest.fn(),
mkdirP: jest.fn()
}));
jest.mock('@actions/tool-cache', () => ({
jest.unstable_mockModule('@actions/tool-cache', () => ({
downloadTool: jest.fn(),
extractZip: jest.fn(),
find: jest.fn(),
cacheDir: jest.fn()
}));
// Mock releases.js so setup-tofu.js can be tested in isolation
jest.mock('../releases');
jest.unstable_mockModule('../releases.js', () => ({
getRelease: jest.fn(),
getDownloadChecksum: jest.fn(),
Release: jest.fn()
}));
jest.unstable_mockModule('../util.js', () => ({
fileSHA256: jest.fn()
}));
// Dynamic imports pick up the mocks
const { getInput, warning, exportVariable, getMultilineInput } = await import('@actions/core');
const tc = await import('@actions/tool-cache');
const io = await import('@actions/io');
const { getRelease, getDownloadChecksum } = await import('../releases.js');
const { default: setup } = await import('../setup-tofu.js');
const { fileSHA256 } = await import('../util.js');
// Set up global test fixtures
const fallbackVersion = 'latest';
@@ -38,43 +66,56 @@ let versionFileName = '.opentofu-version';
describe('setup-tofu', () => {
beforeAll(async () => {
// Mock dependencies
const tc = require('@actions/tool-cache');
tc.downloadTool.mockResolvedValue('/mock/download/path');
tc.extractZip.mockResolvedValue('/mock/extract/path');
tc.find.mockReturnValue(null); // Default to cache miss
tc.cacheDir.mockResolvedValue('/mock/cached/path');
const io = require('@actions/io');
io.mv.mockResolvedValue();
io.cp.mockResolvedValue();
io.mkdirP.mockResolvedValue();
const mockRelease = {
version: '1.10.5',
getBuild: jest.fn().mockReturnValue({ url: 'mock-url' })
getBuild: jest.fn().mockReturnValue({
url: 'mock-url',
name: 'tofu_1.10.5_linux_amd64.zip'
})
};
releases.getRelease.mockResolvedValue(mockRelease);
getRelease.mockResolvedValue(mockRelease);
// Default to "no published checksum retrievable" so tests that don't
// exercise checksum behaviour keep skipping verification, as before.
getDownloadChecksum.mockResolvedValue(null);
// Write version file to temporary directory
tempDirPath = path.join(os.tmpdir(), 'setup-tofu-');
tempDirPath = join(tmpdir(), 'setup-tofu-');
tempDir = await fs.mkdtemp(tempDirPath);
versionFile = path.join(tempDir, versionFileName);
versionFile = join(tempDir, versionFileName);
await fs.writeFile(versionFile, `${version}\n`);
// Mock action inputs to return default values
core.getInput.mockImplementation((name) => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: versionFile,
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
provider_acceptance_tests: 'false',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: []
};
return defaults[name] || [];
});
// Mock environment variables
process.env.GITHUB_TOKEN = 'mock-github-token';
});
@@ -93,8 +134,9 @@ describe('setup-tofu', () => {
await setup();
expect(releases.getRelease).toHaveBeenCalledWith(
version, process.env.GITHUB_TOKEN
expect(getRelease).toHaveBeenCalledWith(
version,
process.env.GITHUB_TOKEN
);
expect(fs.readFile).toHaveBeenCalled();
@@ -105,10 +147,10 @@ describe('setup-tofu', () => {
version = ' ';
versionFileName = '.opentofu-version-empty';
versionFile = path.join(tempDir, versionFileName);
versionFile = join(tempDir, versionFileName);
await fs.writeFile(versionFile, `${version}\n`);
core.getInput.mockImplementation((name) => {
getInput.mockImplementation((name) => {
if (name === 'tofu_version_file') {
return versionFile;
}
@@ -120,11 +162,12 @@ describe('setup-tofu', () => {
await setup();
expect(releases.getRelease).toHaveBeenCalledWith(
fallbackVersion, process.env.GITHUB_TOKEN
expect(getRelease).toHaveBeenCalledWith(
fallbackVersion,
process.env.GITHUB_TOKEN
);
expect(core.warning).toHaveBeenCalledWith(
expect(warning).toHaveBeenCalledWith(
expect.stringContaining(`Version file ${versionFile} is empty`)
);
@@ -135,9 +178,9 @@ describe('setup-tofu', () => {
jest.spyOn(fs, 'readFile');
versionFileName = '.opentofu-version-file-does-not-exist';
versionFile = path.join(tempDir, versionFileName);
versionFile = join(tempDir, versionFileName);
core.getInput.mockImplementation((name) => {
getInput.mockImplementation((name) => {
if (name === 'tofu_version_file') {
return versionFile;
}
@@ -149,12 +192,15 @@ describe('setup-tofu', () => {
await setup();
expect(releases.getRelease).toHaveBeenCalledWith(
fallbackVersion, process.env.GITHUB_TOKEN
expect(getRelease).toHaveBeenCalledWith(
fallbackVersion,
process.env.GITHUB_TOKEN
);
expect(core.warning).toHaveBeenCalledWith(
expect.stringContaining(`Failed to read version from file ${versionFile}`)
expect(warning).toHaveBeenCalledWith(
expect.stringContaining(
`Failed to read version from file ${versionFile}`
)
);
expect(fs.readFile).toHaveBeenCalled();
@@ -163,7 +209,7 @@ describe('setup-tofu', () => {
it('should not read file when tofu_version_file is not provided', async () => {
jest.spyOn(fs, 'readFile');
core.getInput.mockImplementation((name) => {
getInput.mockImplementation((name) => {
if (name === 'tofu_version') {
return fallbackVersion;
}
@@ -172,20 +218,48 @@ describe('setup-tofu', () => {
await setup();
expect(releases.getRelease).toHaveBeenCalledWith(
fallbackVersion, process.env.GITHUB_TOKEN
expect(getRelease).toHaveBeenCalledWith(
fallbackVersion,
process.env.GITHUB_TOKEN
);
expect(fs.readFile).not.toHaveBeenCalled();
});
it('should parse the opentofu version from a .tool-versions (asdf) file', async () => {
jest.spyOn(fs, 'readFile');
const asdfVersion = '1.9.0';
versionFileName = '.tool-versions';
versionFile = join(tempDir, versionFileName);
await fs.writeFile(versionFile, `nodejs 24.14.0\nopentofu ${asdfVersion}\nterraform 1.5.0\n`);
getInput.mockImplementation((name) => {
if (name === 'tofu_version_file') {
return versionFile;
}
if (name === 'tofu_version') {
return fallbackVersion;
}
return '';
});
await setup();
expect(getRelease).toHaveBeenCalledWith(
asdfVersion,
process.env.GITHUB_TOKEN
);
expect(fs.readFile).toHaveBeenCalled();
});
});
describe('caching functionality', () => {
it('should use cached version when cache is enabled and found', async () => {
const tc = require('@actions/tool-cache');
tc.find.mockReturnValue('/mock/cached/path');
core.getInput.mockImplementation((name) => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
@@ -207,10 +281,9 @@ describe('setup-tofu', () => {
});
it('should download and cache when cache is enabled but not found', async () => {
const tc = require('@actions/tool-cache');
tc.find.mockReturnValue(null); // Cache miss
core.getInput.mockImplementation((name) => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
@@ -232,16 +305,16 @@ describe('setup-tofu', () => {
});
it('should not use cache when cache is disabled', async () => {
const tc = require('@actions/tool-cache');
tc.find.mockReturnValue('/mock/cached/path');
core.getInput.mockImplementation((name) => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
provider_acceptance_tests: 'false',
cache: 'false',
github_token: ''
};
@@ -256,4 +329,161 @@ describe('setup-tofu', () => {
expect(tc.cacheDir).not.toHaveBeenCalled();
});
});
describe('provider_acceptance_tests functionality', () => {
it('should export acceptance test env vars when enabled without wrapper', async () => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'false',
provider_acceptance_tests: 'true',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(exportVariable).toHaveBeenCalledWith('TF_ACC', '1');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_NAMESPACE', 'hashicorp');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_HOST', 'registry.opentofu.org');
expect(exportVariable).toHaveBeenCalledWith(
'TF_ACC_TERRAFORM_PATH',
expect.stringContaining('tofu')
);
expect(exportVariable).not.toHaveBeenCalledWith(
'TF_ACC_TERRAFORM_PATH',
expect.stringContaining('tofu-bin')
);
});
it('should point TF_ACC_TERRAFORM_PATH to tofu-bin when wrapper is enabled', async () => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
provider_acceptance_tests: 'true',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(exportVariable).toHaveBeenCalledWith('TF_ACC', '1');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_NAMESPACE', 'hashicorp');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_HOST', 'registry.opentofu.org');
expect(exportVariable).toHaveBeenCalledWith(
'TF_ACC_TERRAFORM_PATH',
expect.stringContaining('tofu-bin')
);
});
it('should not export acceptance test env vars when disabled', async () => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'false',
provider_acceptance_tests: 'false',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC', expect.anything());
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC_PROVIDER_NAMESPACE', expect.anything());
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC_PROVIDER_HOST', expect.anything());
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC_TERRAFORM_PATH', expect.anything());
});
});
describe('checksum validation', () => {
const mockChecksum = 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6';
const mockChecksum2 = 'fcfac0a865b57e0711cb8bae47c8fc70ad93198fa6146a40020ea459715fda83';
const mockInvalidChecksum = 'invalidchecksuminvalidchecksuminvalidchecksuminvalidchecksum';
fileSHA256.mockResolvedValue(mockChecksum);
it('should validate checksum when checksums are provided', async () => {
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: [mockInvalidChecksum, mockChecksum]
};
return defaults[name] ?? [];
});
await setup();
expect(fileSHA256).toHaveBeenCalled();
// An explicit checksums input wins; the published SHA256SUMS is not fetched.
expect(getDownloadChecksum).not.toHaveBeenCalled();
});
it('should validate against the published SHA256SUMS when no checksums input is provided', async () => {
fileSHA256.mockResolvedValue(mockChecksum);
getDownloadChecksum.mockResolvedValue(mockChecksum);
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: []
};
return defaults[name] ?? [];
});
await setup();
expect(getDownloadChecksum).toHaveBeenCalledWith(
'1.10.5',
'tofu_1.10.5_linux_amd64.zip'
);
expect(fileSHA256).toHaveBeenCalled();
});
it('should skip verification when no published checksum can be retrieved', async () => {
getDownloadChecksum.mockResolvedValue(null);
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: []
};
return defaults[name] ?? [];
});
await setup();
expect(getDownloadChecksum).toHaveBeenCalled();
expect(fileSHA256).not.toHaveBeenCalled();
expect(warning).toHaveBeenCalledWith(
expect.stringContaining('Proceeding without checksum verification')
);
});
it('should throw error when checksum validation fails', async () => {
fileSHA256.mockResolvedValue(mockInvalidChecksum);
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: [mockChecksum, mockChecksum2]
};
return defaults[name] ?? [];
});
await expect(setup()).rejects.toMatchObject(new Error(
`Failed to validate OpenTofu CLI zip checksum. Received: ${mockInvalidChecksum}. Valid checksums: ${mockChecksum}, ${mockChecksum2}`));
expect(fileSHA256).toHaveBeenCalled();
});
});
});
+16
View File
@@ -0,0 +1,16 @@
/**
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { createHash } from 'crypto';
import { createReadStream } from 'fs';
import { pipeline } from 'stream/promises';
export async function fileSHA256 (filePath) {
const hash = createHash('sha256');
const fileStream = createReadStream(filePath);
await pipeline(fileStream, hash);
return hash.digest('hex');
}
+7611 -7191
View File
File diff suppressed because it is too large. Load diff
+39 -37
View File
@@ -1,39 +1,41 @@
{
"name": "setup-opentofu",
"version": "1.0.1",
"description": "Setup OpenTofu CLI for GitHub Actions",
"license": "MPL-2.0",
"publisher": "OpenTofu",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/opentofu/setup-opentofu.git"
},
"scripts": {
"test": "semistandard --env jest && jest --coverage",
"lint": "semistandard --env jest --fix",
"build": "ncc build wrapper/tofu.js --out wrapper/dist && ncc build index.js --out dist",
"prepare": "husky install",
"format-check": "echo \"unimplemented for actions/reusable-workflows basic-validation\""
},
"keywords": [],
"author": "",
"dependencies": {
"@actions/core": "2.0.2",
"@actions/exec": "2.0.0",
"@actions/io": "2.0.0",
"@actions/tool-cache": "2.0.2",
"semver": "7.7.3"
},
"devDependencies": {
"@vercel/ncc": "0.38.4",
"husky": "9.1.7",
"jest": "30.2.0",
"semistandard": "17.0.0"
},
"semistandard": {
"ignore": [
"**/dist/**"
]
}
"name": "setup-opentofu",
"version": "2.0.2",
"description": "Setup OpenTofu CLI for GitHub Actions",
"type": "module",
"license": "MPL-2.0",
"publisher": "OpenTofu",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/opentofu/setup-opentofu.git"
},
"scripts": {
"test": "semistandard --env jest && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --coverage",
"lint": "semistandard --env jest --fix",
"build": "ncc build wrapper/tofu.js --out wrapper/dist && ncc build index.js --out dist",
"prepare": "husky install",
"format-check": "echo \"unimplemented for actions/reusable-workflows basic-validation\""
},
"keywords": [],
"author": "",
"dependencies": {
"@actions/core": "^3.0.1",
"@actions/exec": "^3.0.0",
"@actions/http-client": "4.0.1",
"@actions/io": "^3.0.2",
"@actions/tool-cache": "^4.0.0",
"semver": "^7.8.6"
},
"devDependencies": {
"@vercel/ncc": "0.45.0",
"husky": "9.1.7",
"jest": "^30.5.2",
"semistandard": "17.0.0"
},
"semistandard": {
"ignore": [
"**/dist/**"
]
}
}
+3 -6
View File
@@ -1,5 +1,6 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
@@ -20,7 +21,7 @@
* // Log out STDOUT contents
* console.log(listener.contents);
*/
class OutputListener {
export default class OutputListener {
constructor (stream) {
this._buff = [];
this._stream = stream;
@@ -35,10 +36,6 @@ class OutputListener {
}
get contents () {
return this._buff
.map(chunk => chunk.toString())
.join('');
return this._buff.map((chunk) => chunk.toString()).join('');
}
}
module.exports = OutputListener;
+6 -3
View File
@@ -1,14 +1,17 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
const os = require('os');
const path = require('path');
import os from 'os';
import path from 'path';
module.exports = (() => {
const tofuBin = (() => {
// If we're on Windows, then the executable ends with .exe
const exeSuffix = os.platform().startsWith('win') ? '.exe' : '';
return [process.env.TOFU_CLI_PATH, `tofu-bin${exeSuffix}`].join(path.sep);
})();
export default tofuBin;
+4 -2
View File
@@ -1,10 +1,12 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
const OutputListener = require('../lib/output-listener');
const { PassThrough } = require('stream');
import OutputListener from '../lib/output-listener.js';
import { PassThrough } from 'stream';
describe('output-listener', () => {
it('receives and exposes data', () => {
const stream = new PassThrough();
+11 -10
View File
@@ -1,20 +1,21 @@
#!/usr/bin/env node
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
const io = require('@actions/io');
const core = require('@actions/core');
const { exec } = require('@actions/exec');
import { which } from '@actions/io';
import { setOutput, setFailed } from '@actions/core';
import { exec } from '@actions/exec';
const OutputListener = require('./lib/output-listener');
const pathToCLI = require('./lib/tofu-bin');
import OutputListener from './lib/output-listener.js';
import pathToCLI from './lib/tofu-bin.js';
async function checkTofu () {
// Setting check to `true` will cause `which` to throw if tofu isn't found
const check = true;
return io.which(pathToCLI, check);
return which(pathToCLI, check);
}
(async () => {
@@ -39,9 +40,9 @@ async function checkTofu () {
const exitCode = await exec(pathToCLI, args, options);
// Set outputs, result, exitcode, and stderr
core.setOutput('stdout', stdout.contents);
core.setOutput('stderr', stderr.contents);
core.setOutput('exitcode', exitCode.toString(10));
setOutput('stdout', stdout.contents);
setOutput('stderr', stderr.contents);
setOutput('exitcode', exitCode.toString(10));
if (exitCode === 0 || exitCode === 2) {
// A exitCode of 0 is considered a success
@@ -52,5 +53,5 @@ async function checkTofu () {
}
// A non-zero exitCode is considered an error
core.setFailed(`OpenTofu exited with code ${exitCode}.`);
setFailed(`OpenTofu exited with code ${exitCode}.`);
})();