mirror of
https://github.com/opentofu/setup-opentofu.git
synced 2026-11-26 18:30:54 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
072b9103f4 | ||
|
|
96ef8e8ef7 | ||
|
|
d1e6b1026d | ||
|
|
44508bff04 | ||
|
|
1ecf18781e | ||
|
|
fd1f729ebf | ||
|
|
fb72d0a2d4 | ||
|
|
3dc45c9802 | ||
|
|
b648b1c29e | ||
|
|
94ffd00999 | ||
|
|
22f847ff73 | ||
|
|
37a417e5ae | ||
|
|
7f68c568ed | ||
|
|
cf87c0adc1 | ||
|
|
cb2c66ad3c | ||
|
|
19d3fc38c4 | ||
|
|
698c415dcd | ||
|
|
a1320f8929 | ||
|
|
d3dc77de53 | ||
|
|
56007213a1 | ||
|
|
7051243a57 | ||
|
|
50e079f741 | ||
|
|
0c73a96b62 | ||
|
|
7526f4bce4 | ||
|
|
a630d3b887 | ||
|
|
7e2b8769cc | ||
|
|
847eaa4afe | ||
|
|
34bf4e3161 | ||
|
|
4bcfe8cded | ||
|
|
03a9076efe | ||
|
|
ba1f8b8e04 | ||
|
|
26ccb9be2d | ||
|
|
b572e07b01 | ||
|
|
4959f8f18c |
No files matched your search
@@ -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,3 +6,9 @@ updates:
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "github-actions"
|
||||
cooldown:
|
||||
default-days: 7
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
@@ -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@v6
|
||||
- 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
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
tofu-version-files: ['./.github/workflows/data/local/.opentofu-version']
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
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@v6
|
||||
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@v6
|
||||
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@v6
|
||||
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@v6
|
||||
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@v6
|
||||
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@v6
|
||||
uses: actions/checkout@v7.0.1
|
||||
|
||||
- name: Setup OpenTofu
|
||||
uses: ./
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.'
|
||||
|
||||
Vendored
+1967
-340
File diff suppressed because it is too large.
Load diff
Vendored
+1084
-308
File diff suppressed because it is too large.
Load diff
@@ -4,14 +4,17 @@
|
||||
* SPDX-License-Identifier: MPL-2.0
|
||||
*/
|
||||
|
||||
import { setFailed } from '@actions/core';
|
||||
import { setFailed, debug } from '@actions/core';
|
||||
|
||||
import setup from './lib/setup-tofu.js';
|
||||
import { getErrorMessage, getErrorDetail } from './lib/error-utils.js';
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
await setup();
|
||||
} catch (error) {
|
||||
setFailed(error.message);
|
||||
const message = getErrorMessage(error);
|
||||
debug(getErrorDetail(error));
|
||||
setFailed(message);
|
||||
}
|
||||
})();
|
||||
@@ -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 };
|
||||
+104
-4
@@ -6,6 +6,7 @@
|
||||
|
||||
import { HttpClient, HttpCodes } from '@actions/http-client';
|
||||
import semver from 'semver';
|
||||
import { getErrorMessage } from './error-utils.js';
|
||||
|
||||
class Build {
|
||||
constructor (version, name) {
|
||||
@@ -44,7 +45,13 @@ async function fetchReleases (githubToken) {
|
||||
Accept: 'application/json'
|
||||
};
|
||||
|
||||
const resp = await http.get(url, headers);
|
||||
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}`);
|
||||
}
|
||||
|
||||
if (resp.message.statusCode !== HttpCodes.OK) {
|
||||
throw new Error(
|
||||
@@ -52,8 +59,21 @@ async function fetchReleases (githubToken) {
|
||||
);
|
||||
}
|
||||
|
||||
const body = await resp.readBody();
|
||||
const releasesMeta = JSON.parse(body);
|
||||
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}
|
||||
@@ -63,6 +83,86 @@ async function fetchReleases (githubToken) {
|
||||
return versions.map((releaseMeta) => new Release(releaseMeta));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
@@ -125,4 +225,4 @@ async function getRelease (
|
||||
return releases.find((release) => release.version === versionSelected);
|
||||
}
|
||||
|
||||
export { getRelease, Release };
|
||||
export { getRelease, getDownloadChecksum, parseChecksum, Release };
|
||||
+101
-18
@@ -7,7 +7,7 @@
|
||||
// Node.js core
|
||||
import { promises as fs } from 'fs';
|
||||
import { platform, arch } from 'os';
|
||||
import { sep, resolve, dirname } from 'path';
|
||||
import { sep, join, resolve, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
// External
|
||||
@@ -16,12 +16,15 @@ import {
|
||||
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 } from './releases.js';
|
||||
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));
|
||||
@@ -45,9 +48,29 @@ function mapOS (os) {
|
||||
return os;
|
||||
}
|
||||
|
||||
async function downloadAndExtractCLI (url) {
|
||||
async function downloadAndExtractCLI (url, checksums) {
|
||||
debug(`Downloading OpenTofu CLI from ${url}`);
|
||||
const pathToCLIZip = await downloadTool(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}`);
|
||||
@@ -56,14 +79,19 @@ async function downloadAndExtractCLI (url) {
|
||||
let pathToCLI;
|
||||
|
||||
debug('Extracting OpenTofu CLI zip file');
|
||||
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);
|
||||
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}`);
|
||||
}
|
||||
|
||||
debug(`OpenTofu CLI path is ${pathToCLI}.`);
|
||||
@@ -75,6 +103,42 @@ 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;
|
||||
|
||||
@@ -149,7 +213,9 @@ async function run () {
|
||||
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 === '' &&
|
||||
@@ -165,9 +231,14 @@ async function run () {
|
||||
try {
|
||||
debug(`Reading OpenTofu version from file: ${versionFile}`);
|
||||
const fileVersion = await fs.readFile(versionFile, 'utf8');
|
||||
const trimmedVersion = fileVersion.trim();
|
||||
if (trimmedVersion) {
|
||||
version = trimmedVersion;
|
||||
// .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 {
|
||||
warning(
|
||||
@@ -205,12 +276,14 @@ async function run () {
|
||||
pathToCLI = cachedPath;
|
||||
} else {
|
||||
debug(`OpenTofu version ${release.version} not found in cache, downloading...`);
|
||||
const extractedPath = await downloadAndExtractCLI(build.url);
|
||||
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
|
||||
@@ -221,13 +294,23 @@ async function run () {
|
||||
// Add to path
|
||||
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) {
|
||||
await addCredentials(credentialsHostname, credentialsToken, osPlatform);
|
||||
}
|
||||
return release;
|
||||
} catch (error) {
|
||||
logError(error);
|
||||
logError(getErrorMessage(error));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@
|
||||
* SPDX-License-Identifier: MPL-2.0
|
||||
*/
|
||||
|
||||
import { Release, getRelease } from '../releases.js';
|
||||
import { Release, getRelease, getDownloadChecksum, parseChecksum } from '../releases.js';
|
||||
|
||||
describe('getRelease', () => {
|
||||
function mockFetchReleases () {
|
||||
@@ -196,3 +196,71 @@ describe('getRelease', () => {
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
+211
-3
@@ -14,6 +14,7 @@ import { join } from 'path';
|
||||
// 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(),
|
||||
@@ -38,15 +39,21 @@ jest.unstable_mockModule('@actions/tool-cache', () => ({
|
||||
|
||||
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 } = await import('@actions/core');
|
||||
const { getInput, warning, exportVariable, getMultilineInput } = await import('@actions/core');
|
||||
const tc = await import('@actions/tool-cache');
|
||||
const io = await import('@actions/io');
|
||||
const { getRelease } = await import('../releases.js');
|
||||
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';
|
||||
@@ -70,10 +77,17 @@ describe('setup-tofu', () => {
|
||||
|
||||
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'
|
||||
})
|
||||
};
|
||||
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 = join(tmpdir(), 'setup-tofu-');
|
||||
tempDir = await fs.mkdtemp(tempDirPath);
|
||||
@@ -88,12 +102,20 @@ describe('setup-tofu', () => {
|
||||
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';
|
||||
});
|
||||
@@ -203,6 +225,34 @@ describe('setup-tofu', () => {
|
||||
|
||||
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', () => {
|
||||
@@ -264,6 +314,7 @@ describe('setup-tofu', () => {
|
||||
cli_config_credentials_hostname: '',
|
||||
cli_config_credentials_token: '',
|
||||
tofu_wrapper: 'true',
|
||||
provider_acceptance_tests: 'false',
|
||||
cache: 'false',
|
||||
github_token: ''
|
||||
};
|
||||
@@ -278,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
@@ -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');
|
||||
}
|
||||
Generated
+1361
-832
File diff suppressed because it is too large.
Load diff
+6
-6
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "setup-opentofu",
|
||||
"version": "1.0.1",
|
||||
"version": "2.0.2",
|
||||
"description": "Setup OpenTofu CLI for GitHub Actions",
|
||||
"type": "module",
|
||||
"license": "MPL-2.0",
|
||||
@@ -20,17 +20,17 @@
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"dependencies": {
|
||||
"@actions/core": "^3.0.0",
|
||||
"@actions/core": "^3.0.1",
|
||||
"@actions/exec": "^3.0.0",
|
||||
"@actions/http-client": "^4.0.0",
|
||||
"@actions/http-client": "4.0.1",
|
||||
"@actions/io": "^3.0.2",
|
||||
"@actions/tool-cache": "^4.0.0",
|
||||
"semver": "^7.7.4"
|
||||
"semver": "^7.8.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vercel/ncc": "0.38.4",
|
||||
"@vercel/ncc": "0.45.0",
|
||||
"husky": "9.1.7",
|
||||
"jest": "^30.3.0",
|
||||
"jest": "^30.5.2",
|
||||
"semistandard": "17.0.0"
|
||||
},
|
||||
"semistandard": {
|
||||
|
||||
Reference in new issue
Block a user