Coder Social home page Coder Social logo

cloudflare / wrangler-action Goto Github PK

View Code? Open in Web Editor NEW
1.0K 14.0 139.0 21.72 MB

πŸ§™β€β™€οΈ easily deploy cloudflare workers applications using wrangler and github actions

License: Apache License 2.0

TypeScript 100.00%
cloudflare cloudflare-workers github-actions wrangler

wrangler-action's Introduction

Wrangler GitHub Action

Easy-to-use GitHub Action to use Wrangler. Makes deploying Workers a breeze.

Big Changes in v3

  • Wrangler v1 is no longer supported.
  • Global API key & Email Auth no longer supported
  • Action version syntax is newly supported. This means e.g. uses: cloudflare/wrangler-action@v3, uses: cloudflare/[email protected], and uses: cloudflare/[email protected] are all now valid syntax. Previously supported syntax e.g. uses: cloudflare/[email protected] is no longer supported -- the prefix v is now necessary.

Refer to Changelog for more information.

Usage

Add wrangler-action to the workflow for your Workers/Pages application. The below example will deploy a Worker on a git push to the main branch:

name: Deploy

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@v4
      - name: Deploy
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}

Authentication

You'll need to configure Wrangler using GitHub's Secrets feature - go to "Settings -> Secrets" and add your Cloudflare API token (for help finding this, see the Workers documentation). Your API token is encrypted by GitHub, and the action won't print it into logs, so it should be safe!

With your API token set as a secret for your repository, pass it to the action in the with block of your workflow. Below, I've set the secret name to CLOUDFLARE_API_TOKEN:

jobs:
  deploy:
    name: Deploy
    steps:
      uses: cloudflare/wrangler-action@v3
      with:
        apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}

Configuration

If you need to install a specific version of Wrangler to use for deployment, you can also pass the input wranglerVersion to install a specific version of Wrangler from NPM. This should be a SemVer-style version number, such as 2.20.0:

jobs:
  deploy:
    steps:
      uses: cloudflare/wrangler-action@v3
      with:
        apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
        wranglerVersion: "2.20.0"

Optionally, you can also pass a workingDirectory key to the action. This will allow you to specify a subdirectory of the repo to run the Wrangler command from.

jobs:
  deploy:
    steps:
      uses: cloudflare/wrangler-action@v3
      with:
        apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
        workingDirectory: "subfoldername"

Worker secrets can optionally be passed in via secrets as a string of names separated by newlines. Each secret name must match the name of an environment variable specified in the env field. This creates or replaces the value for the Worker secret using the wrangler secret put command.

jobs:
  deploy:
    steps:
      uses: cloudflare/wrangler-action@v3
      with:
        apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
        secrets: |
          SECRET1
          SECRET2
      env:
        SECRET1: ${{ secrets.SECRET1 }}
        SECRET2: ${{ secrets.SECRET2 }}

If you need to run additional shell commands before or after your command, you can specify them as input to preCommands (before deploy) or postCommands (after deploy). These can include additional wrangler commands (that is, whoami, kv:key put) or any other commands available inside the wrangler-action context.

jobs:
  deploy:
    steps:
      uses: cloudflare/wrangler-action@v3
      with:
        apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
        preCommands: echo "*** pre command ***"
        postCommands: |
          echo "*** post commands ***"
          wrangler kv:key put --binding=MY_KV key2 value2
          echo "******"

You can use the command option to do specific actions such as running wrangler whoami against your project:

jobs:
  deploy:
    steps:
      uses: cloudflare/wrangler-action@v3
      with:
        apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
        command: whoami

Use cases

Deploy when commits are merged to main

The above workflow examples have already shown how to run wrangler-action when new commits are merged to the main branch. For most developers, this workflow will easily replace manual deploys and be a great first integration step with wrangler-action:

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@v4
      - name: Deploy
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}

Note that there are a number of possible events, like push, that can be used to trigger a workflow. For more details on the events available, refer to the GitHub Actions documentation.

Deploy your Pages site (production & preview)

If you want to deploy your Pages project with GitHub Actions rather than the built-in continous integration (CI), then this is a great way to do it. Wrangler 2 will populate the commit message and branch for you. You only need to pass the project name. If a push to a non-production branch is done, it will deploy as a preview deployment:

on: [push]

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@v4
      - name: Deploy
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          command: pages deploy YOUR_DIST_FOLDER --project-name=example

Deploying on a schedule

If you would like to deploy your Workers application on a recurring basis – for example, every hour, or daily – the schedule trigger allows you to use cron syntax to define a workflow schedule. The below example will deploy at the beginning of every hour:

on:
  schedule:
    - cron: "0 * * * *"

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@v4
      - name: Deploy app
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}

If you need help defining the correct cron syntax, check out crontab.guru, which provides a friendly user interface for validating your cron schedule.

Manually triggering a deployment

If you need to trigger a workflow at-will, you can use GitHub's workflow_dispatch event in your workflow file. By setting your workflow to trigger on that event, you will be able to deploy your application via the GitHub UI. The UI also accepts inputs that can be used to configure the action:

on:
  workflow_dispatch:
    inputs:
      environment:
        description: "Choose an environment to deploy to: <dev|staging|prod>"
        required: true
        default: "dev"
jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@v4
      - name: Deploy app
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          command: deploy --env ${{ github.event.inputs.environment }}

For more advanced usage or to programmatically trigger the workflow from scripts, refer to the GitHub documentation for making API calls.

Upload a Worker Version

To create a new version of your Worker that is not deployed immediately, use the wrangler versions upload --experimental-versions command. Worker versions created in this way can then be deployed all at once at a later time or gradually deployed using the wranger versions deploy --experimental-versions command or via the Cloudflare dashboard under the Deployments tab. For now, the --experimental-versions flag and wrangler v3.40.0 or above is required to use this feature.

jobs:
  upload:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@v4
      - name: Upload Worker Version
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          command: versions upload --experimental-versions

Advanced Usage

Using Wrangler Command Output in Subsequent Steps

More advanced workflows may need to parse the resulting output of Wrangler commands. To do this, you can use the command-output output variable in subsequent steps. For example, if you want to print the output of the Wrangler command, you can do the following:

- name: Deploy
  id: deploy
  uses: cloudflare/wrangler-action@v3
  with:
    apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
    accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
    command: pages deploy --project-name=example

- name: print wrangler command output
  env:
    CMD_OUTPUT: ${{ steps.deploy.outputs.command-output }}
  run: echo $CMD_OUTPUT

Now when you run your workflow, you will see the full output of the Wrangler command in your workflow logs. You can also use this output in subsequent workflow steps to parse the output for specific values.

Note: the command-stderr output variable is also available if you need to parse the standard error output of the Wrangler command.

Using the deployment-url Output Variable

