Compare commits

..
Author SHA1 Message Date
Diogenes Fernandes 92343fa204 fix: wrapper with a signal
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
2026-03-11 23:34:50 -03:00
Diogenes Fernandes 9d84900f32 add cooldown to dependabot
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
2026-01-13 17:27:58 -03:00
dependabot[bot] 9e9a1c276b chore(deps): Bump @actions/core from 2.0.1 to 2.0.2
Bumps [@actions/core](https://github.com/actions/toolkit/tree/HEAD/packages/core) from 2.0.1 to 2.0.2.
- [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: 2.0.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-13 17:27:58 -03:00
Michi U.andDiogenes Fernandes 274fe8537f Add GitHub Actions tool cache support (#76)
Signed-off-by: Michi U. <4169888+michemache@users.noreply.github.com>
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
Co-authored-by: Diogenes Fernandes <diofeher@gmail.com>
2026-01-13 17:20:26 -03:00
10 changed files with 186 additions and 27 deletions

No files matched your search

+2
View File
@@ -1,6 +1,8 @@
version: 2
updates:
- package-ecosystem: "npm"
cooldown:
default-days: 7
directory: "/"
schedule:
interval: "weekly"
+10
View File
@@ -67,6 +67,15 @@ steps:
tofu_wrapper: false
```
Caching can be enabled to reduce download time on subsequent workflow runs by storing the OpenTofu binary using the GitHub Actions [tool-cache](https://github.com/actions/toolkit/tree/main/packages/tool-cache). Note that this feature is primarily useful for self-hosted runners that support toolchain caching, since GitHub-hosted runners are ephemeral and do not persist the tool cache between runs:
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
with:
cache: true
```
Subsequent steps can access outputs when the wrapper script is installed:
```yaml
@@ -264,6 +273,7 @@ The action supports the following inputs:
- `tofu_wrapper` - (optional) Whether to install a wrapper to wrap subsequent calls of
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`.
- `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.
## Outputs
+4
View File
@@ -20,6 +20,10 @@ inputs:
description: 'Whether or not to install a wrapper to wrap subsequent calls of the `tofu` binary and expose its STDOUT, STDERR, and exit code as outputs named `stdout`, `stderr`, and `exitcode` respectively. Defaults to `true`.'
default: 'true'
required: false
cache:
description: 'Whether to use GitHub Actions tool-cache to store and reuse downloaded OpenTofu binaries. Defaults to `false`.'
default: 'false'
required: false
github_token:
description: 'API token for GitHub to increase the rate limit. Defaults to the GITHUB_TOKEN environment variable unless running on Forgejo/Gitea.'
default: ''
+29 -3
View File
@@ -257,6 +257,7 @@ async function run () {
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)) {
// Only default to the environment variable when running in GitHub Actions. Don't do this for other CI systems
@@ -298,8 +299,22 @@ async function run () {
throw new Error(`OpenTofu version ${version} not available for ${platform} and ${arch}`);
}
// Download requested version
const pathToCLI = await downloadAndExtractCLI(build.url);
// Download requested version if not cached
let pathToCLI;
if (useCache) {
const cachedPath = tc.find('tofu', release.version, arch);
if (cachedPath) {
core.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);
}
} else {
pathToCLI = await downloadAndExtractCLI(build.url);
}
// Install our wrapper
if (wrapper) {
@@ -1795,7 +1810,7 @@ class HttpClient {
this._maxRetries = 1;
this._keepAlive = false;
this._disposed = false;
this.userAgent = userAgent;
this.userAgent = this._getUserAgentWithOrchestrationId(userAgent);
this.handlers = handlers || [];
this.requestOptions = requestOptions;
if (requestOptions) {
@@ -2275,6 +2290,17 @@ class HttpClient {
}
return proxyAgent;
}
_getUserAgentWithOrchestrationId(userAgent) {
const baseUserAgent = userAgent || 'actions/http-client';
const orchId = process.env['ACTIONS_ORCHESTRATION_ID'];
if (orchId) {
// Sanitize the orchestration ID to ensure it contains only valid characters
// Valid characters: 0-9, a-z, _, -, .
const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_');
return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`;
}
return baseUserAgent;
}
_performExponentialBackoff(retryNumber) {
return __awaiter(this, void 0, void 0, function* () {
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+12 -1
View File
@@ -1472,7 +1472,7 @@ class HttpClient {
this._maxRetries = 1;
this._keepAlive = false;
this._disposed = false;
this.userAgent = userAgent;
this.userAgent = this._getUserAgentWithOrchestrationId(userAgent);
this.handlers = handlers || [];
this.requestOptions = requestOptions;
if (requestOptions) {
@@ -1952,6 +1952,17 @@ class HttpClient {
}
return proxyAgent;
}
_getUserAgentWithOrchestrationId(userAgent) {
const baseUserAgent = userAgent || 'actions/http-client';
const orchId = process.env['ACTIONS_ORCHESTRATION_ID'];
if (orchId) {
// Sanitize the orchestration ID to ensure it contains only valid characters
// Valid characters: 0-9, a-z, _, -, .
const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_');
return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`;
}
return baseUserAgent;
}
_performExponentialBackoff(retryNumber) {
return __awaiter(this, void 0, void 0, function* () {
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+17 -2
View File
@@ -133,6 +133,7 @@ async function run () {
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)) {
// Only default to the environment variable when running in GitHub Actions. Don't do this for other CI systems
@@ -174,8 +175,22 @@ async function run () {
throw new Error(`OpenTofu version ${version} not available for ${platform} and ${arch}`);
}
// Download requested version
const pathToCLI = await downloadAndExtractCLI(build.url);
// Download requested version if not cached
let pathToCLI;
if (useCache) {
const cachedPath = tc.find('tofu', release.version, arch);
if (cachedPath) {
core.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);
}
} else {
pathToCLI = await downloadAndExtractCLI(build.url);
}
// Install our wrapper
if (wrapper) {
+84 -1
View File
@@ -19,7 +19,9 @@ jest.mock('@actions/io', () => ({
}));
jest.mock('@actions/tool-cache', () => ({
downloadTool: jest.fn(),
extractZip: jest.fn()
extractZip: jest.fn(),
find: jest.fn(),
cacheDir: jest.fn()
}));
// Mock releases.js so setup-tofu.js can be tested in isolation
@@ -39,6 +41,8 @@ describe('setup-tofu', () => {
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();
@@ -46,6 +50,7 @@ describe('setup-tofu', () => {
io.mkdirP.mockResolvedValue();
const mockRelease = {
version: '1.10.5',
getBuild: jest.fn().mockReturnValue({ url: 'mock-url' })
};
releases.getRelease.mockResolvedValue(mockRelease);
@@ -64,6 +69,7 @@ describe('setup-tofu', () => {
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
@@ -173,4 +179,81 @@ describe('setup-tofu', () => {
expect(fs.readFile).not.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) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
cache: 'true',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(tc.find).toHaveBeenCalledWith('tofu', '1.10.5', expect.any(String));
expect(tc.downloadTool).not.toHaveBeenCalled();
expect(tc.extractZip).not.toHaveBeenCalled();
expect(tc.cacheDir).not.toHaveBeenCalled();
});
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) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
cache: 'true',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(tc.find).toHaveBeenCalledWith('tofu', '1.10.5', expect.any(String));
expect(tc.downloadTool).toHaveBeenCalled();
expect(tc.extractZip).toHaveBeenCalled();
expect(tc.cacheDir).toHaveBeenCalledWith('/mock/extract/path', 'tofu', '1.10.5', expect.any(String));
});
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) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(tc.find).not.toHaveBeenCalled();
expect(tc.downloadTool).toHaveBeenCalled();
expect(tc.extractZip).toHaveBeenCalled();
expect(tc.cacheDir).not.toHaveBeenCalled();
});
});
});
+8 -8
View File
@@ -9,7 +9,7 @@
"version": "1.0.1",
"license": "MPL-2.0",
"dependencies": {
"@actions/core": "2.0.1",
"@actions/core": "2.0.2",
"@actions/exec": "2.0.0",
"@actions/io": "2.0.0",
"@actions/tool-cache": "2.0.2",
@@ -32,19 +32,19 @@
}
},
"node_modules/@actions/core": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@actions/core/-/core-2.0.1.tgz",
"integrity": "sha512-oBfqT3GwkvLlo1fjvhQLQxuwZCGTarTE5OuZ2Wg10hvhBj7LRIlF611WT4aZS6fDhO5ZKlY7lCAZTlpmyaHaeg==",
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@actions/core/-/core-2.0.2.tgz",
"integrity": "sha512-Ast1V7yHbGAhplAsuVlnb/5J8Mtr/Zl6byPPL+Qjq3lmfIgWF1ak1iYfF/079cRERiuTALTXkSuEUdZeDCfGtA==",
"license": "MIT",
"dependencies": {
"@actions/exec": "^2.0.0",
"@actions/http-client": "^3.0.0"
"@actions/http-client": "^3.0.1"
}
},
"node_modules/@actions/core/node_modules/@actions/http-client": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-3.0.0.tgz",
"integrity": "sha512-1s3tXAfVMSz9a4ZEBkXXRQD4QhY3+GAsWSbaYpeknPOKEeyRiU3lH+bHiLMZdo2x/fIeQ/hscL1wCkDLVM2DZQ==",
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-3.0.1.tgz",
"integrity": "sha512-SbGS8c/vySbNO3kjFgSW77n83C4MQx/Yoe+b1hAdpuvfHxnkHzDq2pWljUpAA56Si1Gae/7zjeZsV0CYjmLo/w==",
"license": "MIT",
"dependencies": {
"tunnel": "^0.0.6",
+1 -1
View File
@@ -19,7 +19,7 @@
"keywords": [],
"author": "",
"dependencies": {
"@actions/core": "2.0.1",
"@actions/core": "2.0.2",
"@actions/exec": "2.0.0",
"@actions/io": "2.0.0",
"@actions/tool-cache": "2.0.2",
+19 -11
View File
@@ -6,7 +6,7 @@
const io = require('@actions/io');
const core = require('@actions/core');
const { exec } = require('@actions/exec');
const { spawn } = require('child_process');
const OutputListener = require('./lib/output-listener');
const pathToCLI = require('./lib/tofu-bin');
@@ -24,19 +24,27 @@ async function checkTofu () {
// Create listeners to receive output (in memory) as well
const stdout = new OutputListener(process.stdout);
const stderr = new OutputListener(process.stderr);
const listeners = {
stdout: stdout.listener,
stderr: stderr.listener
};
// Execute tofu and capture output
const args = process.argv.slice(2);
const options = {
listeners,
ignoreReturnCode: true,
silent: true // don't print "[command...]" into stdout: https://github.com/actions/toolkit/issues/649
};
const exitCode = await exec(pathToCLI, args, options);
const child = spawn(pathToCLI, args, { stdio: ['inherit', 'pipe', 'pipe'] });
// Forward signals to child so tofu can release state locks on cancellation
const forwardSigterm = () => { child.kill('SIGTERM'); };
const forwardSigint = () => { child.kill('SIGINT'); };
process.on('SIGTERM', forwardSigterm);
process.on('SIGINT', forwardSigint);
child.stdout.on('data', stdout.listener);
child.stderr.on('data', stderr.listener);
const exitCode = await new Promise((resolve) => {
// code is null when the process is killed by a signal; treat as failure
child.on('close', (code) => resolve(code ?? 1));
});
process.removeListener('SIGTERM', forwardSigterm);
process.removeListener('SIGINT', forwardSigint);
// Set outputs, result, exitcode, and stderr
core.setOutput('stdout', stdout.contents);