Overview
To trigger a workflow based on an environment parameter in CircleCI, you should use pipeline parameters combined with conditional logic in your configuration. This approach allows you to control which workflows run based on parameter values passed when triggering the pipeline, enabling environment-specific deployments and workflows that respond dynamically to different execution contexts through the CircleCI API.
Setting Up Environment-Based Triggering
Step 1: Define Pipeline Parameters
First, define a pipeline parameter in your config.yml to represent your environment:
version: 2.1
parameters:
environment:
type: string
default: "dev"Step 2: Implement Conditional Logic
Use conditional logic in your config to run workflows based on the parameter value. You have two syntax options:
Expression-Based Filters:
workflows:
deploy:
jobs:
- deploy-job:
filters: pipeline.parameters.environment == "prod"Classic Conditional Syntax:
workflows:
deploy:
when:
equal: [ prod, << pipeline.parameters.environment >> ]
jobs:
- deploy-job
Step 3: Trigger via API
Trigger the pipeline using the CircleCI API v2 and set the parameter value:
curl -X POST https://circleci.com/api/v2/project/<vcs>/<org>/<repo>/pipeline \
--header "Circle-Token: $CIRCLE_TOKEN" \
--header "content-type: application/json" \
--data '{"parameters":{"environment":"prod"}}'With this setup, the deploy workflow will run only when the environment parameter is set to "prod".
Combining Conditions
For more advanced logic, you can use expression-based job filters to combine multiple conditions, such as branch and parameter values:
workflows:
deploy:
jobs:
- deploy-job:
filters: pipeline.git.branch != "main" and pipeline.parameters.my-custom-param starts-with "DEPLOY:"Important API Considerations
API Version Requirement: You must use API v2 to trigger pipelines with parameters. API v1.1 does not support pipeline parameters, so the default value will always be used if you use the older API version.
Parameter Validation: Ensure your parameter values match exactly what your conditional logic expects, as mismatches will cause jobs to be skipped.
Token Authentication: Make sure your Circle-Token has the necessary permissions to trigger pipelines for your project.
Additional Notes
Default Behavior: When no parameter is specified in the API call, the pipeline will use the default value defined in your configuration.
Multiple Parameters: You can define and use multiple pipeline parameters to create sophisticated conditional workflows that respond to various deployment scenarios.
Testing Strategy: Consider implementing a testing workflow that validates your conditional logic works correctly across different parameter combinations.
Environment Management: This approach is particularly useful for managing deployments across different environments (development, staging, production) from a single configuration file.
Comments
Article is closed for comments.