If you are executing a Wrangler command that results in either a Workers or Pages deployment, you can utilize the deployment-url output variable to get the URL of the deployment. For example, if you want to print the deployment URL after deploying your application, you can do the following:

- name: Deploy
  id: deploy
  uses: cloudflare/wrangler-action@v3
  with:
    apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
    accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
    command: pages deploy --project-name=example

- name: print deployment-url
  env:
    DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment-url }}
  run: echo $DEPLOYMENT_URL

The resulting output will look something like this:

https://<your_pages_site>.pages.dev

Using a different package manager

By default, this action will detect which package manager to use, based on the presence of a package-lock.json, yarn.lock, pnpm-lock.yaml, or bun.lockb file.

If you need to use a specific package manager for your application, you can set the packageManager input to npm, yarn, pnpm, or bun. You don't need to set this option unless you want to override the default behavior.

jobs:
  deploy:
    steps:
      uses: cloudflare/wrangler-action@v3
      with:
        apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
        packageManager: pnpm

Troubleshooting

"I just started using Workers/Wrangler and I don't know what this is!"

Refer to the Quick Start guide to get started. Once you have a Workers application, you may want to set it up to automatically deploy from GitHub whenever you change your project.

"[ERROR] No account id found, quitting.."

You will need to add account_id = "" in your wrangler.toml file or set accountId in this GitHub Action.

on: [push]

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@v4
      - name: Deploy app
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}

wrangler-action's People

Contributors

1000hz avatar adaptive avatar adirishi avatar boidolr avatar bradyjoslin avatar capaj avatar cherry avatar chromy avatar davwheat avatar demosjarco avatar dependabot[bot] avatar emasuriano avatar estebanborai avatar ethanppl avatar github-actions[bot] avatar grantbirki avatar igorminar avatar jacobmgevans avatar jasongill avatar jbampton avatar jgentes avatar kristianfreeman avatar lrapoport-cf avatar nix6839 avatar penalosa avatar ramideas avatar simpleauthority avatar threepointone avatar walshydev avatar whoabuddy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wrangler-action's Issues

Run without authentication

Hi, is it possible to run wranger build using this action without authentication?
wrangler will often run as a build step in GitHub Actions, and if this is triggered by e.g. dependabot secrets will not be filled in.

Cache install?

Something I noticed, every time I used this action, it had to do npm install and download the rust binary.

It would be nice and more dockerish (I believe) if those came in the action pre-installed. Reproducible dependencies also make developer life happier. Whatever runs locally, works online β€” given the same tags and versions.

And then I can update by using a different release of the action, or something like a latest tag if I always want the latest and greatest.

Thoughts?

Action fails with: 'rustc' not found

[email protected] fails with the following error:

Error: 'rustc' not found: cannot find binary path. Installation documentation can be found here: https://www.rust-lang.org/tools/install

This is the workflow file that I used:

name: Publish Cloudflare Worker (Dev)

on:
  push:
    branches:
      - '*'
      - '!main'

jobs:
  publish:
    name: Publish Cloudflare Worker (Dev)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Publish Worker
        uses: cloudflare/[email protected]
        with:
          apiToken: ${{ secrets.CF_API_TOKEN }}
          workingDirectory: 'some_dir/some_subdir'

Has the docker image perhaps been changed in a way that Rust is not properly installed anymore? As a workaround I have now switched to the following workflow, which works but is of course slower as wrangler first has to be installed:

name: Publish Cloudflare Worker (Dev)

on:
  push:
    branches:
      - '*'
      - '!main'

jobs:
  publish:
    name: Publish Cloudflare Worker (Dev)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Publish Worker
        env:
          CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }}
        working-directory: some_dir/some_subdir
        run: cargo install wrangler && wrangler publish

Post actions/cache@v1 fails because `.wrangler` is created for root:root

We have a static web app deployed to Google cloud CDN and to be able to serve different versions we use a Cloudflare worker that maps between an original URL and folder name in the CDN bucket.

The worker config in the git repository is located next to the static page code, inside the serve-index-worker:

repository
β”œβ”€β”€ .github
β”‚   β”œβ”€β”€ workflows                     <-- GitHub actions workflows
β”œβ”€β”€ serve-index-worker
β”‚   β”œβ”€β”€ .gitignore
β”‚   β”œβ”€β”€ generate-worker.js
β”‚   β”œβ”€β”€ package.json
β”‚   β”œβ”€β”€ wrangler.toml
β”œβ”€β”€ src                              <-- page source
β”‚   β”œβ”€β”€ ...
β”œβ”€β”€ .gitignore
β”œβ”€β”€ package.json
β”œβ”€β”€ yarn.lock

