Changing the SSH port on Container-Optimized OS for Google Cloud Platform

(If you want the solution, scroll down to the end.)

I recently took it upon myself to figure out a lightweight solution for a few Docker-utilizing services I manage. Upon creating a new instance in Google Cloud Platform, I noticed the support for Container-Optimized OS (which for the sake of length will be referenced as cos). It seemed pretty cool, so I spun up an instance and got to work.

One of my services requires the default SSH (22) port to be open, whereas cos default exposes its SSH on 22. My first thought was that it'd be pretty easy to sudo vi /etc/ssh/sshd_config and add Port 2222 to the end.

...reboot... yup, nothing.

The documentation on cos' filesystem says that /etc is stateless. Basically, it's mounted from a read-only image and then binded over with keys. My changes wouldn't be kept.

Secondly, we'd have to create an iptables rule to allow our custom SSH port, 2222, seeing as per the firewall documentation only 22 is exposed by default. The same documentation recommends to have a service at boot.

My solution was to use cloud-config to on boot allow our custom port, unload the default ssh daemon and create our own service with the custom port.

#cloud-config

write_files:
- path: /etc/systemd/system/sshd-correct.service
  permissions: 0644
  owner: root
  content: |
    [Unit]
    Description=OpenSSH server daemon except custom port from Google
    After=syslog.target sshd.service network.target auditd.service

    [Service]
    ExecStartPre=/usr/bin/ssh-keygen -A
    ExecStart=/usr/sbin/sshd -D -e -p 2222
    ExecReload=/bin/kill -HUP $MAINPID

    [Install]
    WantedBy=multi-user.target

runcmd:
- systemctl daemon-reload
- systemctl stop sshd.service
- systemctl start sshd-correct.service

bootcmd:
- iptables -w -A INPUT -p tcp --dport 2222 -j ACCEPT

In your VM Instance's details, hit edit and go to Custom metadata. From there, you can copy and paste the above. Use the key name meta-data. A restart away, and tada: custom port!

Metadata edit screenshot