Pull YouTube Analytics Using Terraform (Terracurl)

Wale

Have you ever thought about using Terraform to pull YouTube Analytics data? Sounds a bit wild, right? But with the Terracurl provider, it’s not only possible, it’s actually a pretty fun experiment. In this blog post, I’ll walk you through the whole process of retrieving YouTube views, watch time, and subscriber data using Terraform.

Let’s dive in!

🎥 Prefer to watch instead of read? Check out the full video tutorial below:

📺 Watch the YouTube Video Tutorial (link coming soon)

Step 1: Set Up Terraform with the Terracurl Provider

Before we jump into the setup options, let’s take a moment to understand what Terracurl actually is.

Terracurl is a third-party Terraform provider that allows you to make raw HTTP requests within your Terraform configurations. It’s perfect for interacting with APIs that don’t have native Terraform support, like the YouTube Analytics API. Think of it as curl, but built into your Terraform workflows. You can use it to send GET, POST, PUT, or DELETE requests and handle responses directly inside your infrastructure code.

There are two ways to set up the Terracurl provider in your Terraform project. Choose the one that fits your preference:

We’ll begin by setting up the Terracurl provider using Terraform’s built-in provider registry. You can find the official provider documentation here: Terracurl on Terraform Registry. This allows Terraform to fetch and manage the provider for you.

Create a file called provider.tf and add the following:

terraform {
  required_providers {
    terracurl = {
      source = "devops-rob/terracurl"
      version = "1.2.2"
    }
  }
}

provider "terracurl" {}

Once you’ve saved the file, open your terminal and run:

terraform init

This will initialise your Terraform project and ensure the Terracurl provider is downloaded and ready to use.

Option B: Using the Provider’s Binary (Advanced)

If you’d like to try out a release candidate or prefer using the provider binary manually, you can set it up that way as well.

👉 Read the full blog post on setting up Terracurl via binary

This method is more advanced and great if you’re testing cutting-edge features or building custom provider integrations.

Step 2: Authenticate with Google Cloud

To call the YouTube Analytics API, we’ll need an OAuth2 access token.

Here’s how to get one easily using the OAuth2 Playground:

  1. Go to OAuth2 Playground
  2. Input your scopes:
https://www.googleapis.com/auth/yt-analytics.readonly
  1. Click Authorize APIs
  2. Click Exchange authorization code for tokens
  3. Copy the Access Token

Next, we need your YouTube channel ID. There are two ways to get it:

Option A: Use YouTube API Explorer

  1. Go to YouTube API Explorer
  2. Set part = id
  3. Set forHandle = your channel name (e.g. devcastops)
  4. Click Execute
  5. Copy your channel ID

Option B: Use Your Channel’s Profile Page

  1. Visit your channel (e.g. https://www.youtube.com/@devcastops)
  2. Click the More button in the channel description
  3. Click on Share Channel
  4. Then click Copy Channel ID

Step 3: Create the API Request in Terraform

Let’s use Terraform to call the YouTube Analytics API and get your metrics. We’ll be using the reports.query endpoint.

Here’s the Terraform configuration. Make sure to replace the default values for access_token and yt_channel_id with the ones you retrieved in Step 2. Save the configuration in a file called main.tf:

variable "access_token" {
  type        = string
  description = "The access token obtained from the OAuth 2.0 authorization flow."
  sensitive   = true
  default     = ""
}

variable "yt_channel_id" {
  type        = string
  description = "The YouTube channel ID."
  default     = ""
}

resource "terracurl_request" "youtube_analytics" {
  name   = "views_and_minutes_watched"
  url    = "https://youtubeanalytics.googleapis.com/v2/reports"
  method = "GET"
  headers = {
    Authorization = "Bearer ${var.access_token}"
  }

  response_codes = ["200"]

  request_parameters = {
    ids       = "channel==${var.yt_channel_id}"
    startDate = "2024-01-01"
    endDate   = "2025-03-31"
    metrics   = "views,estimatedMinutesWatched,subscribersGained"
  }
}

output "youtube_analytics_response" {
  value = terracurl_request.youtube_analytics.response
}

This configuration defines two variables (access_token and yt_channel_id) that you’ll supply at runtime. It then creates a terracurl_request resource that:

  • Authenticates with your access token using the Authorization header
  • Sends a GET request to the reports.query endpoint of the YouTube Analytics API
  • Requests metrics including views, estimated watch time, and subscribers gained for a specific date range
  • Outputs the API response directly to your terminal

📌 You can find sample request details in Google’s Docs.

Step 4: Run Terraform

Open your terminal and run:

terraform apply

When prompted, type yes to confirm and run the script.

Your terminal should output something like:

terracurl_request.youtube_analytics: Creation complete after 0s [id=views_and_minutes_watched]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

youtube_analytics_response = <<EOT
{
  "kind": "youtubeAnalytics#resultTable",
  "columnHeaders": [
    {
      "name": "views",
      "columnType": "METRIC",
      "dataType": "INTEGER"
    },
    {
      "name": "estimatedMinutesWatched",
      "columnType": "METRIC",
      "dataType": "INTEGER"
    },
    {
      "name": "subscribersGained",
      "columnType": "METRIC",
      "dataType": "INTEGER"
    }
  ],
  "rows": [
    [
      43,
      50,
      1
    ]
  ]
}

EOT

Pretty cool, right?

Let’s break down the output:

  • The columnHeaders section shows the names and data types of the metrics returned: views, estimatedMinutesWatched, and subscribersGained.
  • The rows array contains the actual data values. Each value corresponds to the column headers in order.

In this example:

  • 43 is the number of views
  • 50 is the estimated minutes watched
  • 1 is the number of subscribers gained

This data came directly from the YouTube Analytics API based on the date range you specified in the request. You can modify the startDate, endDate, or add additional parameters like dimensions=day to get more granular results.

Should You Use Terraform for This?

Honestly? Probably not for a production pipeline. There are better ways to handle YouTube analytics. But this was a fun and educational way to explore the newly released Terracurl provider and see just how versatile Terraform can be.

Thanks for reading and happy automating!