The workflow configuration is just taken from GitHub examples:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v1
        with:
          token: ${{ secrets.GH_ACCESS_TOKEN }}
          submodules: true

      - name: Setup Node
        uses: actions/setup-node@v1
        with:
          node-version: '10.x'

      - name: Get yarn cache
        id: yarn-cache
        run: echo "::set-output name=dir::$(yarn cache dir)"

      - uses: actions/cache@v1
        with:
          path: ${{ steps.yarn-cache.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-

      - name: Install the npm modules
        run: yarn install --frozen-lockfile

      - name: Build the modules
        run: yarn build:dev

      - name: Run unit-tests
        run: yarn test:ci

      - name: Deploy to GCP Storage
        uses: actions-hub/gcloud@master
        env:
          PROJECT_ID: tuup-servers
          APPLICATION_CREDENTIALS: ${{ secrets.GOOGLE_APPLICATION_CREDENTIALS }}
          CLI: gsutil
        with:
          args: -m cp -r ./build/* gs://some.server.url/web-app-dev/

      - name: Publish Cloudflare Worker
        uses: cloudflare/[email protected]
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          workingDirectory: 'serve-index-worker'

Everything works fine, including the worker publishing, but caching post action fails:

Post actions/cache@v1
0s
##[error]The template is not valid. Access to the path '/home/runner/work/repository/.wrangler' is denied.,Permission denied

When checking the content of the workspace it shows that the .wrangler folder is creates with root:root ownership

drwxrwx---    3 root   root     4096 Jan  7 12:09 .wrangler

while everything else is under runner:docker.

I could not find any configuration parameter that would control how the wrangler action is executed. What am I missing? πŸ€”

"builder error: failed to parse header value"

I'm trying to use this Wrangler publish action, but my script fails with:
"Error: Error: builder error: failed to parse header value"

Attached is a screenshot. Perhaps the error is some configuration error in my wrangler.toml, but it works on my dev box. Is there some way to trace where this error is coming from and at what step?
Screen Shot 2020-12-07 at 5 57 43 PM

Use variables for environment

If this is already possible, I haven't been able to figure out the correct syntax. What I'm trying to do is pass in the name of the branch that triggered the workflow as the environment (e.g. if this was triggered from a commit to staging then pass in staging as the environment). I've tried the following (both with and without quotes):

        uses: cloudflare/[email protected]
        with:
          apiToken: ${{ secrets.CF_API_TOKEN }}
          environment: '${GITHUB_REF##*/}' 

but the publish action fails with Error: Could not find environment with name "${GITHUB_REF##*/}"

Is there a way to dynamically publish to different environments?

wrangler build fails with npm@7 workspace build; fails to find parent node_modules/.bin/*

Using the new npm@7 workspace (https://docs.npmjs.com/cli/v7/using-npm/workspaces) monorepo feature and having a worker project in a subdir like packages/a with a custom build step in defined in the wrangler.toml like

type = "javascript"

[build]
command = "npm run build"

https://github.com/olizilla/wrangler-npm-workspace-test/blob/ed566f38cb40a1ea7265ceb803e0a95ada1cb8cf/packages/a/wrangler.toml#L8

and the package.json build script calls webpack

  "scripts": {
    "build": "webpack"
  }

and thewrangler-action configured to use the subdir packages/a as the workingDir

  deploy:
    name: Deploy worker
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: 16
      - uses: bahmutov/npm-install@v1
      - name: Publish worker
        uses: cloudflare/[email protected]
        with:
          apiToken: ${{ secrets.CF_API_TOKEN }}
          workingDirectory: 'packages/a'

https://github.com/olizilla/wrangler-npm-workspace-test/blob/ed566f38cb40a1ea7265ceb803e0a95ada1cb8cf/.github/workflows/publish.yml#L37-L41

fails, as npm can't find the webpack command.

Run cloudflare/[email protected]
/usr/bin/docker run --name a33c1892afcf99f6a4cc5ad8cc44158b68845_8d1fcd --label 8a33c1 --workdir /github/workspace --rm -e npm_config_cache -e INPUT_APITOKEN -e INPUT_WORKINGDIRECTORY -e INPUT_APIKEY -e INPUT_EMAIL -e INPUT_ENVIRONMENT -e INPUT_WRANGLERVERSION -e INPUT_SECRETS -e INPUT_PRECOMMANDS -e INPUT_POSTCOMMANDS -e INPUT_PUBLISH -e HOME -e GITHUB_JOB -e GITHUB_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_REPOSITORY_OWNER -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RETENTION_DAYS -e GITHUB_ACTOR -e GITHUB_WORKFLOW -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GITHUB_EVENT_NAME -e GITHUB_SERVER_URL -e GITHUB_API_URL -e GITHUB_GRAPHQL_URL -e GITHUB_WORKSPACE -e GITHUB_ACTION -e GITHUB_EVENT_PATH -e GITHUB_ACTION_REPOSITORY -e GITHUB_ACTION_REF -e GITHUB_PATH -e GITHUB_ENV -e RUNNER_OS -e RUNNER_TOOL_CACHE -e RUNNER_TEMP -e RUNNER_WORKSPACE -e ACTIONS_RUNTIME_URL -e ACTIONS_RUNTIME_TOKEN -e ACTIONS_CACHE_URL -e GITHUB_ACTIONS=true -e CI=true -v "/var/run/docker.sock":"/var/run/docker.sock" -v "/home/runner/work/_temp/_github_home":"/github/home" -v "/home/runner/work/_temp/_github_workflow":"/github/workflow" -v "/home/runner/work/_temp/_runner_file_commands":"/github/file_commands" -v "/home/runner/work/wrangler-npm-workspace-test/wrangler-npm-workspace-test":"/github/workspace" 8a33c1:892afcf99f6a4cc5ad8cc44158b68845
Using API Token authentication
/usr/local/bin/wrangler -> /usr/local/lib/node_modules/@cloudflare/wrangler/run-wrangler.js

> @cloudflare/[email protected] postinstall /usr/local/lib/node_modules/@cloudflare/wrangler
> node ./install-wrangler.js

Downloading release from https://workers.cloudflare.com/get-npm-wrangler-binary/1.17.0/x86_64-unknown-linux-musl
wrangler has been installed!
+ @cloudflare/[email protected]
added 22 packages from 9 contributors in 1.811s
 Running npm run build

> [email protected] build /github/workspace/packages/a
> webpack

sh: 1: webpack: not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! [email protected] build: `webpack`
npm ERR! spawn ENOENT
npm ERR! 
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/runner/.npm/_logs/2021-07-07T14_01_26_044Z-debug.log
Error: Build failed! Status Code: 1

In a npm@7 workspace project, the command is installed in the root node_modules/.bin/webpack not in the subdir packages/a/node_modules/.bin/webpack. This action currently uses the node:12 docker image so my guess is that that the wrangler build command is running npm run build in the docker container, so npm@6 is used.

Locally wrangler publish succeeds when npm@7 is available, but fails with npm@6 which is the default bundled with node@12.

A fix here would be to update the node docker image to node:16 which bundles npm@7.

I've made a minimal test repo, that shows the problem https://github.com/olizilla/wrangler-npm-workspace-test
this build should pass: https://github.com/olizilla/wrangler-npm-workspace-test/runs/3009656412

Request: Add additional logging to help users debug errors

When using this action, my GitHub action kept failing with the following error:

Downloading release https://workers.cloudflare.com/get-npm-wrangler-binary/1.11.0/x86_64-unknown-linux-musl
wrangler has been installed!
+ @cloudflare/[email protected]
added 34 packages from 21 contributors in 1.884s
Error: unknown field `name`, expected one of `bucket`, `entry-point`, `include`, `exclude`

I had no clue what that was. Based on the name of the fields, it seemed to be an issue with Docker. It was only after explicitly pulling out the npm i @cloudflare/wrangler -g and wrangler build into their own steps in my GitHub action that I realized that it was the build command that was failing. It turns out that the error originated from my wrangler.toml file β€”Β I had mistakenly moved [site] configuration between some top-level configuration.

I ended up figuring this out, but if there was some simple logging to let me know that wrangler-action was handling installing wrangler, running the build step, and then publishing, it would have saved me some time while debugging.

Running commands after publish

Is it already possible to run wrangler commands after publishing?

I'd like to delete a couple of KV keys, either via several wrangler kv:key delete or via wrangler kv:bulk delete.

Error: No such file or directory (os error 2)

I created a very simple worker, trying to deploy it to cloudflare workeres, but got an error without any details.

Error: No such file or directory (os error 2)

github action:

name: Build and Deploy to firebase, cloudflare-workers, ..
on:
  push:
    branches:
      - master

jobs:
  deploy:
    name: build & deploy
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@v2
      - name: Caching node modules
        uses: actions/cache@v1
        with:
          path: ~/.npm 
          key: ${{ runner.os }}-node_modules-${{ hashFiles('**/package-lock.json') }}-152020
      - name: Install devDpendencies
        run: |
          sudo chown -R $USER /usr
          npm install --no-audit
          npm install -g @angular/cli
      - name: Build
        run: npm run build
      - name: Deploy to CloudFlare workers
        uses: cloudflare/[email protected]
        with:
          apiKey: ${{ secrets.CLOUDFLARE_API_KEY }}
          email: ${{ secrets.CLOUDFLARE_EMAIL }}
        env:
          # https://github.com/cloudflare/wrangler-action/issues/12#issuecomment-588226602
          USER: root

wrangler.toml

name = "myworker"
type = "webpack"
account_id = "***"
route = "www.almogtama3.com/api/v1/cloudflare"
zone_id = "***"
webpack_config="./webpack.server.config.js"

[site]
entry-point="./dist/server/cloudflare-workers.js"
bucket="./dist/browser"

webpack.server.config.js

const webpackServer = require("./webpack.server.config.js");

module.exports = Object.assign(webpackServer, {
  target: "webworker",
  mode: "production",
  entry: {
    "cloudflare-workers": "./src/server/cloudflare-workers.js"
  }
});

webpack.server.config.js


const path = require("path");
const webpack = require("webpack");

module.exports = {
  target: "node",
  mode: "none",
  entry: {
    express: "./src/server/express.ts"
  },
  externals: {
    "./dist/server/main": 'require("./main")',
    sharp: "commonjs sharp" //https://github.com/lovell/sharp/issues/794#issuecomment-306555683
  },
  //https://github.com/googleapis/gax-nodejs/issues/719#issuecomment-605250814
  resolve: {
    extensions: [".ts", ".js", ".json"],
    alias: { pkg: path.resolve(__dirname, "./packages") }
  },
  optimization: {
    minimize: false
  },
  output: {
    // Puts the output at the root of the dist folder
    path: path.join(__dirname, "dist/server"), //todo: `dist/${this.mode}`
    filename: "[name].js", //'[name]' = entry[$key]
    library: "",
    libraryTarget: "commonjs-module"
    //fix: setting library & libraryTarget to fix issue: require('./server.js') == undefined
    //https://github.com/webpack/webpack/issues/2030#issuecomment-232886608
    //https://github.com/webpack/webpack/issues/2030#issuecomment-290363910
  },
  module: {
    noParse: /polyfills-.*\.js/,
    rules: [
      { test: /\.ts$/, loader: "ts-loader" },
      {
        // Mark files inside `@angular/core` as using SystemJS style dynamic imports.
        // Removing this will cause deprecation warnings to appear.
        test: /(\\|\/)@angular(\\|\/)core(\\|\/).+\.js$/,
        parser: { system: true }
      },
      {
        //load .node files
        //ex: ./node_modules/sharp/build/Release/sharp.node
        // https://github.com/lovell/sharp/issues/794#issuecomment-307188099
        test: /\.node$/,
        use: "node-loader"
      }
    ]
  },
  plugins: [
    new webpack.ContextReplacementPlugin(
      // fixes WARNING Critical dependency: the request of a dependency is an expression
      //https://webpack.js.org/plugins/context-replacement-plugin/
      /(.+)?angular(\\|\/)core(.+)?/,
      path.join(__dirname, "src"), // location of your src
      {} // a map of your routes
    ),
    new webpack.ContextReplacementPlugin(
      // fixes WARNING Critical dependency: the request of a dependency is an expression
      /(.+)?express(\\|\/)(.+)?/,
      path.join(__dirname, "src"),
      {}
    )
  ]
};

and here is the error in action
https://github.com/goblins-tech/almogtama3/runs/720247249?check_suite_focus=true#step:8:56

wrangler.toml Secrets

Cannot see a way of keeping the Account ID and Zone ID a secret within github. The Github Actions secrets don't work within the file. I'm sure it's possible but I'm missing it in the documentation somewhere

This doesn't work

type = "webpack"
account_id = "${{ secrets.CLOUDFLARE_ACCOUNT_ID }}"
workers_dev = false
route = "*domain.com/*"
zone_id = "${{ secrets.CLOUDFLARE_ZONE_ID }}"

[site]
bucket = "./public"

Whereas this works without an issue

type = "webpack"
account_id = "1234567890"
workers_dev = false
route = "*domain.com/*"
zone_id = "0987654321"

[site]
bucket = "./public"

Doesn't work for rust wasm worker

It failed when it tried to install wasm-pack during wrangler publish

Wrangler has been installed!
+ @cloudflare/[email protected]
added 27 packages from 13 contributors in 1.957s
⬇️ Installing wasm-pack...
 Compiling your project to WebAssembly...
Error: No such file or directory (os error 2)
Error: tried running command:
/github/workspace/.cache/.wrangler/wasm-pack-c6ddc20cc0d48874/wasm-pack build --target no-modules

I managed to reproduce it in my forked branch here alank976@2d7e8ad:

  1. wrangler generate test-rust-wasm https://github.com/cloudflare/rustwasm-worker-template and tweak a bit zone_id, route, and account_id in wrangler.toml in order to suppress complaints about authentication
  2. use docker-compose to reproduce the github action flow and mount the generated wasm project as INPUT_WORKINGDIRECTORY

You should be able to reproduce the same by running docker-compose up

I will probably try to fix by explicitly installing wasm-pack before wrangler publish and hopefully I can create a PR tomorrow for this :)

