Connect to particular GCP account - google-cloud-platform

I have been using the GCP console to connect to a cloud instance and want to switch to using SSH through powershell as that seems to maintain a longer persistence. Transferring my public key through cloud shell into authorized_key file seems to be temporary since once cloud shell disconnects, the file doesn't persist. I've tried using os-login but that generates a completely different user from what I've been using through cloud shell (Cloud shell creates a user: myname while gcloud creates a user: myname_domain_com. Is there a way to continue using the same profile created by cloud shell when logging in through gcloud. I am using the same email and account in both the console and gcloud myname#domain.com. The alternative is to start all over from gcloud and that would be a pain.

If you want to SSH to different instances of a google cloud project (from a mac or Linux), do the following:
Step 1. Install SSH keys without password
Use the following command to generate the keys on your mac
ssh-keygen -t rsa -f ~/.ssh/ -C
For example private-key-name can be bpa-ssh-key. It will create two files with the following names in the ~/.ssh directory
bpa-ssh-key
bpa-ssh-key.pub
Step 2. Update the public key on your GCP project
Goto Google Cloud Console, choose your project, then
VMInstances->Metadata->SSH Keys->Edit->Add Item
Cut and paste the contents of the bpa-ssh-key.pub (from your mac) here and then save
Reset the VM Instance if it is running
Step 3. Edit config file under ~/.ssh on your mac Edit the ~/.ssh/config to add the following lines if not present already
Host *
PubKeyAuthentication yes
IdentityFile ~/.ssh/bpa-ssh-key
Step 4. SSHing to GCP Instance
ssh username#gcloud-externalip
It should create a SSH shell without asking for the password (since you have created the RSA/SSH keys without a password) on the gcloud instance.
Since Metadata is common across all instances under the same project, you can seam-lessly SSH into any of the instances by choosing the respective External IP of the gcloud instance.

Related

GCP Notebook AI -- SSH with write permissions?

