# Deploy from GitHub Actions

Build your image in GitHub Actions or any CI, push it, and deploy it to an app with one command that waits for the result and fails the job when the deployment fails.

The job fails when the deployment fails: a release command that exits non-zero, a health check that
never passes, or a rollout that times out. The previous version keeps serving in every one of those
cases. Replace app-id with the app's id, repository-id with the registry
repository's id, and `org-EXAMPLE1234` with your organization's id; find the ids on the app and
repository pages.

## Prerequisites

- An app with the `image` builder, or `compose` for several services from one image.
- Permission to create the CI user, its policy and its access key (`iam:CreateUser`,
  `iam:CreatePolicy`, `iam:AttachUserPolicy`, `iam:CreateAccessKey`) and to update the app
  (`deploy:UpdateApp`).
- The `dcloud` CLI needs Node 20.10 or later. It is one file, served by your Deutsche Cloud Console at
  `/api/cli`.

## Step 1: Prepare the app

Set the app's release command and health check:

**Console**
1. Open the app's **Runtime** tab.
2. Under **Release and health checks**, for **Release command**, enter `pnpm db:migrate`.
3. For **Health check path**, enter `/api/health`, and for **Expected status**, enter `200`.
4. Choose **Save**.

**CLI**
```sh
dcloud deploy apps update app-id \
  --release-command 'pnpm db:migrate' \
  --health-check '{"path":"/api/health","expectedStatus":200,"timeoutSec":120}'
```

For a compose app with web and worker services, the release command runs from the published service
by default; `--release-service worker` runs it from another one.

See [Configure the release command and health checks](configure-release-and-health-checks.md).

## Step 2: Create the CI key

A CI key is an access key for an IAM user that exists only for the pipeline, with the policy below
and nothing else.

**Console**
1. Open **IAM**, then **Policies**, choose **Create policy**, and create a policy like the one
   below.
2. Open **IAM**, then **Users**, then choose **Create user**. Choose **Service account**, enter a
   **Username** such as `ci-github`, and choose **Create user**. A new user holds no permissions.
3. On the user's page, attach the policy (**Attach policy…**).
4. Open **IAM**, then **Access keys**, and choose **Create access key**. For **Acts as**, choose
   the user, then choose **Create access key**. Copy the key as the console shows it
   (`EWS1…:<secret>`); it is shown once.

**CLI:** not available. Create the user and its policy in the console, or see the IAM guide.

```json
{
  "Version": "2024-01-01",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["deploy:DescribeApp", "deploy:DeployApp"],
      "Resource": "rn:ews:de1:org-EXAMPLE1234:deploy:app/app-id"
    },
    {
      "Effect": "Allow",
      "Action": ["ecr:GetAuthorizationToken"],
      "Resource": "rn:ews::org-EXAMPLE1234:ecr:*"
    },
    {
      "Effect": "Allow",
      "Action": ["ecr:PushImage", "ecr:PullImage"],
      "Resource": "rn:ews::org-EXAMPLE1234:ecr:repository/repository-id"
    }
  ]
}
```

- Deploying an image from another registry: drop the two `ecr:` statements.
- Pushing to a repository that does not exist yet: add `ecr:CreateRepository` on
  `rn:ews::org-EXAMPLE1234:ecr:*`, or create the repository first (recommended).
- Use the app **id** in the workflow. Looking an app up by slug lists apps, which needs
  `deploy:DescribeApp` on `rn:ews:de1:org-EXAMPLE1234:deploy:*`.

Store the key in the GitHub repository as the secret `DCLOUD_ACCESS_KEY` (`EWS1…:<secret>`, exactly as
the console shows it) and the console URL as the variable `DCLOUD_API_URL`. To sign in with the job's
own OIDC token instead of a stored key, see
[Deploy from GitHub Actions without a stored key](deploy-from-github-actions-with-oidc.md).

## Step 3: Add the workflow

This workflow needs nothing but `curl`, Node and Docker, which GitHub's hosted runners have:

