1
0
Fork 0
mirror of https://github.com/shimataro/ssh-key-action.git synced 2025-06-19 22:52:10 +10:00

add "if_key_exists" (#179)

* add "if_key_exists"

* add test

* fix flag

* fix SSH connection commands

* add test for if_key_exists=ignore

* add test for if_key_exists=fail

* add tests to Windows / macOS

* update CHANGELOG

* update badges

* update README

* fix README

* update README

* add tests for Docker containers
This commit is contained in:
shimataro 2021-03-18 20:57:28 +09:00 committed by GitHub
parent 8053198ce5
commit 88fb14d113
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 1308 additions and 445 deletions

View file

@ -17,36 +17,16 @@ function main(): void
{
try
{
const files: FileInfo[] = [
{
name: core.getInput("name"),
contents: insertLf(core.getInput("key", {
required: true,
}), false, true),
options: {
mode: 0o400,
flag: "ax",
},
},
{
name: "known_hosts",
contents: insertLf(core.getInput("known_hosts", {
required: true,
}), true, true),
options: {
mode: 0o644,
flag: "a",
},
},
{
name: "config",
contents: insertLf(core.getInput("config"), true, true),
options: {
mode: 0o644,
flag: "a",
},
},
];
// parameters
const key = core.getInput("key", {
required: true,
});
const name = core.getInput("name");
const knownHosts = core.getInput("known_hosts", {
required: true,
});
const config = core.getInput("config");
const ifKeyExists = core.getInput("if_key_exists");
// create ".ssh" directory
const home = getHomeDirectory();
@ -56,6 +36,37 @@ function main(): void
mode: 0o700,
});
// files to be created
const files: FileInfo[] = [
{
name: "known_hosts",
contents: insertLf(knownHosts, true, true),
options: {
mode: 0o644,
flag: "a",
},
},
{
name: "config",
contents: insertLf(config, true, true),
options: {
mode: 0o644,
flag: "a",
},
},
];
if(shouldCreateKeyFile(path.join(dirName, name), ifKeyExists))
{
files.push({
name: name,
contents: insertLf(key, false, true),
options: {
mode: 0o400,
flag: "wx",
},
});
}
// create files
for(const file of files)
{
@ -137,4 +148,35 @@ function insertLf(value: string, prepend: boolean, append: boolean): string
return affectedValue;
}
/**
* should create SSH key file?
* @param keyFilePath path of key file
* @param ifKeyExists action if SSH key exists
* @returns Yes/No
*/
function shouldCreateKeyFile(keyFilePath: string, ifKeyExists: string): boolean
{
if(!fs.existsSync(keyFilePath))
{
// should create if file does not exist
return true;
}
switch(ifKeyExists)
{
case "replace":
// remove file and should create if replace
fs.unlinkSync(keyFilePath);
return true;
case "ignore":
// should NOT create if ignore
return false;
default:
// error otherwise
throw new Error(`SSH key is already installed. Set "if_key_exists" to "replace" or "ignore" in order to avoid this error.`);
}
}
main();