All Articles

Setup Netlify by Terraform

Well, it is quite obvious that I use Netlify for deploying this blog. The most important reason why I choose Netlify is that it provides support for Terraform.

By using Terraform, you can manage the infrastructure through the codes which makes life of developers easiler from a long term perspective. However, the first step of conducting Infrastructure as Code (IaC) sometimes struggles.

So I share my own setting for building a site in Netlify by using Terraform as an example. I wish it could be helpful for people who want to have a try on IaC.

provider.tf

Setup Terraform provider of Netlify and Github

variable "netlify_token" {}

provider "netlify" {
  token = var.netlify_token
}

variable "github_owner" {}
variable "github_token" {}

provider "github" {
  owner = var.github_owner
  token = var.github_token
}

If you use a non-organization of Github, please setup owner in the provider of Github. The variables can be passed by environment variables with prefix of TF_VAR_. For example, the variable of github_owner in .tf file can be set as the same as the environment variable named TF_VAR_github_owner. (Please be careful on the management of tokens!)

main.tf

Build a site and create a deploy key in Netlify and then add the deploy key to the blog repository in Github

resource "netlify_deploy_key" "key" {}

resource "netlify_site" "main" {
  name = "myportal"

  repo {
    repo_branch   = "deployment"
    command       = "gatsby build"
    deploy_key_id = netlify_deploy_key.key.id
    dir           = "/public"
    provider      = "github"
    repo_path     = data.github_repository.repo.full_name
  }
}

data "github_repository" "repo" {
  full_name = "username/repository_name"
}

resource "github_repository_deploy_key" "key" {
  title      = "Netlify"
  repository = data.github_repository.repo.name
  key        = netlify_deploy_key.key.public_key
  read_only  = true
}

The deploy key is necessary while Netlify to checkout the codes of blog from github. Therefore, the deploy key itself is generated in Netlify and the its public key is registered as deploy key in Github.

For the setting of repository branch, I intentionally set the branch as deployment rather than master. Because I want to make branches meaningful as followings. If the name of branch master is sensitive to you, please select other names.

  • master branch: working in progress posts
  • deployment branch: published posts

The name of netlify site (in this example, myportal) will decide the domain of site (for this case, myportal.netlify.app) given by Netlify automatically. If you have no plan to setup your own domain, please give your site a good name at least.