Skip to content

Deploy a Worker

Last reviewed: about 2 months ago

In this tutorial, you will follow step-by-step instructions to deploy a Hello World application using Cloudflare Workers and Pulumi infrastructure as code (IaC) to familiarize yourself with the resource management lifecycle. In particular, you will create a Worker, a Route, and a DNS Record to access the application before cleaning up all the resources.

Before you begin

Ensure you have:

  • A Cloudflare account and API Token with permission to edit the resources in this tutorial. If you need to, sign up for a Cloudflare account before continuing. Your token must have the following:
    • Account-Workers Scripts-Edit permission
    • Zone-Workers Route-Edit permission
    • Zone-DNS-Edit permission
  • A Pulumi Cloud account. You can sign up for an always-free individual tier.
  • The Pulumi CLI is installed on your machine.
  • A Pulumi-supported programming language configured. (TypeScript, JavaScript, Python, Go, .NET, Java, or use YAML)
  • A Cloudflare-managed domain. Complete the Add a site tutorial to bring your existing domain under Cloudflare.

1. Initialize your project

A Pulumi project is a collection of files in a dedicated folder that describes the infrastructure you want to create. The Pulumi project folder is identified by the required Pulumi.yaml file. You will use the Pulumi CLI to create and configure a new project.

a. Create a directory

Use a new and empty directory for this tutorial.

Terminal window
mkdir serverless-cloudflare
cd serverless-cloudflare

b. Login to Pulumi Cloud

Pulumi Cloud is a hosted service that provides a secure and scalable platform for managing your infrastructure as code. You will use it to store your Pulumi backend configurations.

At the prompt, press Enter to log into your Pulumi Cloud account via the browser. Alternatively, you may provide a Pulumi Cloud access token.

Terminal window
pulumi login

c. Create a new program

A Pulumi program is code written in a supported programming language that defines infrastructure resources.

To create a program, select your language of choice and run the pulumi command:

Terminal window
pulumi new javascript --name serverless-cloudflare --yes
# wait a few seconds while the project is initialized

d. Create a stack

A Pulumi stack is an instance of a Pulumi program. Stacks are independently configurable and may represent different environments (development, staging, production) or feature branches. For this tutorial, you’ll use the dev stack.

To instantiate your dev stack, run:

Terminal window
pulumi up --yes
# wait a few seconds for the stack to be instantiated.

You have not defined any resources at this point, so you’ll have an empty stack.

e. Save your application settings

In this step, you will store your application settings in a Pulumi ESC Environment, a YAML file containing configurations and secrets. These can be accessed in several ways, including a Pulumi program. All ESC Environments securely reside in your Pulumi Cloud account and can be fully managed via the Pulumi CLI. For this tutorial, you will store the following values:

  • Your Cloudflare account ID.
  • A valid Cloudflare API token.
  • A domain. For instance, example.com.
Terminal window
# Give your new ESC Environment a name
E=hello-world/dev-env
# Initialize the new ESC Environment
pulumi config env init --env $E --yes
Creating environment hello-world/dev-env for stack dev...
Terminal window
# Replace abc123 with your Cloudflare account ID
pulumi env set $E --plaintext pulumiConfig.accountId abc123
# Replace API_TOKEN with your Cloudflare API token
pulumi env set $E --secret pulumiConfig.cloudflare:apiToken API_TOKEN
# Replace example.com with your domain
pulumi env set $E --plaintext pulumiConfig.domain example.com

f. Install the Cloudflare package

You need to install the Cloudflare package for your language of choice in order to define Cloudflare resources in your Pulumi program.

Install the Cloudflare package by running the following command:

Terminal window
npm install @pulumi/cloudflare
added 1 package ...

2. Define Cloudflare resources in code

With the Cloudflare package installed, you can now define any supported Cloudflare resource in your Pulumi program. Next, define a Worker, a Route, and a DNS Record.

a. Add a Workers script

The Workers Script resource represents a Cloudflare Worker that can be deployed to the Cloudflare network.

Replace the contents of your entrypoint file with the following:

Filename: index.js

"use strict";
const pulumi = require("@pulumi/pulumi");
const cloudflare = require("@pulumi/cloudflare");
const config = new pulumi.Config();
const accountId = config.require("accountId");
const domain = config.require("domain");
const content = `export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response("Hello World!", options);
},
};`
const worker = new cloudflare.WorkersScript("hello-world-worker", {
accountId: accountId,
name: "hello-world-worker",
content: content,
module: true, // ES6 module
});

b. Add a Route

You will now add a Workers Route resource to your Pulumi program so the Workers script can have an endpoint and be active. To properly configure the Route, you will also look up the zone ID for your domain.

Add the following code snippet to your entrypoint file after the Worker script resource:

Filename: index.js

const zone = cloudflare.getZone({
accountId: accountId,
name: domain
});
const zoneId = zone.then(z => z.zoneId);
const route = new cloudflare.WorkersRoute("hello-world-route", {
zoneId: zoneId,
pattern: "hello-world." + domain,
scriptName: worker.name,
});

c. Add a DNS Record

You will now add a DNS Record resource to resolve the previously configured Route. In the next step, you’ll also output the Route URL so it can be easily accessed.

Add the following code snippet to your entrypoint file after the Route resource:

Filename: index.js

const record = new cloudflare.Record("hello-world-record", {
name: route.pattern,
type: "A",
content: "192.0.2.1",
zoneId: zoneId,
proxied: true
});
exports.url = pulumi.interpolate`https://${record.hostname}`

d. (Optional) Verify your code

Confirm all your changes match the full solution below:

Filename: index.js

"use strict";
const pulumi = require("@pulumi/pulumi");
const cloudflare = require("@pulumi/cloudflare");
const config = new pulumi.Config();
const accountId = config.require("accountId");
const domain = config.require("domain");
const content = `export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response("Hello World!", options);
},
};`
const worker = new cloudflare.WorkersScript("hello-world-worker", {
accountId: accountId,
name: "hello-world-worker",
content: content,
module: true, // ES6 module
});
const zone = cloudflare.getZone({
accountId: accountId,
name: domain
});
const zoneId = zone.then(z => z.zoneId);
const route = new cloudflare.WorkersRoute("hello-world-route", {
zoneId: zoneId,
pattern: "hello-world." + domain,
scriptName: worker.name,
});
const record = new cloudflare.Record("hello-world-record", {
name: route.pattern,
type: "A",
content: "192.0.2.1",
zoneId: zoneId,
proxied: true
});
exports.url = pulumi.interpolate`https://${record.hostname}`

3. Deploy your application

Now that you have defined all the Cloudflare resources, you can deploy the Hello World application to your Cloudflare account using the Pulumi CLI.

To deploy the changes, run:

Terminal window
pulumi up --yes
wait for the dev stack to become ready

4. Test the Worker

You incrementally added Cloudflare resources to run and access your Hello World application. You can test your application by curling the url output from the Pulumi stack.

Terminal window
curl $(pulumi stack output url)
Hello, World!

5. Clean up

In this last step, you will clean up the resources and stack used throughout the tutorial.

a. Delete the Cloudflare resources

Terminal window
pulumi destroy

b. Remove the Pulumi stack

Terminal window
pulumi stack rm dev

Next steps

Visit the Cloudflare package documentation to explore other resources you can define with Pulumi and Cloudflare.