Installing private dependencies from a private NPM Registry?

Hi there,

I'm trying to set up the wrangler action on one of our repository to automatically publish our workers.
I'm hitting a wall as we rely on a Verdaccio instance to host some private dependencies that we make use of in the worker.

Is there a way for me to set this up?

Here is a shortened version of our workflow that would reproduce the issue:

name: CD

on:
  push:
    branches:
      - master

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@master
      - name: Setup Private Registry
        run: |
          npm config set https://registry.eatwith.io/:_authToken "$GITHUB_OAUTH_TOKEN"
          npm config set https://registry.eatwith.io/:always-auth true
          npm config set registry https://registry.eatwith.io
          yarn config set https://registry.eatwith.io/:_authToken "$GITHUB_OAUTH_TOKEN"
          yarn config set https://registry.eatwith.io/:always-auth true
          yarn config set registry https://registry.eatwith.io
        env:
          GITHUB_OAUTH_TOKEN: ${{ secrets.YARN_TOKEN }}
      - name: Create .env file before build
        run: |
          touch .env
          echo "SECRET_VAR=${{secrets.SECRET_VAR}}" >> .env
          echo "OTHER_SECRET=${{secrets.OTHER_SECRET}}" >> .env
      - name: Publish to production
        uses: cloudflare/[email protected]
        with:
          apiKey: ${{ secrets.CF_API_KEY }}
          email: ${{ secrets.CF_EMAIL }}
          environment: 'production'

