How to user droplet UserData to change sshd_config

I’m trying the following code to change the IP ssh listens to. Unfortunately this doesn’t work as I can’t successfully connect after droplet is created.

Tested in an existing dropley with su privileges it works. I’m creating a droplet from an image where su only have access after authentication. Does it have any connection?

I’m trying this on a Debian 8.

#!/bin/bash apt-get update export PRIVATE_IPV4=$(curl -s sed -i “s/.ListenAddress./ListenAddress $PRIVATE_IPV4 /g” /etc/ssh/sshd_config ssh restart

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

Hi Thanks for answering. Indeed, my sed command was replacing both lines. But that is not an issue to log in to ssh, after I manually give a reset cycle from dashboard.

The problem is that ssh restart doesn’t do anything. I assume this is because in the image I’m building from I removed root access, and the other 2 users have not access to run commands without password.

I also added

  mode: reboot

with no success


You should be able to use something such as:

sed -i "0,/ListenAddress.*/c\ListenAddress $PRIVATEIPV4" /etc/ssh/sshd_config

Since there’s two instances of ListenAddress in the default Debian sshd_config file, when you run your sed, it actually modifies both instances as the s/ and /g matches all instances, not just one.

By default, you’ll see:

#ListenAddress ::

When running your sed replacement, you end up with:

ListenAddress PRIVATE_IP ::
ListenAddress PRIVATE_IP

Where PRIVATE_IP is your Droplet Private IP.

When running the command I’ve provided, it’ll only modify the first instance and it’ll remove the line entirely and replace it with just:

ListenAddress PRIVATE_IP

That said, unless you’re connecting over a VPN, you won’t be able to connect to SSH using the Private IP, so if you plan on connecting sans VPN, you’d need to change that to the public IP.