Home > Back-end >  Reformatting ssh-key to import into gcp project metadata
Reformatting ssh-key to import into gcp project metadata

Time:11-14

I want to add an ssh-key generated in a shell script to my gcp project metadata. The problem is, that I don't really know how to format the generated key to be in the format which is need for the project metadata. The ssh-key I have looks like this:

ssh-rsa AAAAB3.... username

The format that is stated in the documentation is this:

username:ssh-rsa AAAAB3....

Is there a way to reformat the key within my shell script using echo and cat?

My best try is this: echo $USERNAME:$(cat ~/.ssh/id_rsa.pub), but this still leaves the trailing username at the end.

CodePudding user response:

Assuming you are using bash, this should do the trick:

# Use the following line to read the key from a file
# KEY_WITH_USERNAME=$(cat ~/.ssh/id_rsa.pub)

KEY_WITH_USERNAME="ssh-rsa AAAAB3.... username"
USERNAME=${KEY_WITH_USERNAME##* }

KEY_WITHOUT_USERNAME=${KEY_WITH_USERNAME%"$USERNAME"}

echo $USERNAME:$KEY_WITHOUT_USERNAME

Outputs:

username:ssh-rsa AAAAB3....

See related questions about how to remove pre- or suffix from a string in Bash and how to split a string and get the final part.

  • Related