Is there a way to support a similar configuration?
Based on https://github.com/cloudflare/wrangler-action/blob/master/entrypoint.sh it seems there is no way currently for me to modify the NPM's configuration that is used when running wrangler publish is this something you would be interested in supporting?

Worker deployment authentication error

every wrangler action fails with:

Built successfully, built project size is 189 KiB.
Error:  Code 10000: Authentication error

I tried both worker api token which built with template for worker and global API key and email to publish worker but two method results are same.
Is there any debug log options? and actually deployments get success.
Actually it happens also in local environment. If there's need more information, let me know.

Retry after 504 Gateway Timeout

We occasionally run into a 504 Gateway Timeout error with Wrangler when publishing, for example:

Deleting stale files...
Returned status code 504, Gateway Timeout. Please try again in a few seconds
Error: 

What is the recommended way of handling this, apart from running the entire action again (which takes a lot longer than just the publish step)?

Error: wrangler.toml not found

I have not found anything about this issue yet. My config is:

name: Deploy to Cloudflare Workers Sites

on:
  push:
    branches:
    - main

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2

    - name: Setup Latest Version of Hugo
      uses: peaceiris/actions-hugo@v2
      with:
        hugo-version: 'latest'

    - name: Build Hugo Site
      run: hugo --minify --gc

    - name: Publish to Cloudflare Workers Sites
      uses: cloudflare/[email protected]
      with:
        apiToken: ${{ secrets.CF_API_TOKEN }}

And it fails at:
image

Log output:

/usr/bin/docker run --name e1cc511d632ad861f943bc82d6d86488e0a75b_8eb506 --label e1cc51 --workdir /github/workspace --rm -e INPUT_APITOKEN -e INPUT_APIKEY -e INPUT_EMAIL -e INPUT_ENVIRONMENT -e INPUT_WORKINGDIRECTORY -e INPUT_WRANGLERVERSION -e INPUT_SECRETS -e INPUT_PRECOMMANDS -e INPUT_POSTCOMMANDS -e INPUT_PUBLISH -e HOME -e GITHUB_JOB -e GITHUB_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_REPOSITORY_OWNER -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RETENTION_DAYS -e GITHUB_RUN_ATTEMPT -e GITHUB_ACTOR -e GITHUB_WORKFLOW -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GITHUB_EVENT_NAME -e GITHUB_SERVER_URL -e GITHUB_API_URL -e GITHUB_GRAPHQL_URL -e GITHUB_WORKSPACE -e GITHUB_ACTION -e GITHUB_EVENT_PATH -e GITHUB_ACTION_REPOSITORY -e GITHUB_ACTION_REF -e GITHUB_PATH -e GITHUB_ENV -e RUNNER_OS -e RUNNER_NAME -e RUNNER_TOOL_CACHE -e RUNNER_TEMP -e RUNNER_WORKSPACE -e ACTIONS_RUNTIME_URL -e ACTIONS_RUNTIME_TOKEN -e ACTIONS_CACHE_URL -e GITHUB_ACTIONS=true -e CI=true -v "/var/run/docker.sock":"/var/run/docker.sock" -v "/home/runner/work/_temp/_github_home":"/github/home" -v "/home/runner/work/_temp/_github_workflow":"/github/workflow" -v "/home/runner/work/_temp/_runner_file_commands":"/github/file_commands" -v "/home/runner/work/blog-dariomader.io/blog-dariomader.io":"/github/workspace" e1cc51:1d632ad861f943bc82d6d86488e0a75b
Using API Token authentication
/usr/local/bin/wrangler -> /usr/local/lib/node_modules/@cloudflare/wrangler/run-wrangler.js

> @cloudflare/[email protected] postinstall /usr/local/lib/node_modules/@cloudflare/wrangler
> node ./install-wrangler.js

Downloading release from https://workers.cloudflare.com/get-npm-wrangler-binary/1.19.3/x86_64-unknown-linux-musl
wrangler has been installed!
+ @cloudflare/[email protected]
added 22 packages from 9 contributors in 4.747s
Error: wrangler.toml not found

EDIT: Can be closed. Obviously the wrangler.toml file was missing. I was following instructions where it was not defined to run "wrangler generate"

env parameter does not work for secrets

Should be uploading secrets for script my-worker-test, not my-worker

      - uses: cloudflare/[email protected]
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          command: publish --env ${{ github.events.inputs.environment }}
          secrets: |
            secret1
            secret2
        env:
          USER: root
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          secret1: ${{ secrets.secret1 }}
          secret2: ${{ secrets.secret2 }}
Using API Token authentication
 ⛅️ wrangler 2.0.5 
-------------------
πŸŒ€ Creating the secret for script my-worker
✨ Success! Uploaded secret secret1
 ⛅️ wrangler 2.0.5 
-------------------
πŸŒ€ Creating the secret for script my-worker
✨ Success! Uploaded secret secret2
$ Running: wrangler publish --env test
 ⛅️ wrangler 2.0.5 
-------------------
Running custom build: npm run build
> [email protected] build
> worktop build src/index.ts
  build/index.mjs  12.5kb
⚑ Done in 8ms
Uploaded my-worker-test (0.54 sec)
Published my-worker-test (0.31 sec)

How do I get the URL after a `pages` preview deployment?

I want to use the preview deployment of pages in PR and add URL to environment, but I don't know how to get the "Preview URL", it's not written in the documentation.

Desired effect

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    environment:
      name: dev-preview
      url: ${{ steps.builddeploy.outputs.web_app_url }}
    steps:
      - uses: actions/checkout@v3
      - name: Publish
        uses: cloudflare/[email protected]
        with:
          apiToken: ${{ secrets.CF_API_TOKEN }}
          accountId: ${{ secrets.CF_ACCOUNT_ID }}
          command: pages publish --project-name=example

When this CI is run you will see:
image

errors on missing user

I have a Hugo static site I'm attempting to publish with this action. However, each time I try, I receive an error when it attempts to install cargo after my previous action builds the site.

I have my account email and API Key saved in GitHub secrets for the repo; I know that worked because of the success when publishing manually below.

In the example here using this action, my action yams file contains:

name: Deploy to Workers

on:
  push:
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@master
        with:
          submodules: true

      - name: Install Hugo
        run: sudo snap install hugo

      - name: Build
        run: hugo

      - name: Publish
        uses: cloudflare/[email protected]
        with:
          apiKey: ${{ secrets.CF_API_KEY }}
          email: ${{ secrets.CF_EMAIL }}

Every time, that results in this error:

