Create a Spotify Playlist with Terraform

Truong, articles
Back

Check out the Spotify playlist that I built with Terraform for HashiCorp Summer of Learning!

https://open.spotify.com/playlist/04s6qErLUtCqJGF0vidKbL

Prerequisites

Terraform version 1.0+

Docker Desktop

Spotify account with developer access

Prepare Code

main.tf

terraform {
  required_providers {
    spotify = {
      version = "~> 0.1.5"
      source  = "conradludgate/spotify"
    }
  }
}

variable "spotify_api_key" {
  type = string
}

provider "spotify" {
  api_key = var.spotify_api_key
}

resource "spotify_playlist" "playlist" {
  name        = "Terraform Summer Playlist"
  description = "This playlist was created by Terraform"
  public      = true

  tracks = [
    data.spotify_search_track.by_artist.tracks[0].id,
    data.spotify_search_track.by_artist.tracks[1].id,
    data.spotify_search_track.by_artist.tracks[2].id,
  ]
}

data "spotify_search_track" "by_artist" {
  artists = ["Ed Sheeran"]
  #  album = "‎÷ (Deluxe)"
  #  name  = "Perfect"
}

output "tracks" {
  value = data.spotify_search_track.by_artist.tracks
}

terraform.tfvars

spotify_api_key = "..."

.env

SPOTIFY_CLIENT_ID=
SPOTIFY_CLIENT_SECRET=

.gitignore

# Local .terraform directories
**/.terraform/*

# .tfstate files
*.tfstate
*.tfstate.*

# Crash log files
crash.log

# Ignore any .tfvars files that are generated automatically for each Terraform run. Most
# .tfvars files are managed as part of configuration and so should be included in
# version control.
#
# example.tfvars

# Ignore override files as they are usually used to override resources locally and so
# are not checked in
override.tf
override.tf.json
*_override.tf
*_override.tf.json

# Include override files you do wish to add to version control using negated pattern
#
# !example_override.tf

# Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan
# example: *tfplan*

Install the Spotify provider

In your terminal, initialize Terraform, which will install the Spotify provider.

Make sure you already installed Terraform. If not you click on this link to follow this guide.

$ terraform init

Create the playlist

Now you are ready to create your playlist. Apply your Terraform configuration. Terraform will show you the changes it plans to make and prompt for your approval.

$ terraform apply

Follow this tutorial to build your own. https://hashi.co/terraform-spotify-playlist

© TruongIdeas & Feedback