My friends and I decided we were going to give Valheim, an early-access survival game, a try. Since many of us are parents now and we’re in a socially distancing world, colocating for an evening of fun was out of the question. I decided to use the event as an excuse to practice my DevOps skills.
I use Terraform at work for a variety of things, but I don’t write enough of it to be completely comfortable. As such, I decided to use Terraform to provision a dedicated server for us. This article documents how I went about it using DigitalOcean and Terraform.
Create an SSH key
When provisioning cloud servers, SSH is your best friend. When you need to perform any maintenance on the server, you will need SSH to connect to it. Since this is a single-purpose machine that we’ll be provisioning, let’s create a single-purpose SSH key to go with it.
This command generates an elliptic curve SSH key that we will use to connect to the server. It uses an empty passphrase since its only purpose is to connect to this throwaway server. We will use the DigitalOcean API to upload this key to them for use with our server.
Configure the Terraform provider
First, you will need to create an API token on DigitalOcean. You’ll want to keep this in a safe place because once you generate it you will not be able to see the token again. Once you have it, you’ll want to set it as an environment variable. I use direnv for this purpose and, as such, put the environment variable in a
.envrc file in my project. That looks like the following:
Once you have that environment variable set, you can use the DigitalOcean Terraform provider. To configure Terraform to use that provider, you will need to specify it as a required provider1 like so:
And then declare it as a provider:
I like to add that comment in the provider block to state where its credentials come from; it’s not necessary. For those of you following at home, you can place all of the configuration in a single
.tf file or design your own scheme for organizing your blocks.
To install the provider, initialize Terraform with:
Set up the SSH key
The first resource we need to create is the SSH key. This is because DigitalOcean creates the server from an image that uses cloud-init to set default SSH keys for the root user. Without it, the other commands won’t work.
To create the SSH key resource, we specify it like so:
This takes the file on our local machine located at
~/.ssh/id_valheim.pub and uploads it as an SSH key to DigitalOcean. If you chose to name your key something different in the previous step, use that filename here. The name shows up in DigitalOcean’s security settings to help you identify it later. Pick something memorable.
Create the server
Once we have the provider set up, we can write a recipe to provision the server. First, we have to set up the SSH key that we generated in the last step
For our purposes, a bit of anecdotal research showed that others successfully run a four-person server on a 2 CPU / 4 GiB server. This is a standard server size from DigitalOcean called
s-2vcpu-4b. With that knowledge, we can write the following resource:
The image here is the latest Ubuntu LTS at the time of this writing. The name helps to identify your droplet in DigitalOcean’s cloud console. In my case, three of the four of us were playing from Ohio so I picked the New York City 1 data center (or region). Setting the monitoring flag to true enables DigitalOcean’s new agent-based resource monitoring that is more fine-grained than the default. I prefer it to their older metrics. The tags are a way to keep your droplets organized in the cloud console.
The most important field here is the
ssh_keys field. This takes the SSH key that we uploaded in the previous resource and links it to the droplet so that we can log into the droplet via SSH. Without it, DigitalOcean will email you a root password, but that is incompatible with the rest of the Terraform configuration.
Configure the server
I very much label this section as caveat lector, reader beware. Because I am treating this server as a “create it and delete it later” server, I am using a Terraform provisioner to provision the box. As stated in the documentation, Hashicorp only intends you to use these provisioners as a last resort. If this were for a mission-critical system, I would probably use Packer to build an image and deploy it instead. But that’s a little too heavy for my current task, so here we are.
There are three steps that we will perform. First, we’ll create some necessary directories and attempt to temporarily disable the automated updates for Ubuntu Server. Next, we’ll upload some configuration files to the server. Lastly, we’ll install Docker and start the Valheim service.
Create necessary directories
Running simple scripts in the Terraform provisioner is simple. The
remote-exec provisioner generates a script file and runs it with the shell. We’ll use this functionality for the first step:
The first line is a hack that attempts to beat a race condition between the provisioning scripts and the Ubuntu automatic updates service. If the automatic update occurs just before any of our calls to Apt, we won’t be able to obtain the lock on the repositories and package caches and our scripts will fail. So we use
sed to disable the automatic upgrades service, then create two directories.
The first directory,
/opt/valheim, will contain our game data. The second contains an environment file for the Systemd unit we will use to manage the server process.
The connection block configures the SSH connection that we use to run the provisioner. This will be in each of the provisioner blocks that follow, as I don’t think there is a way to share connection information between provisioner blocks without something like Terragrunt. The block says “create an SSH connect using the root user at the IPv4 address that we just created and use the
Now that we have the basics, we can upload a Systemd service unit and its accompanying environment file. This takes two blocks, one for each file.
Upload Systemd unit
To upload the Systemd unit that manages the Valheim server, we can add this provisioner to the droplet resource:
The file provisioner takes a local file (or content string) and uploads it as a file to the resource. In this case, it takes the Systemd unit below, which we store in
conf/valheim-server.service at the root of our Terraform project.
This is the default Systemd unit for the Docker container we use to run the server. It reads environment variables from an environment file that we’ll upload next and starts the Docker container with them. Running through line-by-line:
-v /opt/valheim:/config:Zmounts our game data directory as a volume as an unshared bind-mount within the container
-p 2456-2458:2456-2458/udpforwards the default game ports from the host to the container
-e SERVER_NAMEwill configure the name of the server within Valheim
-e SERVER_PORTsets the first port that Valheim listens on
-e WORLD_NAMEsets the name of the world file for your identification
-e SERVER_PASSsets the password to enter the server, which must be 5+ characters according to the manual
-e SERVER_PUBLICis a boolean flag for whether the server should show up in the public server list
-e --dnslines set the DNS servers that the container should use
lloesche/valheim-serveris the name of the container image to run
The rest of the unit file attempts to ensure the container is the only copy running and tells the unit to load the environment file that we upload next.
Upload environment file
The second file provisioner uploads the environment file that configures the Systemd unit:
This reads a configuration file template (shown below) from the
conf/valheim-server.conf.tpl file at the root of your Terraform project and inserts some Terraform variables. To enable the variables, we need three variable blocks in our Terraform file:
You can set these as environment variables with the pattern
TF_VAR_<variable>, which I recommend doing in your
.envrc file if you use
The template itself looks like:
These are the environment variables that you see referenced above in the System unit.
Now that we have all of that on the server, it’s time to install Docker and start the service!
Install Docker and start Valheim
This section is the longest part of provisioning the server because it does several things. First, Docker is not available from the default Ubuntu repositories so we have to add its repository and configuration, which takes a few commands. Then, we need to install Docker. Finally, we enable the Valheim service and re-enable the automatic upgrade system.
We do this with the following provisioner block:
Dissecting this line-by-line, we see the following:
apt-get update [...] gnupg-agentinstalls the prerequisites for adding the Docker repository in a headless way so we aren’t prompted for input
curl [...] | apt-key add -adds the Docker GPG key to the Apt keychain
echo [...] > /etc/apt/sources.list.d/docker.listadds the Docker repository to Apt
apt-get update [...] containerd.ioinstalls Docker, again in a headless way
systemctl daemon-reloadensures that Systemd has a reference to our new Docker service
systemctl enable --now valheim-server.serviceenables the Valheim server, which makes it start up upon reboot, and starts the server now
sed [...]re-enables Ubuntu’s automatic updates
Once this provisioner finishes, Terraform finalizes its actions. We’ll have a Valheim server running in approximately four minutes! To connect, put in the IP address of your droplet with the port
One of the ways that I improved my skills as both a developer and systems operator was through running private services for my friends and me, like video game servers. This article shared a pared-down version of the DevOps setup I used for setting up a dedicated Valheim server. Using a single local tool, Terraform, we were able to go from nothing to a fully functioning server running on DigitalOcean.
Granted, this simple setup skips a larger step in provisioning and uses a hack to try to beat the race against Ubuntu’s auto-updates. Converting those steps to a repeatable process was beyond the scope of what I wanted to do, but there are many ways to do so with a variety of different tools. As an exercise, see what you can come up with!
If you’re interested in seeing my full setup using CloudFlare for DNS and DigitalOcean firewalls, you can find it on GitHub. Also, you can sign up for DigitalOcean and receive a $100 credit for 60 days so you can test this for free2.
Do you ever use your leisure time for things like this? Have you ever used a cloud provider to host a game server?
As of this writing, I am using Terraform v0.14. It and its prior version, v0.13, require different provider setup than prior versions. To check which version you’re using, run
terraform -version. ↩
Full disclosure: that link is a referral link. If you sign up and spend $25, I will receive a $25 credit. If you’d prefer not to participate in that referral, here is a link without referral. ↩