I'm trying to set up remote access (with VSCode) to the GCP VM that's setup with Notebooks AI. However, when I ssh into the VM I don't have write permissions for /home/jupyter so cannot edit any of the notebook files.
I have tried both gcloud compute ssh and setting up local aliases with gcloud compute config-ssh.
My best guess is that the users are different. It looks like the terminal on JupyterLab is logged in as jupyter#[instance...] while when I ssh in its myname#[instance...]. Checking permissions of /home/jupyter/, it's owned by user jupyter of group jupyter. I also tried adding users to the jupyter group with sudo usermod -a -G but that didn't do the trick. When I try to ssh in as jupyter#[instance...] from anywhere else I get permission denied (public key).
I can edit files once logged in if I use sudo vim ..., but that won't help for VS code.
EDIT: a partial solution is to open up permissions using sudo chmod 777 /home/jupyter/*. However, that's probably a hackish, unsafe way to do it. Moreover, it only works on existing files -- new files will still only be writable by whichever user created them.
To SSH into the notebook instance as the “jupyter” user, an SSH key should be generated for that user and be added to the notebook VM instance. Also, please make sure that the notebook instance VM has the appropriate firewall rule to allow the SSH connection. The following are the steps that would create an SSH connection to the “jupyter” user which has the write permissions.
Run the following commands on the local machine to generate the required SSH key:
ssh-keygen -t rsa -f ~/.ssh/jupyter-ssh-key -C jupyter
“jupyter-ssh-key” → Name of the pair of public and private keys (Public key: jupyter-ssh-key.pub, Private key: jupyter-ssh-key)
“jupyter” → User in the VM that we are trying to connect to
chmod 400 ~/.ssh/jupyter-ssh-key
In the Compute Engine console, edit the VM settings to add the contents of the generated SSH public key. Detailed instructions can be found here.
Initiate the SSH connection from the local machine to the notebook VM:
ssh -i ~/.ssh/jupyter-ssh-key jupyter#<external-ip-of-notebook-vm-instance>
If the SSH connection succeeds, the same can be followed in VSCode.
In VSCode, select the “Remote-SSH: Connect to Host” option from the command palette. Enter the above ssh -i command to add the notebook VM instance as a recognized host. A new VSCode window will appear where we have been logged in as the “jupyter” user.

Can't connect to GCP VM Permission denied (publickey) error

I'm creating a new VM instance. I've clean all the meta data. Then I'm running the following command in the cloud shell:
gcloud beta compute ssh --zone "europe-west2-c" "vmname" --project "myprojectname"
then I've been asking to enter a passphrase (which I don't know). I press enter until I get the following error Permission denied (publickey) error
I've delete and recreated my instance multiple time but I always have the same error. What should I do?
Troubleshooting Steps:
Logon using UI ssh. This creates an ephemeral ssh key, Google Agent also executes the codepath to refresh .ssh/authorized_keys and address any invalid dir/file permissions for both .ssh/ and .ssh/authorized_keys. This approach will address common gcloud compute ssh issues that relates to corrupted keys, missing dir/file or invalid dir/file permission. Try the gcloud again after performing the UI ssh.
Make sure that account has authenticated to gcloud as an IAM user with the compute instance admin role; for example, run gcloud auth revoke --all, gcloud auth login [IAM-USER] then try gcloud compute ssh again.
Verify that persistent SSH Keys metadata for gcloud is set for either the project or instance. Look in Compute Engine > Metadata, then click SSH Keys. Persistent keys do not have the expireOn attribute.
It's possible the account has lost the private key, mismatched a keypair, etc. You can force gcloud to generate a new SSH keypair by doing the following:
Move ~/.ssh/google_compute_engine and ~/.ssh/google_compute_engine.pub if present.
For example:
mv ~/.ssh/google_compute_engine.pub ~/.ssh/google_compute_engine.pub.old
mv ~/.ssh/google_compute_engine ~/.ssh/google_compute_engine.old
Try gcloud compute ssh [INSTANCE-NAME] again. A new keypair will be created and the public key will be added to the SSH keys metadata.
Verify that the Linux Google Agent scripts are installed, up-to-date, and running. See Determining Google Agent Status. If the Linux Google Agent is not installed, re-install it. See guest-environment.
Verify account home owner/permission is correct. Make sure that account home directory has the correct ownership and is not globally writable. If not using os-login (which is default), your's .ssh folder must have mode 0700, .ssh/authorized_keys file must have mode 0600. Review /var/log/auth.log for any errors.
Commands:
sudo chmod 700 /home/[user-id]/.ssh
sudo chmod 600 /home/[user-id]/.ssh/authorized_keys
If os-login is enabled and the Virtual Machine instance is using a service account (default). Add the following roles to the account.
roles/compute.osLogin
roles/iam.serviceAccountUser
For more information troubleshooting SSH.
The possible causes for a Permission denied (publickey) error are:
Your key expired and Compute Engine deleted your
~/.ssh/authorized_keys file.
You used an SSH key stored in metadata to connect to a VM that has
OS Login enabled.
You used an SSH key stored in an OS Login profile to connect to a VM
that doesn't have OS Login enabled.
You connected using a third-party tool and your SSH command is
misconfigured.
The sshd daemon isn't running or isn't configured properly.
You can find more information on how to troubleshoot SSH key errors in this link
I have the same issue sometimes . Cause and solution according to GCP troubleshooting link is:
Your key expired and Compute Engine deleted your
~/.ssh/authorized_keys file. If you manually added SSH keys to your VM
and then connected to your VM using the Google Cloud Console, Compute
Engine created a new key pair for your connection. After the new key
pair expired, Compute Engine deleted your ~/.ssh/authorized_keys file
in the VM, which included your manually added SSH key.
To resolve this issue, try one of the following:
Connect to your VM using the Google Cloud Console or the gcloud
command-line tool. Re-add your SSH key to metadata. For more information, see Add SSH keys to VMs that use metadata-based SSH keys.
I use terraform so in this case I instructed the workflow to destroy the VM and rebuild it.
To fix this issue when you cannot start ssh:
Edit VM and enable Serial port
Start serial console
Edit ~/.ssh/authorized_keys
On your desktop/client,
edit /Users/[yourdesktopuser]/.ssh/id_rsa.pub
copy contents to clipboard
Paste this content to the end of authorized_keys file in the VM serial console
Save and close
This will then recognize the public key from your desktop

what's the password when Transferring files with gcloud compute scp?

I wanted to Transferring files with gcloud compute scp (https://cloud.google.com/community/tutorials/setting-up-lamp), after running VM, connect SSH key, I input( gcloud compute scp [local file path] root#lamp-2:/home/ )on cloud shell , the system prompt me to inter root#compute.194334494129028111's password, what does that mean?
The correct command from the tutorial is:
gcloud compute copy-files [LOCAL_FILE_PATH] lamp-tutorial:/somepath
Why are you specifying a different user (root) for the target? You can always scp the files to a different users, then ssh into the machine and copy the files to another user's directory (assuming you have permission for the other user).
Generally, when scp asks for a password, it didn't find a matching ssh key. Different users on the target machine would have different ssh keys. What do you mean by "connect SSH key"? Did you connect to the vm as described in the tutorial or did you set up ssh access with ssh-keygen from Cloud Shell to the VM?

GCP VMs + ssh/config file

guys.
GCP offers multiple ways of ssh-ing in gcloud, cloud shell, and local machine cloud SDK.
While all these options are great and I have been using them, I normally prefer using .ssh/config to shorten the process of logging in to machines.
For an example, for EC2, you just add:
Host $name
HostName $hostname
User $username
IdentityFile $pathtoFile
Is there any way to replicate this for GCP VMs?
Thanks
According to This Doc
If you have already connected to an instance through the gcloud tool, your keys are already generated and applied to your project or instance. The key files are available in the following locations:
Linux and macOS
Public key: $HOME/.ssh/google_compute_engine.pub
Private key: $HOME/.ssh/google_compute_engine
Windows
Public key: C:\Users[USERNAME].ssh\google_compute_engine.pub
Private key: C:\Users[USERNAME].ssh\google_compute_engine
You can use the key with typical -i or in .ssh/config config file.
Or simply do
ssh-add ~/.ssh/google_compute_engine
to add the identity to your ssh agent.
PS> I've seen people create an alias for the ssh command, something like
alias gce='gcloud compute ssh'
If you want to SSH to different instances of a google cloud project (from a mac or Linux), do the following:
Step 1. Install SSH keys without password
Use the following command to generate the keys on your mac
ssh-keygen -t rsa -f ~/.ssh/<private-key-name> -C <your gcloud username>
For example private-key-name can be bpa-ssh-key. It will create two files with the
following names in the ~/.ssh directory
bpa-ssh-key
bpa-ssh-key.pub
Step 2. Update the public key on your GCP project
Goto Google Cloud Console, choose your project, then
VMInstances->Metadata->SSH Keys->Edit->Add Item
Cut and paste the contents of the bpa-ssh-key.pub (from your mac) here and then save
Reset the VM Instance if it is running
Step 3. Edit config file under ~/.ssh on your mac
Edit the ~/.ssh/config to add the following lines if not present already
Host *
PubKeyAuthentication yes
IdentityFile ~/.ssh/bpa-ssh-key
Step 4. SSHing to GCP Instance
ssh username#gcloud-externalip
It should create a SSH shell without asking for the password (since you have created the RSA/SSH keys without a password) on the gcloud instance.
Since Metadata is common across all instances under the same project, you can seam-lessly SSH into any of the instances by choosing the respective External IP of the gcloud instance.

Cannot Transfer files from my mac to VM instance on GCP

I have managed to set up a VM instance on Google cloud platform using the following instructions:
https://towardsdatascience.com/running-jupyter-notebook-in-google-cloud-platform-in-15-min-61e16da34d52
I am then able to run a Jupyter notebook as per the instructions.
Now I want to be able to use my own data in the notebook....this is where I am really struggling. I downloaded the Cloud SDK onto my mac and ran this from the terminal (as per https://cloud.google.com/compute/docs/instances/transfer-files)
My-MacBook-Air:~ me$ gcloud compute scp /Users/me/Desktop/my_data.csv aml-test:~/amlfolder
where aml-test is the name of my instance and amlfolder a folder I created on the VM instance. I don't get any error messages and it seems to work (the terminal displays the following after I run it >> 100% 66MB 1.0MB/s 01:03 )
However when I connect to my VM instance via the SSH button on the google console and type
cd amlfolder
ls
I cannot see any files! (nor can I see them from the jupyter notebook homepage)
I cannot figure out how to use my own data in a python jupyter notebook on a GCP VM instance. I have been trying/googling for an entire day. As you might have guessed I'm a complete newbie to GCP (and cd, ls and mkdir is the extent of my linux command knowledge!)
I also tried using Google Cloud Storage - I uploaded the data into a google storage bucket (as per https://cloud.google.com/compute/docs/instances/transfer-files) but don't know how to complete the last step '4. On your instance, download files from the bucket.'
If anyone can figure out what i am doing wrong, or an easier method to get my own data running into a python jupyter notebook on GCP than using gcloud scp command please help!
Definitely try writing
pwd
to verify you're in the path you think you are, there's a chance that your scp command and the console SSH command login as different users.
To copy data from a bucket to the instance, do
gsutil cp gcs://bucket-name/you-file .
As you can see in gcloud compute docs , gcloud compute scp /Users/me/Desktop/my_data.csv aml-test:~/amlfolder will use your local environment username, so the tilde in your command refers to the home directory of a username that is the same name as your local.
But when you SSH from the Browser as you can see from docs that your Gmail username will be used.
So, you should check the home directory of the user used by gcloud compute scp ... command.
The easiest way to check, SSH to your VM and run
ls /home/ --recursive