GCP – sudo works in GoogleCloudShell but not when I ssh into vm

google-cloud-platformssh

I created a brand new Google Compute Engine VM (Debian 9) and opened a shell to it using the GoogleCloud shell. I can sudo from that browser shell window.

I then setup my ssh-keys and ssh into the vm. For the sake of discussion, my username is "user123". I ssh into my GCP vm using:

ssh user123@1.2.3.4

Where 1.2.3.4 is my GCP external IP address. I'm then logged in.

So as user user123 in GoogleCloudShell sudo works, but when logged in via ssh as user123, I'm prompted for a password.

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for user123:

Naturally, I don't want or need to setup a password, I need to get sudo to allow this user123 user account to sudo. But it works when logged into GoogleCloudShell…. Hum… I'll track it down but that is my question.

NOTE: Since I have root in my GoogleCloudShell (via sudo), I should be able to find what I need to do and fix this.

What is the next step I need to take in order to allow sudo to work when logged in via ssh?

Best Answer

I'll give you 2 answers.

First, cloud shell is managing instance metadata for you behind the scenes, and allows passwordless sudo for all users added to the project this way. Use google to set up your user

https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys https://cloud.google.com/compute/docs/instances/managing-instance-access

Add the user account you want through the project console. This will propagate that user to all hosts in your project.

Secondly, what you want is to set up passwordless sudo. You can (using visudo) edit /etc/sudoers or create a new file under /etc/sudoers.d and add a line like this:

user123       ALL = (ALL) NOPASSWD: ALL

you can see that google is doing it by group membership in the google-sudoers group

timmy@instance-1:~$ sudo cat /etc/sudoers.d/google_sudoers 
%google-sudoers ALL=(ALL:ALL) NOPASSWD:ALL
timmy@instance-1:~$ id
uid=1000(timmy) gid=1001(timmy) groups=1001(timmy),4(adm),30(dip),44(video),46(plugdev),1000(google-sudoers)
Related Question