```yaml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    env:
      DCLOUD_API_URL: ${{ vars.DCLOUD_API_URL }}
      DCLOUD_ACCESS_KEY: ${{ secrets.DCLOUD_ACCESS_KEY }}
      APP_ID: 00000000-0000-0000-0000-000000000000 # your app id
      REPOSITORY: web # your registry repository
    steps:
      - uses: actions/checkout@v4

      - name: Install the CLI
        run: |
          curl -fsSL "$DCLOUD_API_URL/api/cli" -o /usr/local/bin/dcloud
          chmod +x /usr/local/bin/dcloud

      - name: Log in to the registry
        run: |
          login="$(dcloud ecr auth login-token --json)"
          host="$(node -e 'process.stdout.write(JSON.parse(process.argv[1]).data.registryHost)' "$login")"
          token="$(node -e 'process.stdout.write(JSON.parse(process.argv[1]).data.token)' "$login")"
          echo "::add-mask::$token"
          printf '%s' "$token" | docker login "$host" -u dcloud --password-stdin
          echo "IMAGE=$host/$REPOSITORY:$GITHUB_SHA" >> "$GITHUB_ENV"

      - name: Build and push
        run: |
          docker build -t "$IMAGE" .
          docker push "$IMAGE"

      - name: Deploy and wait
        run: dcloud deploy apps deploy "$APP_ID" --image "$IMAGE" --wait --timeout 20m
```

The last step prints the deployment's activity, the release command's output included, and exits
non-zero when the deployment does not go live.

### Use the composite action instead

The `github-action/` folder of the Deutsche Cloud repository is a composite action that does the same
four steps. Copy it into your repository (for example to `.github/actions/ews-deploy/`) and use it:

```yaml
- uses: ./.github/actions/ews-deploy
  with:
    app: ${{ env.APP_ID }}
    local-image: web:ci # built earlier in the job; pushed as <registry>/<repository>:<sha>
    repository: web
  env:
    DCLOUD_API_URL: ${{ vars.DCLOUD_API_URL }}
    DCLOUD_ACCESS_KEY: ${{ secrets.DCLOUD_ACCESS_KEY }}
```

| Input         | Meaning                                                                | Default              |
| ------------- | ---------------------------------------------------------------------- | -------------------- |
| `app`         | app id, slug or name                                                   | required             |
| `image`       | deploy this reference as-is (any registry)                             | the app's image      |
| `local-image` | a locally built image to tag and push into your registry, then deploy  | none                 |
| `repository`  | registry repository for `local-image`                                  | the `app` value      |
| `tag`         | tag to push `local-image` as                                           | the commit SHA       |
| `api-url`     | console URL                                                            | `$DCLOUD_API_URL`    |
| `access-key`  | `EWS1…:secret`                                                         | `$DCLOUD_ACCESS_KEY` |
| `wait`        | wait for the result                                                    | `true`               |
| `timeout`     | how long to wait                                                       | `20m`                |
| `setup-node`  | install Node for the CLI; `false` when the runner has Node 20 or later | `true`               |

Outputs: `image`, `deployment-id`. Without the inputs, credentials are read from `DCLOUD_API_URL`
and `DCLOUD_ACCESS_KEY` (or the former names `EWS_API_URL` and `EWS_ACCESS_KEY`), so an earlier
step that sets them (a credential exchange, for example) works without changing the action.

## The deploy command

```sh
dcloud deploy apps deploy app-id --image ghcr.io/example/web:1.4.2 --wait --timeout 20m
```

| Flag        | Meaning                                                                        |
| ----------- | ------------------------------------------------------------------------------ |
| `--image`   | deploy this image for this deployment; the app's configured image is unchanged |
| `--wait`    | stay until the deployment is `live`, `failed` or `superseded`                  |
| `--timeout` | stop waiting after this long: `900`, `90s`, `15m`, `1h`; default `20m`         |
| `--json`    | print the final deployment on stdout; progress stays on stderr                 |
| `--quiet`   | print only the deployment id                                                   |

| Exit code | Meaning                                                        |
| --------- | -------------------------------------------------------------- |
| 0         | live (or started, without `--wait`)                            |
| 1         | any other failure: network, a server error, a malformed answer |
| 2         | the command line is wrong                                      |
| 3         | no credential, or the credential was rejected                  |
| 4         | the key lacks a permission                                     |
| 5         | the app does not exist or is not visible to the key            |
| 6         | the deployment failed or was superseded                        |
| 7         | `--timeout` passed; the deployment continues on the platform   |

| Variable            | Meaning                                            |
| ------------------- | -------------------------------------------------- |
| `DCLOUD_API_URL`    | console URL                                        |
| `DCLOUD_ACCESS_KEY` | `EWS1…:<secret>`; wins over any stored CLI profile |

To deploy an image kept in ghcr.io, Docker Hub or your own registry, give the app a credential for
it first; see [Pull from another registry](pull-from-another-registry.md).

## Result

Every push to `main` builds the image, pushes it, deploys it and waits. The job goes red when the
deployment does not go live, and the lines above the error are the deployment's own activity.

## Related

- [Deployments](deployments.md)
- [Troubleshooting](troubleshooting.md)
- `deploy.deployments.create` · `deploy.deployments.wait`