Downloading release https://workers.cloudflare.com/get-npm-wrangler-binary/1.6.0/x86_64-unknown-linux-musl
46
Wrangler has been installed!
47
+ @cloudflare/[email protected]
48
added 27 packages from 13 contributors in 1.573s
49
 Using namespace for Workers Site "__oldblog-samrhea-workers_sites_assets"
50
 Success
51
⬇️ Installing cargo-generate...
52
 Creating project called `workers-site`...
53
Error: could not determine the current user, please set $USER
54
Error: tried running command:
55
/github/workspace/.cache/.wrangler/cargo-generate-fc3c677afe428cb1/cargo-generate generate --git https://github.com/cloudflare/worker-sites-init --name workers-site --force
56
exited with exit code: 1
57
##[error]Docker run failed with exit code 1

When I run the wrangler steps manually, it works. Example yaml here:

name: Deploy to Workers

on:
  push:
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@master
        with:
          submodules: true

      - name: Install Hugo
        run: sudo snap install hugo

      - name: Install Wrangler
        run: sudo npm i @cloudflare/wrangler -g

      - name: Build
        run: hugo

      - name: config wrangler
        run: CF_EMAIL=${{ secrets.CF_EMAIL }} CF_API_KEY=${{ secrets.CF_API_KEY }} wrangler publish

Suggestion: Remove recommendation for `repository_dispatch` in favor of `workflow_dispatch`

A couple months ago, GHA announced the workflow_dispatch event. This new event treats manually triggered workflows as first-class citizens. It can be triggered via the UI, eliminating the requirement for cumbersome CLI commands that repository_dispatch requires.

Now, it's not this repo's responsibility for showing people the ropes around GHA, but as long as it is in the business of making recommendations in the README, this'd be a nice update to make.

Happy to make a PR for it if people think the change would be useful

docs: improve readme concerning Cloudflare API token

First thanks for this action πŸ˜ƒ

The readme links to the documentation by stating for help finding this, see the Workers documentation. But on that page, it doesn't say where to find that token. And when I go to the token page on the dashboard, I'm unable to view the Wrangler token.

After some research online, I found this blog post that explains that a new token must be created.

The current wording ("finding") in the readme suggests that the token already exists.

I would update the readme by linking to this page and indicate that the Cloudflare Workers must be selected.

Secrets uploaded with trailing `\n`

Hi all and thank you for the awesome job with the Cloudflare ecosystem. πŸ™‡β€β™‚οΈ

Looks like there might be a bit of a problem with Wrangler Action 2.0 (I do not recall having had this issue with the previous version, which was using the same configuration and the same secret values).

Given this configuration:

# ...
uses: cloudflare/[email protected]
  with:
    apiToken: ${{ secrets.CF_API_TOKEN }}
    secrets: |
      SECRET_A
      SECRET_B
    env:
      SECRET_A: ${{ secrets.A }}
      SECRET_B: ${{ secrets.B }}

Gives you secrets like this in the worker:

SECRET_A="valueA\n"
SECRET_B="valueB\n"

Please note that the value of the Github secrets had not changed, but just to be safe, I tried to re-enter them, making extra certain that no trailing \n or line feed is there, and I still have the issue. The CF_API_TOKEN is also working fine so I assume it isn't a new problem with Github secrets.

When I upload the secrets manually using wrangler CLI it works fine. πŸŽ‰
I just can't do it from here without having the \n appended to everything. πŸ€·β€β™‚οΈ

needs discussion: wrangler-action outputs

github actions have the concept of outputs, which are variables that come out of an action and can be used subsequently in the workflow:

https://help.github.com/en/actions/automating-your-workflow-with-github-actions/metadata-syntax-for-github-actions#outputs

when publishing, the action could capture (at minimum) the URL when a project is published, and output it as outputs.published_url (or something similarly named).

for implementation, it's worth noting that wrangler currently exposes the published URL as part of the last line of output in wrangler publish:

Successfully published your script to $URL

the naive implementation would be to do a regex capture group or something similar at the end of the line. this would allow workflow developers to take that url and pass it into a subsequent notification step, for instance, posting the deployed URL in a slack channel. i started a POC of this naive implementation, which will output the stderr of wrangler publish into a .wrangler_publish_log file, and parse it for a URL ($PUBLISH_URL could then be exposed as outputs.published_url):

export PUBLISH_LOG=".wrangler_publish_log"
wrangler publish | tee $PUBLISH_LOG
if [[ -s $PUBLISH_LOG ]];
then
  export PUBLISH_LOG_LAST_LINE="$(cat $PUBLISH_LOG | tail -n1)" 
  export PUBLISH_URL="$(echo $PUBLISH_LOG_LAST_LINE | sed -E 's/^.* Successfully published your script to (.*)/\1/')"
  echo $PUBLISH_URL # https://static-test.signalnerve.workers.dev
fi

the reason that i haven't begun implementing this is because i'm wondering if we should also parse/output errors. currently, tee will just process stdout, but if we update the publish + capture line:

# wrangler publish  | tee $PUBLISH_LOG
wrangler publish 2>&1 | tee $PUBLISH_LOG

we can also capture stderr, and potentially expose it as an output (e.g. create a pagerduty alert when publish fails). in that case, i'm wondering the following:

  1. would it be okay to expose an entire error log over essentially plaintext? sure, you can pop into the actions workflow and see the error in the actions UI, but i want to double-check that it's okay to expose an entire error log as potential input to a workflow we have no control over
  2. is there enough consistency to wrangler's error output that if we don't capture the entire log as seen above, we can parse a known number of lines and send that as outputs.error? my gut feeling is no, it isn't consistent enough, but i need to investigate a bit more to confirm that.

the number of questions here makes me think that long-term, maybe another better solution would be to have something on the wrangler side that outputs errors in a computer-friendly way, not human-friendly. e.g., if the publish output was JSON, we could just parse the keys coming out of wrangler publish, and pass them on to outputs.*.

