### Dagger Toolchain Install Example Source: https://docs.dagger.io/reference/cli This example shows how to install a specific toolchain, in this case, the Go toolchain from a GitHub repository, to the current module. ```bash dagger toolchain install github.com/dagger/dagger/toolchains/go ``` -------------------------------- ### Initialize Go Example Module Source: https://docs.dagger.io/reference/best-practices/modules Sets up a new Go module in the examples/go directory and installs the current Dagger module. ```bash mkdir -p examples/go cd examples/go dagger init --name=examples/go --sdk=go --source=. dagger install ../.. ``` -------------------------------- ### Create and Clone Example Application with gh CLI Source: https://docs.dagger.io/getting-started/quickstarts/toolchain Use the `gh` CLI to create a new GitHub repository from a template and navigate into it. This sets up the example application for the quickstart. ```bash gh repo create hello-dagger --template dagger/hello-dagger-template --public --clone cd hello-dagger ``` -------------------------------- ### Initialize Python Example Module Source: https://docs.dagger.io/reference/best-practices/modules Sets up a new Python module in the examples/python directory and installs the current Dagger module. ```bash mkdir -p examples/python cd examples/python dagger init --name=examples/python --sdk=python --source=. dagger install ../.. ``` -------------------------------- ### Initialize TypeScript Example Module Source: https://docs.dagger.io/reference/best-practices/modules Sets up a new TypeScript module in the examples/typescript directory and installs the current Dagger module. ```bash mkdir -p examples/typescript cd examples/typescript dagger init --name=examples/typescript --sdk=typescript --source=. dagger install ../.. ``` -------------------------------- ### Initialize Go Module and Project Setup Source: https://docs.dagger.io/extending/custom-applications/go Clone an example project, create a new Go module, and set up the directory structure for a multi-architecture build. ```bash git clone https://go.googlesource.com/example cd example/hello mkdir multibuild && cd multibuild go mod init multibuild ``` -------------------------------- ### Full Development Workflow Example Source: https://docs.dagger.io/core-concepts An example demonstrating a full development workflow using Dagger, including installing a toolchain, running build commands, executing tests, and developing custom functions. ```bash # Install a toolchain (provides functions and checks) dagger install github.com/example/node-toolchain # Use toolchain functions dagger call node build # Build your application dagger check node:test # Run tests dagger check # Run all validation checks # Customize by adding your own functions dagger develop --sdk=typescript # Add custom functions # Write functions that use toolchain capabilities ``` -------------------------------- ### List Containers and Check Dagger Version Source: https://docs.dagger.io/reference/container-runtimes/apple-container This example demonstrates listing containers using the 'container' command and then checking the Dagger core version. It shows the state of containers before and after Dagger might have started or interacted with them. ```bash $ container ls ID IMAGE OS ARCH STATE ADDR CPUS MEMORY $ dagger core version v0.18.19 $ container ls container ls ID IMAGE OS ARCH STATE ADDR CPUS MEMORY dagger-engine-v0.18.19 registry.dagger.io/engine:v0.18.19 linux arm64 running 192.168.64.4 4 8192 MB ``` -------------------------------- ### Navigate to Project and List Dagger Functions Source: https://docs.dagger.io/getting-started/quickstarts/agent-in-project Change to your project's working directory and list the available Dagger Functions to verify the project setup. Ensure you have completed the AI agent and CI quickstarts. ```bash cd hello-dagger dagger functions ``` -------------------------------- ### Install `curl`, Make HTTP Request, and Get Output Source: https://docs.dagger.io/extending/chaining Chain container configuration with `withExec()` to install `curl`, perform an HTTP request, and capture the output. This demonstrates a multi-step workflow within a container. ```bash dagger < args = List.of("redis-cli", "-h", "redis-srv"); // set value String setter = redisCli.withExec(append(args, List.of("set", "foo", "bar"))).stdout(); // get value String getter = redisCli.withExec(append(args, List.of("get", "foo"))).stdout(); return setter + getter; ``` ```java private List append(List list, List elements) { return Stream.concat(list.stream(), elements.stream()).toList(); } ``` -------------------------------- ### Advanced GitLab CI/CD Pipeline with Dagger for Testing and Building Source: https://docs.dagger.io/getting-started/ci-integrations/gitlab-ci This example demonstrates a more complex GitLab CI/CD pipeline using Dagger to test a project and then build and publish a container image. It extends the basic Dagger setup and assumes a Go application. Assumes DAGGER_CLOUD_TOKEN is set as a protected variable. ```yaml .docker: image: docker:latest services: - docker:${DOCKER_VERSION}-dind variables: DOCKER_HOST: tcp://docker:2376 DOCKER_TLS_VERIFY: '1' DOCKER_TLS_CERTDIR: '/certs' DOCKER_CERT_PATH: '/certs/client' DOCKER_DRIVER: overlay2 DOCKER_VERSION: '27.2.0' # assumes the Dagger Cloud token is # in a masked/protected variable named DAGGER_CLOUD_TOKEN # set via the GitLab UI DAGGER_CLOUD_TOKEN: $DAGGER_CLOUD_TOKEN .dagger: extends: [.docker] before_script: - apk add curl - curl -fsSL https://dl.dagger.io/dagger/install.sh | BIN_DIR=/usr/local/bin sh test: extends: [.dagger] script: - dagger -m github.com/kpenfound/dagger-modules/golang@v0.2.0 call test --source=. build: extends: [.dagger] needs: ["test"] script: - dagger -m github.com/kpenfound/dagger-modules/golang@v0.2.0 call build-container --source=. --args=. publish --address=ttl.sh/my-app-$RANDOM ``` -------------------------------- ### Start NGINX Service and Get Endpoint in TypeScript Source: https://docs.dagger.io/cookbook/services Launches an NGINX service, gets its HTTP endpoint, and fetches content. Ensure Dagger is installed. ```TypeScript import { dag, object, func } from "@dagger.io/dagger" @object() export class MyModule { @func() async get(): Promise { // start NGINX service let service = dag.container().from("nginx").withExposedPort(80).asService() service = await service.start() // wait for service to be ready const endpoint = await service.endpoint({ port: 80, scheme: "http" }) // send HTTP request to service endpoint return await dag.http(endpoint).contents() } } ``` -------------------------------- ### Call Toolchain Functions Source: https://docs.dagger.io/getting-started/quickstarts/toolchain Execute functions provided by an installed toolchain. Examples include running tests, building the application, getting a development environment, or publishing the container. ```bash # Build the application dagger call hello build # Get a development environment dagger call hello build-env # Publish after building and testing dagger call hello publish --address=ghcr.io/myorg/hello-dagger:latest ``` -------------------------------- ### Dagger Init Examples Source: https://docs.dagger.io/reference/cli Examples demonstrating how to initialize a new Dagger module using different blueprint and SDK configurations. ```bash # Reference a remote module as blueprint dagger init --blueprint=github.com/example/blueprint # Reference a local module as blueprint dagger init --blueprint=../my/blueprints/simple-webapp # Implement a standalone module in Go dagger init --sdk=go ``` -------------------------------- ### Start NGINX Service and Get Endpoint in Go Source: https://docs.dagger.io/getting-started/types/service Starts an NGINX service, retrieves its HTTP endpoint, and sends a request. Ensure Dagger is configured. ```go package main import ( "context" "dagger/my-module/internal/dagger" ) type MyModule struct{} func (m *MyModule) Get(ctx context.Context) (string, error) { // Start NGINX service service := dag.Container().From("nginx").WithExposedPort(80).AsService() service, err := service.Start(ctx) if err != nil { return "", err } // Wait for service endpoint endpoint, err := service.Endpoint(ctx, dagger.ServiceEndpointOpts{Scheme: "http", Port: 80}) if err != nil { return "", err } // Send HTTP request to service endpoint return dag.HTTP(endpoint).Contents(ctx) } ``` -------------------------------- ### Install Dagger CLI on Linux with install.sh Source: https://docs.dagger.io/getting-started/installation The quickest way to install the latest stable Dagger CLI on Linux is by using the install.sh script, installing it in `$HOME/.local/bin`. ```bash curl -fsSL https://dl.dagger.io/dagger/install.sh | BIN_DIR=$HOME/.local/bin sh ``` -------------------------------- ### Start NGINX Service and Get Endpoint in Go Source: https://docs.dagger.io/cookbook/services Starts an NGINX service, retrieves its HTTP endpoint, and fetches its content. Ensure Dagger is configured. ```Go package main import ( "context" "dagger/my-module/internal/dagger" ) type MyModule struct{} func (m *MyModule) Get(ctx context.Context) (string, error) { // Start NGINX service service := dag.Container().From("nginx").WithExposedPort(80).AsService() sservice, err := service.Start(ctx) if err != nil { return "", err } // Wait for service endpoint endpoint, err := service.Endpoint(ctx, dagger.ServiceEndpointOpts{Scheme: "http", Port: 80}) if err != nil { return "", err } // Send HTTP request to service endpoint return dag.HTTP(endpoint).Contents(ctx) } ``` -------------------------------- ### HealthcheckConfig::timeout() Source: https://docs.dagger.io/reference/php/doc-index Gets the healthcheck timeout duration. Example: 3s ```APIDOC ## HealthcheckConfig::timeout() ### Description Healthcheck timeout. Example:3s ### Method ```php HealthcheckConfig::timeout() ``` ``` -------------------------------- ### Start HTTP Service and Query Endpoint (Java) Source: https://docs.dagger.io/extending/services Starts an NGINX service, retrieves its HTTP endpoint, and sends a GET request. Uses the Dagger Java SDK. ```Java package io.dagger.modules.mymodule; import static io.dagger.client.Dagger.dag; import io.dagger.client.Container; import io.dagger.client.DaggerQueryException; import io.dagger.client.Service; import io.dagger.module.annotation.Function; import io.dagger.module.annotation.Object; import java.util.concurrent.ExecutionException; @Object public class MyModule { @Function public String get() throws ExecutionException, DaggerQueryException, InterruptedException { // Start NGINX service Service service = dag().container() .from("nginx") .withExposedPort(80) .asService(); service = service.start(); // Wait for service endpoint String endpoint = service.endpoint(new Service.EndpointArguments().withScheme("http").withPort(80)); // Send HTTP request to service endpoint return dag().http(endpoint).contents(); } } ``` -------------------------------- ### Build Argument Example Source: https://docs.dagger.io/api/reference Example of a build argument object with name and value. ```json { "name": "abc123", "value": "abc123" } ``` -------------------------------- ### Call Dagger Function to Get Output Source: https://docs.dagger.io/extending/services This example shows how to call a Dagger function named 'get' using the Dagger CLI. It demonstrates interactive mode and direct CLI invocation. ```bash dagger -c get ``` ```bash dagger call get ``` ```bash Hello, world! ``` -------------------------------- ### Install and Use a Toolchain Source: https://docs.dagger.io/core-concepts/toolchains Install a toolchain from GitHub, list its available functions, and then call a specific function. This is the basic workflow for using a toolchain. ```bash # Install from GitHub dagger toolchain install github.com/dagger/jest # See what functions are available dagger functions # Call toolchain functions dagger call jest test # Run all checks dagger check ``` -------------------------------- ### Clone Go Example Repository Source: https://docs.dagger.io/reference/api/internals Clones the Go examples repository and navigates into its directory. This is a prerequisite for the subsequent Dagger queries. ```bash git clone https://github.com/golang/example cd example ``` -------------------------------- ### Execute Redis Commands with Dagger Source: https://docs.dagger.io/extending/services This snippet shows how to start a Redis service, bind it to a container, and execute `SET` and `GET` commands using `redis-cli`. Ensure the Redis service is properly started before executing commands and stopped afterwards. ```java package io.dagger.modules.mymodule; import static io.dagger.client.Dagger.dag; import io.dagger.client.Container; import io.dagger.client.exception.DaggerQueryException; import io.dagger.client.Service; import io.dagger.module.annotation.Function; import io.dagger.module.annotation.Object; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Stream; @Object public class MyModule { /** Explicitly start and stop a Redis service */ @Function public String redisService() throws ExecutionException, DaggerQueryException, InterruptedException { Service redisSrv = dag().container() .from("redis") .withExposedPort(6379) .asService(new Container.AsServiceArguments().withUseEntrypoint(true)); try { // start Redis ahead of time to it stays up for the duration of the test redisSrv = redisSrv.start(); Container redisCli = dag().container().from("redis").withServiceBinding("redis-srv", redisSrv); List args = List.of("redis-cli", "-h", "redis-srv"); // set value String setter = redisCli.withExec(append(args, List.of("set", "foo", "bar"))).stdout(); // get value String getter = redisCli.withExec(append(args, List.of("get", "foo"))).stdout(); return setter + getter; } finally { redisSrv.stop(); } } private List append(List list, List elements) { return Stream.concat(list.stream(), elements.stream()).toList(); } } ``` -------------------------------- ### Basic Dagger Run Commands Source: https://docs.dagger.io/reference/cli These examples demonstrate how to run common development commands like Go, Node.js, and Python scripts using `dagger run`. ```bash dagger run go run main.go ``` ```bash dagger run node index.mjs ``` ```bash dagger run python main.py ``` -------------------------------- ### Dagger Config Examples Source: https://docs.dagger.io/reference/cli Examples demonstrating how to use the 'dagger config' command with different module references, such as local paths or remote Git repositories. ```bash dagger config -m /path/to/some/dir ``` ```bash dagger config -m github.com/dagger/hello-dagger ``` -------------------------------- ### Rust Dagger API Client Example Source: https://docs.dagger.io/getting-started/api/http Connects to the Dagger API using Rust, executes a query to get container information, and prints the stdout. ```rust use base64::encode; use gql_client::Client; use serde_json::Value; use std::collections::HashMap; use std::env; #[tokio::main] async fn main() -> Result<(), Box> { let port = env::var("DAGGER_SESSION_PORT").expect("$DAGGER_SESSION_PORT doesn't exist"); let token = env::var("DAGGER_SESSION_TOKEN").expect("$DAGGER_SESSION_TOKEN doesn't exist"); let query = r#" query { container { from (address: "alpine:latest") { withExec(args:["uname", "-nrio"]) { stdout } } } } "#; let mut headers = HashMap::new(); headers.insert( "authorization", format!("Basic {}", encode(format!({\}:", token))), ); let client = Client::new_with_headers(format!("http://127.0.0.1:{}/query", port), headers); let data = client.query_unwrap::(query).await.unwrap(); println!( "{}", data["container"]["from"]["withExec"]["stdout"] .as_str() .unwrap() ); Ok(()) } ``` -------------------------------- ### Install Package and Fetch Webpage Source: https://docs.dagger.io/getting-started/quickstarts/basics Install 'curl' in an Alpine container, then use it to retrieve content from 'https://dagger.io' and display the output. ```bash container | from alpine | with-exec apk add curl | with-exec curl https://dagger.io | stdout ``` -------------------------------- ### CLI Examples for Publishing Source: https://docs.dagger.io/cookbook Examples of how to publish a container image using the Dagger CLI. ```APIDOC ## Publish Container Image to Docker Hub ### Description Publishes a container image to Docker Hub using the Dagger CLI. ### Method CLI Command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example **System Shell / Dagger Shell:** ```bash dagger -c 'publish docker.io user env://PASSWORD' ``` **Dagger Interactive Mode:** ```bash publish docker.io user env://PASSWORD ``` **Dagger Call Command:** ```bash dagger call publish --registry=docker.io --username=user --password=env://PASSWORD ``` ## Publish Container Image to GitHub Container Registry ### Description Publishes a container image to GitHub Container Registry (GHCR) using the Dagger CLI. ### Method CLI Command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example **System Shell / Dagger Shell:** ```bash dagger -c 'publish ghcr.io user env://PASSWORD' ``` **Dagger Interactive Mode:** ```bash publish ghcr.io user env://PASSWORD ``` **Dagger Call Command:** ```bash dagger call publish --registry=ghcr.io --username=user --password=env://PASSWORD ``` ``` -------------------------------- ### Execute `ls /etc/` in a Container Source: https://docs.dagger.io/extending/chaining Use `withExec()` to run a command in a container and `stdout` to get the output. This example lists the contents of the `/etc/` directory. ```bash dagger < 'Basic ' . base64_encode($sessionToken . ':')] ); // define raw GraphQL query $query = <<runRawQuery($query); print_r($results->getData()->container->from->withExec->stdout); } catch (Exception $e) { print_r($e->getMessage()); exit; } ``` -------------------------------- ### Client::env() Source: https://docs.dagger.io/reference/php/doc-index Initializes a new environment. ```APIDOC ## Client::env() ### Description Initializes a new environment. ### Method (Not specified, likely a method call within the PHP SDK) ### Endpoint (Not applicable for SDK methods) ### Parameters (No parameters specified) ### Request Example (Not applicable for SDK methods) ### Response (No response details specified) ``` -------------------------------- ### Install Dagger Go SDK Source: https://docs.dagger.io/extending/custom-applications/go Install the Dagger Go SDK in an existing Go module. Ensure you are using Go 1.22 or later. ```bash go get dagger.io/dagger@latest ``` -------------------------------- ### Start NGINX Service and Get Endpoint in PHP Source: https://docs.dagger.io/cookbook/services Initializes an NGINX service, retrieves its HTTP endpoint, and fetches content. Requires Dagger PHP SDK. ```PHP container()->from('nginx')->withExposedPort(80)->asService(); $service->start(); // wait for service to be ready $endpoint = $service->endpoint(80, 'http'); // send HTTP request to service endpoint return dag()->http($endpoint)->contents(); } } ``` -------------------------------- ### Build, Publish, and Run Container Source: https://docs.dagger.io/getting-started/quickstarts/basics Create an Alpine container, add a file, set its entrypoint to display the file's content, and publish it to a temporary registry. ```bash container | from alpine | with-new-file /hi.txt "Hello from Dagger!" | with-entrypoint cat /hi.txt | publish ttl.sh/hello ``` -------------------------------- ### Call Dagger Function to Get Member URLs (CLI) Source: https://docs.dagger.io/extending/custom-types Example of calling a Dagger function from the module using the Dagger CLI to retrieve all member URLs. ```bash dagger -c 'dagger-organization | members | url' ``` -------------------------------- ### Start NGINX Service and Get Endpoint in Python Source: https://docs.dagger.io/cookbook/services Initiates an NGINX service, obtains its HTTP endpoint, and retrieves content. Requires Dagger Python SDK. ```Python from dagger import dag, function, object_type @object_type class MyModule: @function async def get(self) -> str: # start NGINX service service = dag.container().from_("nginx").with_exposed_port(80).as_service() await service.start() # wait for service endpoint endpoint = await service.endpoint(port=80, scheme="http") # s end HTTP request to service endpoint return await dag.http(endpoint).contents() ``` -------------------------------- ### Client::envFile() Source: https://docs.dagger.io/reference/php/doc-index Initialize an environment file. ```APIDOC ## Client::envFile() ### Description Initialize an environment file. ### Method (Not specified, likely a method call within the PHP SDK) ### Endpoint (Not applicable for SDK methods) ### Parameters (No parameters specified) ### Request Example (Not applicable for SDK methods) ### Response (No response details specified) ``` -------------------------------- ### List Docker Containers and Check Dagger Version Source: https://docs.dagger.io/reference/container-runtimes/docker This example first lists running Docker containers, then checks the Dagger core version, and finally lists Docker containers again to show the Dagger engine container. ```bash $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES $ dagger core version v0.18.19 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 27d47c3d5a10 registry.dagger.io/engine:v0.18.19 "dagger-entrypoint.s…" 6 days ago Up 4 hours dagger-engine-v0.18.19 ``` -------------------------------- ### Execute Dagger CLI Command Source: https://docs.dagger.io/cookbook/services Demonstrates how to call a Dagger function using the Dagger CLI. This example assumes a Dagger module with a 'get' function is available. ```bash dagger call get ``` -------------------------------- ### Create Interdependent Services with Dagger CLI Source: https://docs.dagger.io/cookbook/services Start two interdependent services using the Dagger CLI. This example shows how to expose ports and manage service dependencies. ```bash dagger -c 'services | up --ports 8080:80' ``` ```bash services | up --ports 8080:80 ``` ```bash dagger call services up --ports 8080:80 ``` -------------------------------- ### Install Dagger CLI with install.sh and sudo Source: https://docs.dagger.io/getting-started/installation If your user account lacks privileges for `/usr/local`, use this command with `sudo -E` to install the Dagger CLI. ```bash curl -fsSL https://dl.dagger.io/dagger/install.sh | BIN_DIR=/usr/local/bin sudo -E sh ``` -------------------------------- ### dagger call hello --help Source: https://docs.dagger.io/extending/documentation Provides help information for calling the 'hello' function, including its arguments. ```APIDOC ## dagger call hello --help ### Description Provides help information for calling the 'hello' function, including its arguments. ### USAGE ``` dagger call hello [arguments] ``` ### ARGUMENTS #### Query Parameters - **--greeting** (string) - Required - The greeting to display - **--name** (string) - Required - Who to greet ``` -------------------------------- ### Call Dagger Function to Get Member URLs (Interactive) Source: https://docs.dagger.io/extending/custom-types Example of calling a Dagger function from the module in Dagger's interactive mode to retrieve all member URLs. ```bash dagger-organization | members | url ``` -------------------------------- ### env Source: https://docs.dagger.io/api/reference Initializes a new environment. ```APIDOC ## env ### Description Initializes a new environment ### Type `Env!` ### Arguments #### Path Parameters - **privileged** (Boolean) - Description: Give the environment the same privileges as the caller: core API including host access, current module, and dependencies. Default = `false` - **writable** (Boolean) - Description: Allow new outputs to be declared and saved in the environment. Default = `false` ``` -------------------------------- ### Call a Dagger Function in Azure Pipelines Source: https://docs.dagger.io/getting-started/ci-integrations/azure-pipelines This example demonstrates calling a simple Dagger Function from an Azure Pipeline. Ensure the Dagger CLI is installed and the DAGGER_CLOUD_TOKEN is set as a secret. ```yaml trigger: - main pool: name: 'Azure Pipelines' vmImage: ubuntu-latest steps: # full clone checkout required to prevent azure pipeline traces from being orphaned in the Dagger Cloud UI - checkout: self fetchDepth: 0 displayName: 'Checkout Source Code, fetch full history' # branch checkout required to prevent azure pipeline traces from being orphaned in the Dagger Cloud UI - script: git checkout $(Build.SourceBranchName) displayName: 'Checkout Source Branch' - script: curl -fsSL https://dl.dagger.io/dagger/install.sh | BIN_DIR=$HOME/.local/bin sh displayName: 'Install Dagger CLI' - script: dagger -m github.com/shykes/daggerverse/hello@v0.1.2 call hello --greeting="bonjour" --name="monde" displayName: 'Call Dagger Function' env: # assumes the Dagger Cloud token is # in a secret named DAGGER_CLOUD_TOKEN # set via the Azure Pipeline settings UI/CLI # the secret is then explicitly mapped to the script env DAGGER_CLOUD_TOKEN: $(DAGGER_CLOUD_TOKEN) ``` -------------------------------- ### Check Podman Containers and Dagger Version Source: https://docs.dagger.io/reference/container-runtimes/podman This example first lists running Podman containers, then checks the Dagger core version, and finally lists Podman containers again to show the Dagger engine container. ```bash $ podman ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES $ dagger core version v0.18.19 $ podman ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 27d47c3d5a10 registry.dagger.io/engine:v0.18.19 "dagger-entrypoint.s…" 6 days ago Up 4 hours dagger-engine-v0.18.19 ``` -------------------------------- ### Create Development Environment Source: https://docs.dagger.io/getting-started/quickstarts/ci Sets up a containerized development environment with necessary dependencies installed. ```java /** Build a ready-to-use development environment */ @Function public Container buildEnv(@DefaultPath("/") Directory source) throws InterruptedException, ExecutionException, DaggerQueryException { CacheVolume nodeCache = dag().cacheVolume("node"); return dag().container() .from("node:21-slim") .withDirectory("/src", source) .withMountedCache("/root/.npm", nodeCache) .withWorkdir("/src") .withExec(List.of("npm", "install")); } ``` -------------------------------- ### Java Dagger Module Definition Source: https://docs.dagger.io/extending/arguments Define a Dagger module in Java with a getUser function. This example also uses Alpine to install necessary tools and fetch user data. ```java package io.dagger.modules.mymodule; import static io.dagger.client.Dagger.dag; import io.dagger.client.exception.DaggerQueryException; import io.dagger.module.annotation.Function; import io.dagger.module.annotation.Object; import java.util.List; import java.util.concurrent.ExecutionException; @Object public class MyModule { @Function public String getUser(String gender) throws ExecutionException, DaggerQueryException, InterruptedException { return dag().container() .from("alpine:latest") .withExec(List.of("apk", "add", "curl")) .withExec(List.of("apk", "add", "jq")) .withExec( List.of( "sh", "-c", "curl https://randomuser.me/api/?gender=%s | jq .results[0].name" .formatted(gender))) .stdout(); } } ``` -------------------------------- ### Dagger Init Options Source: https://docs.dagger.io/reference/cli Options for the 'dagger init' command, including blueprint, SDK, license, and module name. ```bash --blueprint string Reference another module as blueprint --include strings Paths to include when loading the module. Only needed when extra paths are required to build the module. They are expected to be relative to the directory containing the module's dagger.json file (the module source root). --license string License identifier to generate. See https://spdx.org/licenses/ (default "Apache-2.0") --name string Name of the new module (defaults to parent directory name) --sdk string Optionally install a Dagger SDK --source string Source directory used by the installed SDK. Defaults to module root --with-self-calls Enable self-calls capability for the module (experimental) ``` -------------------------------- ### PHP Dagger Function to Get User Name Source: https://docs.dagger.io/extending/functions Create a Dagger Function in PHP using the `#[DaggerObject]` and `#[DaggerFunction]` attributes. This example fetches user data from a remote API. ```php container() ->from('alpine:latest') ->withExec(['apk', 'add', 'curl']) ->withExec(['apk', 'add', 'jq']) ->withExec([ 'sh', '-c', 'curl https://randomuser.me/api/ | jq .results[0].name', ]) ->stdout(); } } ``` -------------------------------- ### Perform Multi-Stage Build and Publish Container (PHP) Source: https://docs.dagger.io/cookbook/builds Builds an application using a Go builder stage and then publishes the resulting binary on an Alpine base image to a registry. Requires Dagger installed. ```php container() ->from('golang:latest') ->withDirectory('/src', $src) ->withWorkdir('/src') ->withEnvVariable('CGO_ENABLED', '0') ->withExec(['go', 'build', '-o', 'myapp']); // publish binary on alpine base $prodImage = dag() ->container() ->from('alpine') ->withFile('/bin/myapp', $builder->file('/src/myapp')) ->withEntrypoint(['/bin/myapp']); // publish to ttl.sh registry $addr = $prodImage->publish('ttl.sh/myapp:latest'); return $addr; } } ``` -------------------------------- ### Get OS Release from Alpine Container Source: https://docs.dagger.io/getting-started/concepts Use the Dagger API to retrieve the contents of the /etc/os-release file from an Alpine container. This example demonstrates sequential function calls to build a workflow. ```bash dagger < str: return await ( dag.container() .from_("alpine:latest") .with_exec(["apk", "add", "curl"]) .with_exec(["apk", "add", "jq"]) .with_exec( ["sh", "-c", "curl https://randomuser.me/api/ | jq .results[0].name"] ) .stdout() ) ``` -------------------------------- ### Perform Multi-Stage Build and Publish Container (Python) Source: https://docs.dagger.io/cookbook/builds Builds an application using a Go builder stage and then publishes the resulting binary on an Alpine base image to a registry. Requires Dagger installed. ```python import dagger from dagger import dag, function, object_type @object_type class MyModule: @function def build(self, src: dagger.Directory) -> str: """Build and publish Docker container""" # build app builder = ( dag.container() .from_("golang:latest") .with_directory("/src", src) .with_workdir("/src") .with_env_variable("CGO_ENABLED", "0") .with_exec(["go", "build", "-o", "myapp"]) ) # publish binary on alpine base prod_image = ( dag.container() .from_("alpine") .with_file("/bin/myapp", builder.file("/src/myapp")) .with_entrypoint(["/bin/myapp"]) ) # publish to ttl.sh registry addr = prod_image.publish("ttl.sh/myapp:latest") return addr ``` -------------------------------- ### Call Dagger Function to Get Member URLs (CLI explicit call) Source: https://docs.dagger.io/extending/custom-types Example of explicitly calling a Dagger function from the module using the Dagger CLI to retrieve all member URLs. ```bash dagger call dagger-organization members url ``` -------------------------------- ### Perform Multi-Stage Build and Publish Container (Go) Source: https://docs.dagger.io/cookbook/builds Builds an application using a Go builder stage and then publishes the resulting binary on an Alpine base image to a registry. Requires a Go toolchain and Dagger installed. ```go package main import ( "context" "dagger/my-module/internal/dagger" ) type MyModule struct{} // Build and publish Docker container func (m *MyModule) Build( ctx context.Context, // source code location // can be local directory or remote Git repository ssrc *dagger.Directory, ) (string, error) { // build app builder := dag.Container(). From("golang:latest"). WithDirectory("/src", src). WithWorkdir("/src"). WithEnvVariable("CGO_ENABLED", "0"). WithExec([]string{"go", "build", "-o", "myapp"}) // publish binary on alpine base prodImage := dag.Container(). From("alpine"). WithFile("/bin/myapp", builder.File("/src/myapp")). WithEntrypoint([]string{"/bin/myapp"}) // publish to ttl.sh registry addr, err := prodImage.Publish(ctx, "ttl.sh/myapp:latest") if err != nil { return "", err } return addr, nil } ``` -------------------------------- ### Basic TeamCity Build with Dagger Recipe Source: https://docs.dagger.io/getting-started/ci-integrations/teamcity This example demonstrates a simple TeamCity build configuration using the Dagger Kotlin DSL to call a Dagger Function. Ensure agents have Docker installed. ```kotlin import jetbrains.buildServer.configs.kotlin.* version = "2025.07" project { buildType(Greeter) } object Greeter : BuildType({ name = "say hi!" // to select agents with Docker requirements { exists("docker.server.version") } steps { step { id = "hello from dagger" // type consists of the "tc:recipe:" prefix followed by the recipe id type = "tc:recipe:jetbrains/dagger@1.0.0" // recipe inputs param("env.input_version", "0.19.2") param("env.input_command", "dagger call -m github.com/shykes/hello hello --greeting \"bonjour\" ") } } }) ``` -------------------------------- ### Install Dagger Client for PHP Source: https://docs.dagger.io/getting-started/api/http Installs the GraphQL client library for PHP using Composer. ```bash mkdir my-project cd my-project composer require gmostafa/php-graphql-client ``` -------------------------------- ### Initialize Dagger Module for Go Source: https://docs.dagger.io/getting-started/api/sdk Initializes a new Dagger module and sets up the development environment for the Go SDK. Ensure you have Go installed. ```bash dagger init --name=my-module dagger develop --sdk=go ``` -------------------------------- ### PHP Dagger Module Definition Source: https://docs.dagger.io/extending/arguments Define a Dagger module in PHP with a getUser function. Similar to the Python example, it uses Alpine to install curl and jq for fetching and parsing user data. ```php container() ->from("alpine:latest") ->withExec(["apk", "add", "curl"]) ->withExec(["apk", "add", "jq"]) ->withExec([ "sh", "-c", "curl https://randomuser.me/api/?gender={$gender} | jq .results[0].name", ]) ->stdout(); } } ``` -------------------------------- ### Interactive Dagger Shell Commands for Redis Module Source: https://docs.dagger.io/extending/services Examples of commands to be run within an interactive Dagger shell session to interact with the Redis module. These commands allow setting and getting values. ```bash set foo 123 get foo ``` -------------------------------- ### Basic Dagger Shell Command Source: https://docs.dagger.io/features/shell A simple example demonstrating how to fetch content from a URL using Dagger Shell. This command fetches the Dagger website content and outputs it. ```bash container | from alpine | with-exec apk add curl | with-exec -- curl -L https://dagger.io | stdout ``` -------------------------------- ### Create and Use HTTP Service in PHP Source: https://docs.dagger.io/cookbook/services Defines Dagger Functions to create and interact with an HTTP service. The httpService function starts a Python HTTP server, and the get function sends a request to it. ```php container() ->from('python') ->withWorkdir('/srv') ->withNewFile('index.html', 'Hello, world!') ->withExposedPort(8080) ->asService(args: ['python', '-m', 'http.server', '8080']); } #[DaggerFunction] #[Doc('Send a request to an HTTP service and return the response')] public function get(): string { return dag() ->container() ->from('alpine') ->withServiceBinding('www', $this->httpService()) ->withExec(['wget', '-O-', 'http://www:8080']) ->stdout(); } } ```