DevCEDTeam / CED

0 stars 0 forks source link

Cloudflare Terraform Step by Step #161

Open DevCEDTeam opened 1 month ago

DevCEDTeam commented 1 month ago

The text extraction was partial and some content was missed or incomplete. I'll now provide the complete step-by-step instructions based on the context, ensuring it is formatted correctly for GitHub and includes sample code that you can easily cut and paste.


Cloudflare Terraform Setup Step-by-Step

This guide walks you through setting up Terraform with Cloudflare, including automated testing with Terratest. The instructions are designed for use in a GitHub repository or Markdown file, with code blocks that are easy to copy and paste.


1. Install Terraform on Ubuntu (or Windows using WSL)

Install Dependencies:

sudo apt update
sudo apt install -y software-properties-common gnupg2 curl

Import the Hashicorp GPG Key:

curl https://apt.releases.hashicorp.com/gpg | gpg --dearmor > hashicorp.gpg
sudo install -o root -g root -m 644 hashicorp.gpg /etc/apt/trusted.gpg.d/

Add the Hashicorp Repository:

sudo apt-add-repository "deb [arch=$(dpkg --print-architecture)] https://apt.releases.hashicorp.com $(lsb_release -cs) main"

Install Terraform:

sudo apt update
sudo apt install -y terraform

Verify Terraform Installation:

terraform --version

Ensure it's the correct version (e.g., v1.4.0 or higher).


2. Create Your First Terraform Configuration for Cloudflare

Create a Terraform Configuration File (e.g., cloudflare.tf):

terraform {
  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 3.0"
    }
  }
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token
}

resource "cloudflare_record" "www" {
  name    = "www"
  value   = "1.1.1.1"
  zone_id = "your_zone_id"
  type    = "A"
}

resource "cloudflare_page_rule" "www" {
  target = "yoursite.example.com/*"
  actions {
    always_use_https = true
  }
}

This configuration sets up:


3. Configure Your .editorconfig (Optional)

For consistent coding style, create a file called .editorconfig and add the following content:

root = true

[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

This ensures consistent indentation and formatting across your project.


4. Initialize Terraform

Run the following command to initialize Terraform and download the necessary plugins:

terraform init

5. Review and Apply Configuration

To review the planned changes:

terraform plan

To apply the changes:

terraform apply

This will deploy the DNS records and page rules to your Cloudflare account.


6. Verify Changes in Cloudflare

You can verify that the DNS records and page rules have been created by checking the Cloudflare dashboard.

To test the DNS records using nslookup:

nslookup yoursite.example.com

7. Import Existing Cloudflare State into Terraform

Install cf-terraforming:

curl -L https://github.com/cloudflare/cf-terraforming/releases/download/v0.11.0/cf-terraforming_0.11.0_linux_amd64.tar.gz -o cf-terraforming.tar.gz
tar -xzf cf-terraforming.tar.gz
sudo mv ./cf-terraforming /usr/local/bin
sudo chmod +x /usr/local/bin/cf-terraforming

Export Cloudflare State to a File:

export CLOUDFLARE_API_TOKEN='your_api_token'
export CLOUDFLARE_ZONE_ID='your_zone_id'
cf-terraforming generate --resource-type "cloudflare_record" --zone $CLOUDFLARE_ZONE_ID > imported.tf

Import Resources into Terraform:

cf-terraforming import --resource-type "cloudflare_record" --zone $CLOUDFLARE_ZONE_ID

8. Configure Remote State with Terraform Cloud

Add the Following Block to cloudflare.tf:

terraform {
  cloud {
    hostname     = "app.terraform.io"
    organization = "your_organization"
    workspaces {
      name = "Cloudflare"
    }
  }
  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 3.0"
    }
  }
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token
}

Run terraform init to Connect to Terraform Cloud:

terraform init

This will connect your project to Terraform Cloud for remote state management.


9. Finalize State Management

Once you have synced your state with Cloudflare, run:

terraform plan
terraform apply

This will ensure that your local state is up-to-date with the resources in Cloudflare.


Automated Testing with Terratest

1. Install Go and Terratest

Ensure you have Go installed, then install the required modules:

go mod init your-repo
go get github.com/gruntwork-io/terratest/modules/terraform
go get github.com/stretchr/testify/assert

2. Create a Terratest File (terraform_test.go):

package test

import (
    "testing"
    "github.com/gruntwork-io/terratest/modules/terraform"
    "github.com/stretchr/testify/assert"
)

func TestTerraformCloudflare(t *testing.T) {
    terraformOptions := &terraform.Options{
        TerraformDir: "../terraform", // Adjust path if needed
    }

    defer terraform.Destroy(t, terraformOptions)

    terraform.InitAndApply(t, terraformOptions)

    dnsRecord := terraform.Output(t, terraformOptions, "cloudflare_record")
    pageRule := terraform.Output(t, terraformOptions, "cloudflare_page_rule")

    assert.NotEmpty(t, dnsRecord, "DNS record output should not be empty")
    assert.NotEmpty(t, pageRule, "Page rule output should not be empty")
}

3. Configure Terraform Outputs

In your cloudflare.tf, add these output blocks to expose the values for testing:

output "cloudflare_record" {
  value = cloudflare_record.www.name
}

output "cloudflare_page_rule" {
  value = cloudflare_page_rule.www.target
}

4. Run Terratest

Run the test using the following command:

go test -v

This will:

  1. Initialize and apply the Terraform configuration.
  2. Verify that the DNS record and page rule exist.
  3. Clean up by destroying the resources after the test completes.

Terratest Enhancements


These instructions are now complete and formatted for GitHub or any other Markdown viewer. You can easily copy and paste the sample code as needed.


a. Would you like me to assist with integrating these tests into a CI/CD pipeline (like GitHub Actions)?
b. Do you need help with testing more advanced Cloudflare resources, such as Load Balancers or Workers?