(opening this ticket because we have been discussing this internally in chat this morning, and i'd like to document it for long-term development discussion of both wrangler and this action πŸ‘ )

feature request: secrets publishing

We maintain secrets in GitHub Actions for different environments, and now with the new secrets release available in Workers, it would be fantastic to be able to publish secrets directly using this action.

Something like:

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - uses: actions/checkout@master
      - name: Publish
        uses: cloudflare/[email protected]
        with:
          apiToken: ${{ secrets.CF_API_TOKEN }}
          environment: 'production'
          secrets:
            - foo: ${{ secrets.production_foo }}
            - bar: ${{ secrets.production_bar }}

This would allow us to set and deploy secrets in GitHub actions for different environments, without having someone manually issue wrangler secret commands, or manually creating our own step where we npm install wrangler, and run the commands inline.

NPM build step required but not documented

When adding this to a project started with @cloudflare/worker-sites-template, I found that it failed it build because a npm run build fails.

I ended up needing to have a least this minimal package.json for it to work:

{
  "private": true,
  "scripts": {
    "build": "echo \"No build step\""
  }
}

If possible we should remove this requirement, or minimally, we should at least document that it is required.

Run npm install - Wrangler V2

You can mark the path "itty-router" as external to exclude it from the bundle, which will remove this error.

It gives such an error because the packages are not downloaded.

Action times out

Similar to #44 we're currently unable to deploy our site because the workflow never finishes:

Using namespace for Workers Site "...-workers_sites_assets"
 Success
 Uploading site files
 Successfully published your script to
 .../* => stayed the same
with this schedule
 */6 * * * *
 */15 * * * *
 */20 * * * *
 Deleting stale files...
Error: The operation was canceled.

It runs for 10 minutes until it times out, because of our:

timeout-minutes: 10

The wrangler version is v1.19.10.

Passing environment variables

We'd love to pass environment variables to the Worker Site similar to how secrets work:

addEventListener('fetch', event => {
  console.log(process.env.RELEASE) // coming from `jobs.*.steps.step.with`
  console.log(STRIPE_SECRET) // coming from `wrangler secret put STRIPE_SECRET`
})

A use case for this would be Sentry Releases. We want to report errors happening in Workers Sites to Sentry. It would be really useful to also pass the GitHub SHA as the "RELEASE" constant.

steps:
      - uses: cloudflare/[email protected]
        with:
          apiToken: ${{ secrets.CF_API_TOKEN }}
          RELEASE: ${GITHUB_SHA} # or: ${github.sha}

@signalnerve: Any thoughts on this? Is this already possible somehow?

Multiple secret publish results in very noisy output

If you are publishing multiple secrets with this action, you get a lot of superfluous output, such as:

--------------------
β–² [WARNING] Processing wrangler.toml configuration:

    - 😢 Ignored: "miniflare":
      Wrangler does not use configuration in the `miniflare` section. Unless you are using Miniflare directly you can remove this section.


πŸŒ€ Creating the secret for the Worker "xxx" 
✨ Success! Uploaded secret xxx1
 ⛅️ wrangler 2.0.24 
--------------------
β–² [WARNING] Processing wrangler.toml configuration:

    - 😢 Ignored: "miniflare":
      Wrangler does not use configuration in the `miniflare` section. Unless you are using Miniflare directly you can remove this section.


πŸŒ€ Creating the secret for the Worker "xxx" 
✨ Success! Uploaded secret xxx2
 ⛅️ wrangler 2.0.24 
--------------------
β–² [WARNING] Processing wrangler.toml configuration:

    - 😢 Ignored: "miniflare":
      Wrangler does not use configuration in the `miniflare` section. Unless you are using Miniflare directly you can remove this section.


πŸŒ€ Creating the secret for the Worker "xxx" 
✨ Success! Uploaded secret xxx3

# and so on

This is made worse when you have a configuration like miniflare in your wrangler.toml that gets ignored and very loudly warned about every time.

The best solution here would likely be some kind of mass secret publishing within wrangler itself.

clean up action output when running

the action is super noisy when running! as much as possible, i'd like to pass quiet flags and minimize output that isn't explicitly tied to when wrangler publish runs – the nvm and node installations in particular

feat: customize node version

Overview

Currently, cloudflare/wrangler-action does not support NodeJS version outside v12. This will potentially cause issues with some dependencies as some require a newer version of NodeJS.

To adhere to this issue, I think we can implement a new property node-version just like how actions/setup-node implemented it.

support deploying workers from subdirectories

via https://github.com/cloudflare/lasso (and i imagine other projects as well), the action should support deploying from a specific subdirectory inside of a repository. currently, if there isn't a wrangler.toml in the top-level repo directory, the action should fail.

my gut feeling here is workingDirectory (or something similarly named) in the workflow config. it's a relative path that the docker entrypoint will cd into if it's set. usage below (with an added bonus of showing how you could deploy multiple workers with this addition):

- name: Publish worker one
  uses: cloudflare/[email protected]
  with:
    apiKey: ${{ secrets.CF_API_KEY }}
    email: ${{ secrets.CF_EMAIL }}
    workingDirectory: 'worker-one'
- name: Publish worker two
  uses: cloudflare/[email protected]
  with:
    apiKey: ${{ secrets.CF_API_KEY }}
    email: ${{ secrets.CF_EMAIL }}
    workingDirectory: 'worker-two'

Wrangler install fails, but action still succeeds

I have this step in my Github Actions job:

      - name: Publish Partner API Cloudflare
        uses: cloudflare/[email protected]
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          environment: ${{ github.event.inputs.environmentName }}
          workingDirectory: packages/partner-api-worker

In the Github Actions logs, I saw this:

Using API Token authentication
/usr/local/bin/wrangler -> /usr/local/lib/node_modules/@cloudflare/wrangler/run-wrangler.js

> @cloudflare/[email protected] postinstall /usr/local/lib/node_modules/@cloudflare/wrangler
> node ./install-wrangler.js

Downloading release from workers.cloudflare.com/get-npm-wrangler-binary/1.17.0/x86_64-unknown-linux-musl
wrangler has been installed!
+ @cloudflare/[email protected]
added 22 packages from 9 contributors in 1.702s
  Installing wranglerjs v1.17.0...

Oops! wrangler encountered an error... please help Cloudflare debug this issue by submitting an error report (/github/workspace/errors/1622642554269.log)

To submit this error report to Cloudflare, run:

    $ wrangler report

But the task succeeded anyway. That's misleading, it makes it seem like it worked when it didn't - this ought to be a failure case.

(separately it's a little annoying it doesn't say what the error was or at least some kind of error code, I can't access the file system of the github action directly.)

Option for yarn instead of npm?

I use yarn for managing my packages, is it possible to add a configuration that installs wrangler and all of the packages via yarn rather than the default npm, as it is now?

wrangler-action failing since wrangler 1.14.0 - "Error: Cannot find module 'webpack'"

Since wrangler 1.14.0 any workers configured to use webpack using the wrangler-action fail.

/usr/bin/docker run --name e478d2379fc5c846f8ba82b651625ce8d5_098a67 --label 5588e4 --workdir /github/workspace --rm -e INPUT_APITOKEN -e INPUT_APIKEY -e INPUT_EMAIL -e INPUT_ENVIRONMENT -e INPUT_WORKINGDIRECTORY -e INPUT_WRANGLERVERSION -e INPUT_SECRETS -e INPUT_PRECOMMANDS -e INPUT_POSTCOMMANDS -e INPUT_PUBLISH -e HOME -e GITHUB_JOB -e GITHUB_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_REPOSITORY_OWNER -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RETENTION_DAYS -e GITHUB_ACTOR -e GITHUB_WORKFLOW -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GITHUB_EVENT_NAME -e GITHUB_SERVER_URL -e GITHUB_API_URL -e GITHUB_GRAPHQL_URL -e GITHUB_WORKSPACE -e GITHUB_ACTION -e GITHUB_EVENT_PATH -e GITHUB_ACTION_REPOSITORY -e GITHUB_ACTION_REF -e GITHUB_PATH -e GITHUB_ENV -e RUNNER_OS -e RUNNER_TOOL_CACHE -e RUNNER_TEMP -e RUNNER_WORKSPACE -e ACTIONS_RUNTIME_URL -e ACTIONS_RUNTIME_TOKEN -e ACTIONS_CACHE_URL -e GITHUB_ACTIONS=true -e CI=true -v "/var/run/docker.sock":"/var/run/docker.sock" -v "/home/runner/work/_temp/_github_home":"/github/home" -v "/home/runner/work/_temp/_github_workflow":"/github/workflow" -v "/home/runner/work/_temp/_runner_file_commands":"/github/file_commands" -v "/home/runner/work/dimebeauty-discount-worker/dimebeauty-discount-worker":"/github/workspace" 5588e4:78d2379fc5c846f8ba82b651625ce8d5
Using API Token authentication
/usr/local/bin/wrangler -> /usr/local/lib/node_modules/@cloudflare/wrangler/run-wrangler.js

> @cloudflare/[email protected] postinstall /usr/local/lib/node_modules/@cloudflare/wrangler
> node ./install-wrangler.js

Downloading release from https://workers.cloudflare.com/get-npm-wrangler-binary/1.14.1/x86_64-unknown-linux-musl
wrangler has been installed!
+ @cloudflare/[email protected]
added 23 packages from 10 contributors in 2.954s
added 18 packages from 49 contributors and audited 18 packages in 1.05s
found 0 vulnerabilities

  Installing wranglerjs v1.14.1...
internal/modules/cjs/loader.js:818
  throw err;
  ^

Error: Cannot find module 'webpack'
Require stack:
- /github/workspace/.cache/.wrangler/wranglerjs-1.14.1/index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
    at Function.Module._load (internal/modules/cjs/loader.js:667:27)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/github/workspace/.cache/.wrangler/wranglerjs-1.14.1/index.js:1:17)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/github/workspace/.cache/.wrangler/wranglerjs-1.14.1/index.js' ]
}
Error: failed to execute `"/usr/local/bin/node" "/github/workspace/.cache/.wrangler/wranglerjs-1.14.1" "--output-file=/tmp/.wranglerjs_outputqBrxG" "--wasm-binding=WASM_MODULE" "--no-webpack-config=1" "--use-entry=/github/workspace/index.js"`: exited with exit code: 1

