Skip to main content

Correct umask value to automate the creation of file with the SSH private key content [Resolved]

I'm trying to find a way to shorten these lines (CI_PRIVATE_SSH_KEY is already set):

mkdir -p "${HOME}/.ssh/"
chmod 700 "${HOME}/.ssh/"
echo "${CI_PRIVATE_SSH_KEY}" > "${HOME}/.ssh/id_rsa"
chmod 600 "${HOME}/.ssh/id_rsa"

This is what I have so far:

(umask 077; mkdir -p "${HOME}/.ssh/"; echo "${CI_PRIVATE_SSH_KEY}" > "${HOME}/.ssh/id_rsa")

But this doens't quite work, because the directory is getting created with no group + other permissions.

So my question is: is there a umask value that let me create directories with 700 and files with 600 (provided the default value is 0022)?

I've also tried 177, but it doesn't work either.

Question Credit: x80486
Question Reference
Asked September 19, 2019
Posted Under: Unix Linux
1 Answers

i agreed with @Jeff Schaller, chmod is clear and obvious versus umask.
try to build one liner with && operator
and the preferred permission of .ssh directory changed to 644
bash would try to run the command from left to right of the && operator
and only continues when all the "left side" command return status is 0

mkdir -p "${HOME}/.ssh/" && chmod 644 "${HOME}/.ssh/" && echo "${CI_PRIVATE_SSH_KEY}" > "${HOME}/.ssh/id_rsa" && chmod 600 "${HOME}/.ssh/id_rsa"

or umask 133 for .ssh , 177 for the key,

(umask 133; mkdir -p "${HOME}/.ssh/";umask 177; echo "${CI_PRIVATE_SSH_KEY}" > "${HOME}/.ssh/id_rsa")

credit: bigdataolddriver
Answered September 19, 2019
Your Answer