Skip to content

Commit

Permalink
Ignore failures when trying to kill the ssh-agent (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
mpdude committed Jun 24, 2020
1 parent 5ef9e03 commit ef0ce0c
Show file tree
Hide file tree
Showing 7 changed files with 284 additions and 109 deletions.
22 changes: 21 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## v0.2.0
## v0.4.0

### Changed

* A failure to kill the agent in the post-action step will no longer fail the workflow run. That way, you can kill the agent yourself when necessary (#33).

## v0.3.0 [2020-05-18]

### Added

* A new post-action step will automatically clean up the running agent at the end of a job. This helps with self-hosted runners, which are non-ephemeral. (@thommyhh, #27)

### Changed

* Unless the SSH_AUTH_SOCK is configured explicitly, the SSH agent will now use a random file name for the socket. That way, multiple, concurrent SSH agents can be used on self-hosted runners. (@thommyhh, #27)

## v0.2.0 [2020-01-14]

### Added

Expand All @@ -16,3 +32,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

* Catch empty ssh-private-key input values and exit with a helpful
error message right away.

## v0.1.0 [2019-09-15]

Initial release.
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ jobs:
...
steps:
- actions/checkout@v1
# Make sure the @v0.3.0 matches the current version of the
# Make sure the @v0.4.0 matches the current version of the
# action
- uses: webfactory/ssh-agent@v0.3.0
- uses: webfactory/ssh-agent@v0.4.0
with:
ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
- ... other steps
Expand All @@ -44,7 +44,7 @@ In that case, you can set-up the different keys as multiple secrets and pass the

```yaml
# ... contens as before
- uses: webfactory/ssh-agent@v0.3.0
- uses: webfactory/ssh-agent@v0.4.0
with:
ssh-private-key: |
${{ secrets.FIRST_KEY }}
Expand All @@ -55,10 +55,10 @@ In that case, you can set-up the different keys as multiple secrets and pass the
The `ssh-agent` will load all of the keys and try each one in order when establishing SSH connections.

There's one **caveat**, though: SSH servers may abort the connection attempt after a number of mismatching keys have been presented. So if, for example, you have
six different keys loaded into the `ssh-agent`, but the server aborts after five unknown keys, the last key (which might be the right one) will never even be tried.
six different keys loaded into the `ssh-agent`, but the server aborts after five unknown keys, the last key (which might be the right one) will never even be tried. If you don't need all of the keys at the same time, you could try to `run: kill $SSH_AGENT_PID` to kill the currently running `ssh-agent` and use the action again in a following step to start another instance.

## Exported variables
The action exports `SSH_AUTH_SOCK` and `SSH_AGENT_PID` through the Github Actions core module.
The action exports the `SSH_AUTH_SOCK` and `SSH_AGENT_PID` environment variables through the Github Actions core module.
The `$SSH_AUTH_SOCK` is used by several applications like git or rsync to connect to the SSH authentication agent.
The `$SSH_AGENT_PID` contains the process id of the agent. This is used to kill the agent in post job action.

Expand Down Expand Up @@ -118,7 +118,7 @@ To actually grant the SSH key access, you can – on GitHub – use at least two
As a note to my future self, in order to work on this repo:

* Clone it
* Run `npm install` to fetch dependencies
* Run `yarn install` to fetch dependencies
* _hack hack hack_
* `node index.js`. Inputs are passed through `INPUT_` env vars with their names uppercased. Use `env "INPUT_SSH-PRIVATE-KEY=\`cat file\`" node index.js` for this action.
* Run `npm run build` to update `dist/*`, which holds the files actually run
Expand Down
3 changes: 2 additions & 1 deletion cleanup.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ try {
console.log('Stopping SSH agent')
execSync('kill ${SSH_AGENT_PID}', { stdio: 'inherit' })
} catch (error) {
core.setFailed(error.message)
console.log(error.message);
console.log('Error stopping the SSH agent, proceeding anyway');
}
163 changes: 122 additions & 41 deletions dist/cleanup.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ try {
console.log('Stopping SSH agent')
execSync('kill ${SSH_AGENT_PID}', { stdio: 'inherit' })
} catch (error) {
core.setFailed(error.message)
console.log(error.message);
console.log('Error stopping the SSH agent, proceeding anyway');
}


Expand All @@ -79,17 +80,24 @@ try {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = __webpack_require__(87);
const os = __importStar(__webpack_require__(87));
/**
* Commands
*
* Command Format:
* ##[name key=value;key=value]message
* ::name key=value,key=value::message
*
* Examples:
* ##[warning]This is the user warning message
* ##[set-secret name=mypassword]definitelyNotAPassword!
* ::warning::This is the message
* ::set-env name=MY_VAR::some value
*/
function issueCommand(command, properties, message) {
const cmd = new Command(command, properties, message);
Expand All @@ -100,7 +108,7 @@ function issue(name, message = '') {
issueCommand(name, {}, message);
}
exports.issue = issue;
const CMD_PREFIX = '##[';
const CMD_STRING = '::';
class Command {
constructor(command, properties, message) {
if (!command) {
Expand All @@ -111,37 +119,56 @@ class Command {
this.message = message;
}
toString() {
let cmdStr = CMD_PREFIX + this.command;
let cmdStr = CMD_STRING + this.command;
if (this.properties && Object.keys(this.properties).length > 0) {
cmdStr += ' ';
let first = true;
for (const key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
const val = this.properties[key];
if (val) {
// safely append the val - avoid blowing up when attempting to
// call .replace() if message is not a string for some reason
cmdStr += `${key}=${escape(`${val || ''}`)};`;
if (first) {
first = false;
}
else {
cmdStr += ',';
}
cmdStr += `${key}=${escapeProperty(val)}`;
}
}
}
}
cmdStr += ']';
// safely append the message - avoid blowing up when attempting to
// call .replace() if message is not a string for some reason
const message = `${this.message || ''}`;
cmdStr += escapeData(message);
cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
return cmdStr;
}
}
/**
* Sanitizes an input into a string so it can be passed into issueCommand safely
* @param input input to sanitize into a string
*/
function toCommandValue(input) {
if (input === null || input === undefined) {
return '';
}
else if (typeof input === 'string' || input instanceof String) {
return input;
}
return JSON.stringify(input);
}
exports.toCommandValue = toCommandValue;
function escapeData(s) {
return s.replace(/\r/g, '%0D').replace(/\n/g, '%0A');
return toCommandValue(s)
.replace(/%/g, '%25')
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A');
}
function escape(s) {
return s
function escapeProperty(s) {
return toCommandValue(s)
.replace(/%/g, '%25')
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A')
.replace(/]/g, '%5D')
.replace(/;/g, '%3B');
.replace(/:/g, '%3A')
.replace(/,/g, '%2C');
}
//# sourceMappingURL=command.js.map

Expand All @@ -161,9 +188,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const command_1 = __webpack_require__(431);
const path = __webpack_require__(622);
const os = __importStar(__webpack_require__(87));
const path = __importStar(__webpack_require__(622));
/**
* The code to exit an action
*/
Expand All @@ -182,28 +217,25 @@ var ExitCode;
// Variables
//-----------------------------------------------------------------------
/**
* sets env variable for this action and future actions in the job
* Sets env variable for this action and future actions in the job
* @param name the name of the variable to set
* @param val the value of the variable
* @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function exportVariable(name, val) {
process.env[name] = val;
command_1.issueCommand('set-env', { name }, val);
const convertedVal = command_1.toCommandValue(val);
process.env[name] = convertedVal;
command_1.issueCommand('set-env', { name }, convertedVal);
}
exports.exportVariable = exportVariable;
/**
* exports the variable and registers a secret which will get masked from logs
* @param name the name of the variable to set
* @param val value of the secret
* Registers a secret which will get masked from logs
* @param secret value of the secret
*/
function exportSecret(name, val) {
exportVariable(name, val);
// the runner will error with not implemented
// leaving the function but raising the error earlier
command_1.issueCommand('set-secret', {}, val);
throw new Error('Not implemented.');
function setSecret(secret) {
command_1.issueCommand('add-mask', {}, secret);
}
exports.exportSecret = exportSecret;
exports.setSecret = setSecret;
/**
* Prepends inputPath to the PATH (for this action and future actions)
* @param inputPath
Expand All @@ -221,7 +253,7 @@ exports.addPath = addPath;
* @returns string
*/
function getInput(name, options) {
const val = process.env[`INPUT_${name.replace(' ', '_').toUpperCase()}`] || '';
const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
Expand All @@ -232,12 +264,22 @@ exports.getInput = getInput;
* Sets the value of an output.
*
* @param name name of the output to set
* @param value value to store
* @param value value to store. Non-string values will be converted to a string via JSON.stringify
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function setOutput(name, value) {
command_1.issueCommand('set-output', { name }, value);
}
exports.setOutput = setOutput;
/**
* Enables or disables the echoing of commands into stdout for the rest of the step.
* Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
*
*/
function setCommandEcho(enabled) {
command_1.issue('echo', enabled ? 'on' : 'off');
}
exports.setCommandEcho = setCommandEcho;
//-----------------------------------------------------------------------
// Results
//-----------------------------------------------------------------------
Expand All @@ -254,6 +296,13 @@ exports.setFailed = setFailed;
//-----------------------------------------------------------------------
// Logging Commands
//-----------------------------------------------------------------------
/**
* Gets whether Actions Step Debug is on or not
*/
function isDebug() {
return process.env['RUNNER_DEBUG'] === '1';
}
exports.isDebug = isDebug;
/**
* Writes debug message to user log
* @param message debug message
Expand All @@ -264,20 +313,28 @@ function debug(message) {
exports.debug = debug;
/**
* Adds an error issue
* @param message error issue message
* @param message error issue message. Errors will be converted to string via toString()
*/
function error(message) {
command_1.issue('error', message);
command_1.issue('error', message instanceof Error ? message.toString() : message);
}
exports.error = error;
/**
* Adds an warning issue
* @param message warning issue message
* @param message warning issue message. Errors will be converted to string via toString()
*/
function warning(message) {
command_1.issue('warning', message);
command_1.issue('warning', message instanceof Error ? message.toString() : message);
}
exports.warning = warning;
/**
* Writes info to log with console.log.
* @param message info message
*/
function info(message) {
process.stdout.write(message + os.EOL);
}
exports.info = info;
/**
* Begin an output group.
*
Expand Down Expand Up @@ -318,6 +375,30 @@ function group(name, fn) {
});
}
exports.group = group;
//-----------------------------------------------------------------------
// Wrapper action state
//-----------------------------------------------------------------------
/**
* Saves state for current action, the state can only be retrieved by this action's post job execution.
*
* @param name name of the state to store
* @param value value to store. Non-string values will be converted to a string via JSON.stringify
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function saveState(name, value) {
command_1.issueCommand('save-state', { name }, value);
}
exports.saveState = saveState;
/**
* Gets the value of an state set by this action's main execution.
*
* @param name name of the state to get
* @returns string
*/
function getState(name) {
return process.env[`STATE_${name}`] || '';
}
exports.getState = getState;
//# sourceMappingURL=core.js.map

/***/ }),
Expand Down
Loading

0 comments on commit ef0ce0c

Please sign in to comment.