Publish worker secrets before publish worker

The wrangler action errors when publishing a secret for the first time if that secret hasn't been previously published to the targeted environment manually. The action fails with an error saying that the new secret variable in the worker is undefined.

This could be fixed by modifying the order in which the action script publishes the worker and secret. Currently the worker is published before the secret, propose changing to publishing secrets before the worker.

Current code

# If an environment is detected as input, for each secret specified get the value of
# the matching named environment variable then configure using wrangler secret put.
if [ -z "$INPUT_ENVIRONMENT" ]
then
  wrangler publish

  for SECRET in $INPUT_SECRETS; do
    VALUE=$(printenv "$SECRET") || secret_not_found "$SECRET"
    echo "$VALUE" | wrangler secret put "$SECRET"
  done
else
  wrangler publish -e "$INPUT_ENVIRONMENT"

  for SECRET in $INPUT_SECRETS; do
    VALUE=$(printenv "$SECRET") || secret_not_found "$SECRET"
    echo "$VALUE" | wrangler secret put "$SECRET" --env "$INPUT_ENVIRONMENT"
  done
fi

Proposed:

# If an environment is detected as input, for each secret specified get the value of
# the matching named environment variable then configure using wrangler secret put.
if [ -z "$INPUT_ENVIRONMENT" ]
then
  for SECRET in $INPUT_SECRETS; do
    VALUE=$(printenv "$SECRET") || secret_not_found "$SECRET"
    echo "$VALUE" | wrangler secret put "$SECRET"
  done

  wrangler publish
else
  for SECRET in $INPUT_SECRETS; do
    VALUE=$(printenv "$SECRET") || secret_not_found "$SECRET"
    echo "$VALUE" | wrangler secret put "$SECRET" --env "$INPUT_ENVIRONMENT"
  done

  wrangler publish -e "$INPUT_ENVIRONMENT"
fi

wrangler-action failing since wrangler 1.14.0 (EACCES: permission denied, mkdir)

The newest wrangler doesn't work with wrangler-action due to an unknown permission issue. I've told my Github Action to use wranglerVersion: '1.13.0' in the meantime to get it working again.

uses: cloudflare/[email protected]
  with:
    apiToken: ${{ secrets.CF_API_TOKEN }}
    wranglerVersion: '1.13.0'

The error in question:

Using API Token authentication
/usr/local/bin/wrangler -> /usr/local/lib/node_modules/@cloudflare/wrangler/run-wrangler.js

> @cloudflare/[email protected] postinstall /usr/local/lib/node_modules/@cloudflare/wrangler
> node ./install-wrangler.js

internal/fs/utils.js:269
    throw err;
    ^

Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/@cloudflare/wrangler/wrangler'
    at mkdirSync (fs.js:921:3)
    at Binary._getInstallDirectory (/usr/local/lib/node_modules/@cloudflare/wrangler/node_modules/@cloudflare/binary-install/src/binary.js:52:7)
    at Binary.install (/usr/local/lib/node_modules/@cloudflare/wrangler/node_modules/@cloudflare/binary-install/src/binary.js:78:22)
    at install (/usr/local/lib/node_modules/@cloudflare/wrangler/binary.js:52:10)
    at Object.<anonymous> (/usr/local/lib/node_modules/@cloudflare/wrangler/install-wrangler.js:4:1)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12) {
  errno: -13,
  syscall: 'mkdir',
  code: 'EACCES',
  path: '/usr/local/lib/node_modules/@cloudflare/wrangler/wrangler'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @cloudflare/[email protected] postinstall: `node ./install-wrangler.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @cloudflare/[email protected] postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /github/workspace/.npm/_logs/2021-03-05T01_17_09_614Z-debug.log

Better error when wrangler is not logged in.

πŸ’‘ Feature request

Better error messages when using cloudflare/wrangler-action and the apiKey is incorrect.

Overview and problem statement

Using Wrangler with Cloudflare's Github Wrangler action , I was stuck for a few days with a mysterious error "builder error: failed to parse header value". After a huge amount of trial and error, I finally figured out that my credentials were incorrect.

Would it be possible to add a better error message? To help you figure out situation, here is my original bug report: #47

Basic example

n/a

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.