| [ Web Proxy ] |
| Viewing: https://developers.cloudflare.com/pulumi/tutorial/hello-world/ | [Back] [Original] |
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.
Note
You will provision resources that qualify under free tier offerings for both Pulumi Cloud and Cloudflare.
Ensure you have:
Account-Workers Scripts-Edit permissionZone-Workers Route-Edit permissionZone-DNS-Edit permissionA 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.
Use a new and empty directory for this tutorial.
mkdir serverless-cloudflare
cd serverless-cloudflare
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 .
pulumi login
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:
pulumi new javascript --name serverless-cloudflare --yes
# wait a few seconds while the project is initializedpulumi new typescript --name serverless-cloudflare --yes
# wait a few seconds while the project is initializedpulumi new python --name serverless-cloudflare --yes
# wait a few seconds while the project is initializedpulumi new go --name serverless-cloudflare --yes
# wait a few seconds while the project is initializedpulumi new java --name serverless-cloudflare --yes
# wait a few seconds while the project is initializedpulumi new csharp --name serverless-cloudflare --yes
# wait a few seconds while the project is initializedpulumi new yaml --name serverless-cloudflare --yesA 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:
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.
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:
example.com.# 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...
# 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
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:
npm install @pulumi/cloudflareadded 1 package ...npm install @pulumi/cloudflareadded 1 package ...echo "pulumi_cloudflare>=5.38,<6.0.0" >> requirements.txt
source venv/bin/activate
pip install -r requirements.txt...Collecting pulumi-cloudflare...go get github.com/pulumi/pulumi-cloudflare/sdk/v3/go/cloudflarego: downloading github.com/pulumi/pulumi-cloudflare ...Below are Apache Maven instructions. For other Java project managers such as Gradle, see the official Maven repository
pom.xml file.<dependencies> section.<dependency>
<groupId>com.pulumi</groupId>
<artifactId>cloudflare</artifactId>
<version>5.38.0</version>
</dependency>mvn clean install...[INFO] BUILD SUCCESS...dotnet add package Pulumi.Cloudflare...
info : Adding PackageReference for package 'Pulumi.Cloudflare' into project
...There are no dependencies to download for YAML. Skip ahead.
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.
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
});Filename: index.ts
import * as pulumi from "@pulumi/pulumi";
import * as cloudflare from "@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
});Filename: __main__.py
"""Pulumi program """
import pulumi
import pulumi_cloudflare as cloudflare
CONFIG = pulumi.Config()
ACCOUNT_ID = CONFIG.get("accountId")
DOMAIN = CONFIG.require("domain")
CONTENT = """
export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response("Hello World!", options);
},
};
"""
worker = cloudflare.WorkersScript("hello-world-worker",
account_id=ACCOUNT_ID,
name="hello-world-worker",
content=CONTENT,
module=True # ES6 module
)Filename: main.go
package main
import (
"github.com/pulumi/pulumi-cloudflare/sdk/v5/go/cloudflare"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi/config"
)
func main() {
pulumi.Run(func(ctx *pulumi.Context) error {
conf := config.New(ctx, "")
accountID := conf.Get("accountId")
domain := conf.Get("domain")
content := `
export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response("Hello World!", options);
},
};
`
worker, err := cloudflare.NewWorkersScript(ctx, "hello-world-worker", &cloudflare.WorkersScriptArgs{
AccountId: pulumi.String(accountID),
Name: pulumi.String("hello-world-worker"),
Content: pulumi.String(content),
Module: pulumi.Bool(true), // ES6 module
})
if err != nil {
return err
}
return nil
})
}Filename: src/main/java/myproject/App.java
package myproject;
import com.pulumi.Pulumi;
import com.pulumi.cloudflare.WorkersScript;
import com.pulumi.cloudflare.WorkersScriptArgs;
import com.pulumi.core.Output;
public class App {
public static void main(String[] args) {
Pulumi.run(ctx -> {
var content = """
export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response("Hello World!", options);
},
};
""";
var accountId = ctx.config().require("accountId");
var domain = ctx.config().require("domain");
var worker = new WorkersScript("hello-world-worker", WorkersScriptArgs.builder()
.accountId(accountId)
.name("hello-world-worker")
.content(content)
.module(true)
.build());
return;
});
}
}Filename: Program.cs
using Pulumi;
using Cloudflare = Pulumi.Cloudflare;
return await Deployment.RunAsync(() =>
{
var config = new Config();
var accountId = config.Require("accountId");
var domain = config.Require("domain");
var content = @"
export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response(""Hello World!"", options);
},
};
";
var worker = new Cloudflare.WorkersScript("hello-world-worker", new()
{
AccountId = accountId,
Name = "hello-world-worker",
Content = content,
Module = true
});
return;
});Filename: Pulumi.yaml
name: serverless-cloudflare
runtime: yaml
resources:
worker:
type: cloudflare:WorkersScript
properties:
accountId: "${accountId}"
name: "hello-world-worker"
content: |
export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response("Hello World!", options);
},
};
module: trueYou 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,
});Filename: index.ts
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,
});Filename: __main__.py
zone = cloudflare.get_zone(account_id=ACCOUNT_ID, name=DOMAIN)
zone_id = zone.zone_id
route = cloudflare.WorkersRoute("hello-world-route",
zone_id=zone_id,
pattern="hello-world." + DOMAIN,
script_name=worker.name
)Filename: main.go
zone, err := cloudflare.LookupZone(ctx, &cloudflare.LookupZoneArgs{
AccountId: &accountID,
Name: &domain,
}, nil)
if err != nil {
return err
}
route, err := cloudflare.NewWorkersRoute(ctx, "hello-world-route", &cloudflare.WorkersRouteArgs{
ZoneId: pulumi.String(zone.Id),
Pattern: pulumi.String("hello-world." + domain),
ScriptName: worker.Name,
})
if err != nil {
return err
}Filename: src/main/java/myproject/App.java
final var zone = CloudflareFunctions.getZone(GetZoneArgs.builder()
.accountId(accountId)
.name(domain)
.build());
var route = new WorkersRoute("hello-world-route", WorkersRouteArgs.builder()
.zoneId(zone.applyValue(getZoneResult -> getZoneResult.id()))
.pattern("hello-world." + domain)
.scriptName(worker.name())
.build());Filename: Program.cs
var zone = Output.Create(Cloudflare.GetZone.InvokeAsync(new()
{
AccountId = accountId,
Name = domain,
}));
var route = new Cloudflare.WorkersRoute("hello-world-route", new()
{
ZoneId = zone.Apply(z => z.Id),
Pattern = "hello-world." + domain,
ScriptName = worker.Name,
});Filename: Pulumi.yaml
Below the runtime key, add the following code:
# new top-level section
variables:
zone:
fn::invoke:
function: cloudflare:getZone
arguments:
accountId: ${accountId}
name: ${domain}Below the worker resource, add the following code:
route:
type: cloudflare:WorkersRoute
properties:
zoneId: ${zone.id}
pattern: "hello-world.${domain}"
scriptName: ${worker.name}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}`;Filename: index.ts
const record = new cloudflare.Record("hello-world-record", {
name: route.pattern,
type: "A",
content: "192.0.2.1",
zoneId: zoneId,
proxied: true,
});
export const url = pulumi.interpolate`https://${record.hostname}`;Filename: __main__.py
record = cloudflare.Record("hello-world-record",
name=route.pattern,
type="A",
content="192.0.2.1",
zone_id=zone_id,
proxied=True
)
url = pulumi.Output.concat("https://", record.hostname)
pulumi.export('url', url)Filename: main.go
record, err := cloudflare.NewRecord(ctx, "hello-world-record", &cloudflare.RecordArgs{
Name: route.Pattern,
Type: pulumi.String("A"),
Content: pulumi.String("192.0.2.1"),
ZoneId: pulumi.String(zone.Id),
Proxied: pulumi.Bool(true),
})
if err != nil {
return err
}
ctx.Export("url", pulumi.Sprintf("https://%s", record.Hostname))Filename: src/main/java/myproject/App.java
var record = new Record("hello-world-record", RecordArgs.builder()
.name(route.pattern())
.type("A")
.content("192.0.2.1")
.zoneId(zone.applyValue(getZoneResult -> getZoneResult.id()))
.proxied(true)
.build());
ctx.export("url", Output.format("https://%s", record.hostname()));Filename: Program.cs
Notice the updated ' return ' statement because you're now exporting a value. Ensure that you also include using System.Collections.Generic; in your imports.
var record = new Cloudflare.Record("hello-world-record", new()
{
Name = route.Pattern,
Type = "A",
Content = "192.0.2.1",
ZoneId = zone.Apply(z => z.Id),
Proxied = true
});
return new Dictionary<string, object?>
{
["url"] = Output.Format($"https://{record.Hostname}")
};Notice the new top-level outputs section.
record:
type: cloudflare:Record
properties:
name: ${route.pattern}
type: A
content: "192.0.2.1"
zoneId: ${zone.id}
proxied: true
outputs:
url: "https://${record.hostname}"Note
You may need to use http instead depending on your domain settings.
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}`;Filename: index.ts
import * as pulumi from "@pulumi/pulumi";
import * as cloudflare from "@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,
});
export const url = pulumi.interpolate`https://${record.hostname}`;Filename: __main__.py
"""Pulumi program """
import pulumi
import pulumi_cloudflare as cloudflare
CONFIG = pulumi.Config()
ACCOUNT_ID = CONFIG.get("accountId")
DOMAIN = CONFIG.require("domain")
CONTENT = """
export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response("Hello World!", options);
},
};
"""
worker = cloudflare.WorkersScript("hello-world-worker",
account_id=ACCOUNT_ID,
name="hello-world-worker",
content=CONTENT,
module=True # ES6 module
)
zone = cloudflare.get_zone(account_id=ACCOUNT_ID, name=DOMAIN)
zone_id = zone.zone_id
route = cloudflare.WorkersRoute("hello-world-route",
zone_id=zone_id,
pattern="hello-world." + DOMAIN,
script_name=worker.name
)
record = cloudflare.Record("hello-world-record",
name=route.pattern,
type="A",
content="192.0.2.1",
zone_id=zone_id,
proxied=True
)
url = pulumi.Output.concat("https://", record.hostname)
pulumi.export('url', url)Filename: main.go
package main
import (
"github.com/pulumi/pulumi-cloudflare/sdk/v5/go/cloudflare"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi/config"
)
func main() {
pulumi.Run(func(ctx *pulumi.Context) error {
conf := config.New(ctx, "")
accountID := conf.Get("accountId")
domain := conf.Get("domain")
content := `
export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response("Hello World!", options);
},
};
`
worker, err := cloudflare.NewWorkersScript(ctx, "hello-world-worker", &cloudflare.WorkersScriptArgs{
AccountId: pulumi.String(accountID),
Name: pulumi.String("hello-world-worker"),
Content: pulumi.String(content),
Module: pulumi.Bool(true), // ES6 module
})
if err != nil {
return err
}
zone, err := cloudflare.LookupZone(ctx, &cloudflare.LookupZoneArgs{
AccountId: &accountID,
Name: &domain,
}, nil)
if err != nil {
return err
}
route, err := cloudflare.NewWorkersRoute(ctx, "hello-world-route", &cloudflare.WorkersRouteArgs{
ZoneId: pulumi.String(zone.Id),
Pattern: pulumi.String("hello-world." + domain),
ScriptName: worker.Name,
})
if err != nil {
return err
}
record, err := cloudflare.NewRecord(ctx, "hello-world-record", &cloudflare.RecordArgs{
Name: route.Pattern,
Type: pulumi.String("A"),
Content: pulumi.String("192.0.2.1"),
ZoneId: pulumi.String(zone.Id),
Proxied: pulumi.Bool(true),
})
if err != nil {
return err
}
ctx.Export("url", pulumi.Sprintf("https://%s", record.Hostname))
return nil
})
}Filename: src/main/java/myproject/App.java
package myproject;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.cloudflare.WorkersScript;
import com.pulumi.cloudflare.WorkersScriptArgs;
import com.pulumi.cloudflare.CloudflareFunctions;
import com.pulumi.cloudflare.inputs.GetZoneArgs;
import com.pulumi.cloudflare.WorkersRoute;
import com.pulumi.cloudflare.WorkersRouteArgs;
import com.pulumi.cloudflare.Record;
import com.pulumi.cloudflare.RecordArgs;
public class App {
public static void main(String[] args) {
Pulumi.run(ctx -> {
var content = """
export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response("Hello World!", options);
},
};
""";
var accountId = ctx.config().require("accountId");
var domain = ctx.config().require("domain");
var worker = new WorkersScript("hello-world-worker", WorkersScriptArgs.builder()
.accountId(accountId)
.name("hello-world-worker")
.content(content)
.module(true)
.build());
final var zone = CloudflareFunctions.getZone(GetZoneArgs.builder()
.accountId(accountId)
.name(domain)
.build());
var route = new WorkersRoute("hello-world-route", WorkersRouteArgs.builder()
.zoneId(zone.applyValue(getZoneResult -> getZoneResult.id()))
.pattern("hello-world." + domain)
.scriptName(worker.name())
.build());
var record = new Record("hello-world-record", RecordArgs.builder()
.name(route.pattern())
.type("A")
.content("192.0.2.1")
.zoneId(zone.applyValue(getZoneResult -> getZoneResult.id()))
.proxied(true)
.build());
ctx.export("url", Output.format("https://%s", record.hostname()));
return;
});
}
}Filename: Program.cs
using System.Collections.Generic;
using Pulumi;
using Cloudflare = Pulumi.Cloudflare;
return await Deployment.RunAsync(() =>
{
var config = new Config();
var accountId = config.Require("accountId");
var domain = config.Require("domain");
var content = @"
export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response(""Hello World!"", options);
},
};
";
var worker = new Cloudflare.WorkersScript("hello-world-worker", new()
{
AccountId = accountId,
Name = "hello-world-worker",
Content = content,
Module = true
});
var zone = Output.Create(Cloudflare.GetZone.InvokeAsync(new()
{
AccountId = accountId,
Name = domain,
}));
var route = new Cloudflare.WorkersRoute("hello-world-route", new()
{
ZoneId = zone.Apply(z => z.Id),
Pattern = "hello-world." + domain,
ScriptName = worker.Name,
});
var record = new Cloudflare.Record("hello-world-record", new()
{
Name = route.Pattern,
Type = "A",
Content = "192.0.2.1",
ZoneId = zone.Apply(z => z.Id),
Proxied = true
});
return new Dictionary<string, object?>
{
["url"] = Output.Format($"https://{record.Hostname}")
};
});Filename: Pulumi.yaml
name: serverless-cloudflare
runtime: yaml
variables:
zone:
fn::invoke:
function: cloudflare:getZone
arguments:
accountId: ${accountId}
name: ${domain}
resources:
worker:
type: cloudflare:WorkersScript
properties:
accountId: "${accountId}"
name: "hello-world-worker"
content: |
export default {
async fetch(request) {
const options = { headers: { 'content-type': 'text/plain' } };
return new Response("Hello World!", options);
},
};
module: true
route:
type: cloudflare:WorkersRoute
properties:
zoneId: ${zone.id}
pattern: "hello-world.${domain}"
scriptName: ${worker.name}
record:
type: cloudflare:Record
properties:
name: ${route.pattern}
type: A
content: "192.0.2.1"
zoneId: ${zone.id}
proxied: true
outputs:
url: "https://${record.hostname}"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:
pulumi up --yes
wait for the dev stack to become ready
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.
curl $(pulumi stack output url)
Hello, World!
In this last step, you will clean up the resources and stack used throughout the tutorial.
pulumi destroy
pulumi stack rm dev
Visit the Cloudflare package documentation to explore other resources you can define with Pulumi and Cloudflare.
| Web Proxy Viewer | New URL | Original Page |