We are going to design a system where the configuration is stored in a Git repository (the "source of truth").
The system will have:
- PR gates: Any change to the configuration must go through a pull request (or merge request) process that includes:
- Review by appropriate team members.
- Automated checks (like schema linting, tests, etc.) that must pass before merging.
- Schema linting: The configuration files must adhere to a defined schema. We will use a linter to validate the configuration against the schema.
- Rollbacks: The ability to quickly revert to a previous known good configuration in case of issues.
Steps:
-
Repository Structure:
- We'll have a dedicated Git repository for the configuration.
- The configuration files can be in a format like YAML, JSON, etc. We assume YAML for this example.
- We'll store the schema for the configuration (as a JSON schema or similar) in the repository.
-
PR Gates:
- We'll use branch protection rules on the main branch (or master) to require:
- At least one approving review.
- Status checks to pass (which will include our linting and possibly other tests).
- We'll set up a CI/CD pipeline (like GitHub Actions, GitLab CI, etc.) that runs on PRs and on push to main.
-
Schema Linting:
- We'll write a script that uses a schema validator (like
ajv for JSON schema, or a custom linter) to check the configuration files.
- The CI will run this linter on every PR and on the main branch.
- The linter will be set to fail if any configuration file does not match the schema.
-
Rollbacks:
- Since the configuration is in Git, we can use Git's history to rollback.
- We can create a script that:
- Checks out a previous commit (by hash, tag, or version) and applies that configuration.
- Alternatively, we can have a mechanism to deploy a specific commit/tag.
- We might also want to have a manual approval for rollbacks, but since we are using Git, we can also just revert the bad commit and deploy the reverted state.
-
Deployment:
- We assume that there is a deployment process that takes the configuration from the Git repository and applies it to the system.
- The deployment should be triggered by a merge to the main branch (or by a tag, or manually).
- We can also have a separate branch for hotfixes if needed.
Implementation Details:
A. Repository Layout:
config-repo/
├── schemas/
│ └── config-schema.json # JSON schema for the configuration
├── config/
│ ├── service1.yaml
│ ├── service2.yaml
│ └── ...
├── scripts/
│ ├── lint.sh # Linting script
│ ├── deploy.sh # Deployment script (or a reference to the actual deployment system)
│ └── rollback.sh # Rollback script
├── .github/
│ └── workflows/
│ └── ci.yml # GitHub Actions workflow (if using GitHub)
└── README.md
B. Linting Script (scripts/lint.sh):
We can use a tool like `yamllint` for basic YAML linting and then a JSON schema validator for the structure.
Example using `ajv-cli` (if we are using JSON schema):
```bash
#!/bin/bash
set -e
# Lint all YAML files in the config directory against the schema
for file in config/*.yaml; do
# Convert YAML to JSON and then validate with ajv
# We can use yq or python to convert, but note that ajv only validates JSON.
# Alternatively, we can use a YAML schema validator that supports JSON schema, but let's assume we convert.
# Using yq (version 4) to convert YAML to JSON
json=$(yq eval -o=json "$file")
# Validate with ajv
echo "Validating $file"
echo "$json" | ajv validate -s schemas/config-schema.json -d /dev/stdin
done
```
However, note that the above might not handle all YAML features (like anchors) correctly. Alternatively, we can use a YAML validator that supports JSON schema.
Alternatively, we can use a tool that directly validates YAML against a JSON schema, such as `jsonschema` for Python (with a YAML loader) or `yamale` (which uses a custom schema) or `cue` (which is more powerful).
Let's consider using `yamale` for simplicity, if we are okay with its schema format.
But if we want to stick to JSON schema, we can use the Python `jsonschema` library with a YAML loader.
Example with `jsonschema` and `pyyaml`:
```python
import yaml
import jsonschema
import sys
import glob
schema_file = 'schemas/config-schema.json'
with open(schema_file, 'r') as f:
schema = json.load(f)
for file in glob.glob('config/*.yaml'):
with open(file, 'r') as f:
data = yaml.safe_load(f)
try:
jsonschema.validate(instance=data, schema=schema)
print(f"{file} is valid")
except jsonschema.exceptions.ValidationError as e:
print(f"{file} is invalid: {e}")
sys.exit(1)
```
We can write this as a Python script and run it in the CI.
C. CI Workflow (GitHub Actions example):
We'll have a workflow that runs on pull requests and on push to main.
```yaml
name: Configuration CI
on:
pull_request:
branches: [ main ]
push:
branches: [ main ]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.9'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pyyaml jsonschema
- name: Lint configuration
run: python scripts/lint.py
```
D. Rollback:
We can have a script that does:
```bash
#!/bin/bash
# rollback.sh
# This script should be run with the commit hash to rollback to as an argument.
if [ $# -ne 1 ]; then
echo "Usage: $0 <commit-hash>"
exit 1
fi
COMMIT_HASH=$1
# Check if the commit exists
if ! git rev-parse --verify "$COMMIT_HASH" >/dev/null 2>&1; then
echo "Commit $COMMIT_HASH does not exist."
exit 1
fi
# Reset the main branch to the commit (if we are on the main branch and want to rollback the configuration repo)
# But note: we might not want to rewrite history? Alternatively, we can revert the commit.
# Option 1: Revert the bad commit and then deploy the reverted state.
# git revert <bad-commit> # This creates a new commit that undoes the changes.
# Option 2: Reset the branch and force push (if we are okay with rewriting history and it's a critical situation).
# git reset --hard $COMMIT_HASH
# git push origin main --force
# However, in a team setting, force pushing is dangerous. Instead, we can:
# Step 1: Create a new branch from the old commit and then merge that branch to main (with PR) if we want to keep the history.
# Step 2: Or, if the bad commit is the latest, we can revert it and then deploy.
# Since we have PR gates, we might want to create a PR to rollback? But in an emergency, we might need to act fast.
# Alternatively, we can have a separate process for rollback that doesn't go through PR if it's an emergency.
# Let's assume we have a separate branch for rollbacks? Or we can do:
# 1. Checkout the old commit.
# 2. Create a new branch from that commit.
# 3. Merge that branch to main (if we are okay with the PR process) or push directly (if we have an emergency procedure).
# But note: the PR gate might be required by the branch protection. So we might need an emergency bypass.
# Alternatively, we can have a script that:
# a. Reverts the bad commit (if it's the latest) and then pushes (if we have the permission to bypass PR?).
# Given the complexity, let's design two ways:
# Normal rollback (non-emergency):
# 1. Find the good commit hash.
# 2. Create a new branch from that commit.
# 3. Open a PR to merge that branch to main (so that the same PR gates apply? But we might want to skip?).
# 4. Alternatively, if we are allowed to bypass, we can just merge without PR? But that breaks the gate.
# Emergency rollback:
# We might have a separate branch (like `hotfix-rollback`) that is protected differently? Or we can have an admin who can force push.
# Given the requirement of PR gates, we might not want to bypass. So the rollback should also go through PR? But in an emergency, we might have to.
# Let's assume we have an emergency procedure that allows a designated person to force push to main after a quick review (maybe a Slack approval?).
# For simplicity, let's assume we are using the standard Git workflow and we don't want to force push. So:
# rollback.sh will:
# 1. Check that the commit exists.
# 2. Create a new branch from that commit (if we are not already on that commit).
# 3. Then we can either:
# a. Open a PR from that branch to main (if we are not on main) and then merge via PR (with the same gates?).
# b. Or, if we are on main and we want to revert the last bad commit, we can do `git revert` and then push (if we have write access and the branch protection allows bypass?).
# But note: the branch protection may require PR for every change. So we cannot push directly to main.
# Therefore, we must create a PR for the rollback.
# So the script might not do the rollback itself, but help in creating a rollback branch and then we open a PR.
# Alternatively, we can have the script do:
# git checkout -b rollback-<commit-hash> <commit-hash>
# git push origin rollback-<commit-hash>
# Then we open a PR from rollback-<commit-hash> to main.
# But note: if the bad commit is already in main, then we are creating a branch from an old commit and then merging that branch to main will effectively revert the changes? Not exactly.
# Actually, if we create a branch from an old commit and then merge to main, Git will try to merge and might create a merge commit that brings back the old state? But if the old commit is an ancestor of the current main, then merging that branch will not change anything? Wait:
# Example:
# main: A - B - C (bad)
# We want to go back to B.
# We create a branch from B: rollback-B.
# Then we merge rollback-B into main. Since main is ahead (has C), the merge will be a fast-forward? No, because main has C and rollback-B is behind. So we cannot fast-forward. The merge will create a new commit that has the changes from B and C? Actually, the merge will bring the state of B? Let's see:
# The tree of B is what we want. The tree of C is bad. When we merge rollback-B (which is at B) into main (at C), Git will try to merge the changes from B to C? Actually, the common ancestor is A? Then the merge will apply the changes from A->B and A->C? That's not what we want.
# What we want is to have the state of B. So we can do:
# Option 1: Revert C (if C is the bad commit). Then we get B's state plus the revert commit.
# Option 2: Reset main to B (but that rewrites history).
# Since we have PR gates and we don't want to rewrite history, we should revert the bad commit(s).
# So the rollback process should be:
# 1. Identify the bad commit(s). Let's say we know the bad commit is C.
# 2. Revert C: `git revert C` (this creates a new commit that undoes C).
# 3. Push the revert commit (via PR?).
# But note: if there are multiple bad commits, we might need to revert a range.
# Alternatively, we can create a branch from B and then do a `git merge -s ours`? That's more complex.
# Given the complexity, we might want to have a more sophisticated rollback script that can:
# - If the bad commit is the latest, revert it and then create a PR with the revert commit.
# - If the bad commit is not the latest, we might need to revert multiple commits? Or we can do a reverse merge of the good branch?
# But note: we might have multiple configuration changes in one PR? Then the bad commit might be a merge commit? Reverting a merge commit is tricky.
# Alternatively, we can do:
# Step 1: Find the last known good commit (LKG).
# Step 2: Create a branch from LKG.
# Step 3: Then, on the main branch, we want to reset to LKG? But that rewrites history.
# Since we are using PR gates, we might not want to rewrite history. So we should revert the changes that are not in LKG.
# How to do that?
# We can do:
# git checkout main
# git revert --no-commit <bad-commit-range> # This will revert all the bad commits, but note that if there are merge commits, we might need to use -m 1 or something.
# But if the bad changes are in multiple commits, we can revert a range:
# git revert --no-commit <oldest-bad>^..<newest-bad>
# Then commit the revert.
# However, if the bad commit is a merge commit, we have to choose a parent.
# Given the complexity, we might decide that:
# - We only allow one configuration change per PR? Then we can easily revert the merge commit of the bad PR.
# But if we allow multiple, we might have to revert multiple commits.
# Alternatively, we can do:
# We have a script that:
# 1. Takes a commit hash (the last known good) and reverts all commits after that.
# But note: if we have multiple bad commits, we want to revert from the LKG to the current HEAD? That's a range.
# Example:
# We have: A (good) - B - C (bad) - D (also bad) - E (current HEAD)
# We want to go back to A.
# We can do:
# git revert --no-commit B^..E # This will revert B, C, D, E? But note that B^ is A, so from A to E? Actually, the range B^..E means from the parent of B (which is A) to E? That includes B? Let's check:
# The range A..E includes B, C, D, E.
# So we want to revert B, C, D, E? That's a lot and might cause conflicts.
# Alternatively, we can do:
# git revert --no-commit E D C B # in reverse order? But note that if they are not linear, it's messy.
# Given the complexity, we might decide that:
# We will only ever have one configuration change per PR and one commit per PR (by squashing). Then the bad commit is the merge commit of the PR? Or the squashed commit?
# If we squash, then each PR becomes one commit. Then we can revert that one commit.
# So we can have a policy: every PR must be squashed when merging.
# Then the rollback is straightforward:
# We revert the bad commit (the one that introduced the bad configuration).
# So the rollback script might be:
# ```bash
# #!/bin/bash
# set -e
# if [ $# -ne 1 ]; then
# echo "Usage: $0 <bad-commit-hash>"
# exit 1
# fi
# BAD_COMMIT=$1
# # Check if the commit exists and is on the main branch?
# if ! git merge-base --is-ancestor $BAD_COMMIT main; then
# echo "Commit $BAD_COMMIT is not in the main branch."
# exit 1
# fi
# # Revert the commit
# git checkout main
# git pull origin main
# git revert --no-commit $BAD_COMMIT
# git commit -m "Rollback: revert $BAD_COMMIT due to issues"
# git push origin main # This will require PR? But we are pushing directly? We are on main and we are pushing? That might be blocked by branch protection.
# ```
# But note: we cannot push directly to main if branch protection requires PR.
# So we must create a branch and then open a PR.
# Alternatively, we can do:
# git checkout -b rollback-$BAD_COMMIT
# git revert $BAD_COMMIT
# git push origin rollback-$BAD_COMMIT
# Then open a PR from rollback-$BAD_COMMIT to main.
# This way, the rollback also goes through the PR gates? But in an emergency, we might want to bypass.
# We can have two modes:
# - Normal: create branch and PR.
# - Emergency: if we are allowed to bypass, we can do:
# git checkout main
# git revert $BAD_COMMIT
# git push origin main --force # if we are allowed to force push? Or without force if the revert is a fast-forward? Actually, reverting creates a new commit, so we can just push.
# But note: if we are on main and we do `git revert $BAD_COMMIT`, we are creating a new commit on main. Then we can push? Only if we have write access and the branch protection allows bypassing? Or if we are using a token that has bypass permissions?
# Given the requirement of PR gates, we probably don't want to bypass. So we should do the PR even for rollback.
# However, in an emergency, we might have a separate process that allows a designated person to push to main (bypassing PR). This is a policy decision.
# Let's assume we want to keep the PR gates for rollback too, but we can have an emergency exception.
# So the script can have an `--emergency` flag that does:
# if emergency; then
# git checkout main
# git pull origin main
# git revert $BAD_COMMIT
# git push origin main # This might fail if branch protection requires PR.
# else
# git checkout -b rollback-$BAD_COMMIT
# git revert $BAD_COMMIT
# git push origin rollback-$BAD_COMMIT
# # Then we need to open a PR. We can use the GitHub CLI or just print instructions.
# fi
# But note: if we are in emergency mode and the branch protection requires PR, the push will fail. So we need to adjust the branch protection or use a different branch?
# Alternatively, we can have a separate branch for emergency rollbacks that is not protected? But that's dangerous.
# Given the complexity, I think we should:
# - Always do rollbacks via PR, even in emergency, but have an accelerated process (like pre-approved reviewers) and use the "draft PR" feature to indicate it's an emergency? Or use a special label?
# Or we can have a rule that allows a specific team to push directly to main in an emergency (bypassing PR). This can be set in the branch protection rules.
# Since this is a design question, we can leave the emergency bypass as a policy.
# Let's design the script for the non-emergency case (PR required) and then note that for emergency we might have a different procedure.
# So:
# Non-emergency rollback script:
# ```bash
# #!/bin/bash
# set -e
# if [ $# -ne 1 ]; then
# echo "Usage: $0 <bad-commit-hash>"
# exit 1
# fi
# BAD_COMMIT=$1
# # Check if the commit exists and is on the main branch.
# if ! git rev-parse --verify "$BAD_COMMIT" >/dev/null 2>&1; then
# echo "Commit $BAD_COMMIT does not exist."
# exit 1
# fi
# if ! git merge-base --is-ancestor "$BAD_COMMIT" main; then
# echo "Commit $BAD_COMMIT is not in the main branch."
# exit 1
# fi
# # Make sure we are up to date.
# git checkout main
# git pull origin main
# # Create a new branch for the rollback.
# BRANCH_NAME="rollback-$BAD_COMMIT"
# git checkout -b "$BRANCH_NAME"
# # Revert the bad commit.
# git revert "$BAD_COMMIT"
# # Push the branch.
# git push origin "$BRANCH_NAME"
# echo "Branch $BRANCH_NAME pushed. Please open a PR to merge $BRANCH_NAME into main."
# ```
# Then we can open a PR manually or with a tool.
# If we want to automate the PR creation, we can use the GitHub CLI:
# ```bash
# gh pr create --base main --head "$BRANCH_NAME" --title "Rollback $BAD_COMMIT" --body "Rollback commit $BAD_COMMIT due to issues."
# ```
# But note: the PR will then go through the same gates (reviews, status checks). We might want to pre-approve the rollback? But that's a policy.
# Alternatively, we can have a special label for rollback PRs that triggers an accelerated review.
# Given the time, we'll leave the PR creation manual or use the CLI if available.
E. Deployment:
We assume that the deployment system (like a CI/CD pipeline) is watching the main branch. When there is a merge to main, it deploys the configuration.
So when we merge the rollback PR, it will deploy the rolled back configuration.
F. Summary:
- We have a Git repository with configuration files and a schema.
- We have a CI that lints the configuration on every PR and on main.
- We have branch protection on main that requires at least one review and passing status checks.
- For rollback, we create a branch from a good commit (or revert the bad commit) and open a PR to main.
G. Additional Considerations:
- We might want to version the configuration schema? Then we can have multiple schema versions and the linter uses the correct one? Or we have one schema that is backward compatible? This depends on the system.
- We might want to have a way to test the configuration in a staging environment before deploying to production. This could be part of the CI: deploy to staging and run tests? But that's beyond the scope.
- We might want to have a way to automatically rollback if a deployment fails? That would require monitoring and an automated rollback process. But our rollback process is manual via PR.
- We might want to tag releases of the configuration? Then we can deploy a specific tag. This could be done by having the deployment system trigger on tags.
- We might want to have a CHANGELOG for the configuration? We can generate it from the PRs.
H. Example Workflow for a Change:
1. Developer creates a branch from main.
2. Developer makes changes to configuration files in `config/`.
3. Developer opens a PR to main.
4. CI runs the linter and any other tests (if we have them) and posts a status.
5. If the linter fails, the PR cannot be merged.
6. If the linter passes, reviewers approve the PR.
7. After approval and passing status, the PR is merged.
8. The deployment system (CI/CD) sees the merge to main and deploys the new configuration.
I. Example Workflow for a Rollback:
1. Identify the bad commit (the one that introduced the problem) on main.
2. Run the rollback script (non-emergency) with the bad commit hash.
3. The script creates a branch, reverts the bad commit, and pushes the branch.
4. Open a PR from the rollback branch to main.
5. The PR goes through the same gates (but we might have a policy that rollback PRs are pre-approved? Or we still require one review?).
6. Once merged, the deployment system deploys the rolled back configuration.
J. Emergency Rollback:
If we need to rollback immediately and cannot wait for PR, we might:
1. Have a designated person (or team) with the ability to bypass branch protection and push directly to main.
2. They can run:
git checkout main
git pull origin main
git revert <bad-commit>
git push origin main
3. This bypasses the PR gates, but note that the linter might not run? We can still run the linter locally before pushing? Or we can have a separate emergency branch that is not protected? But that's risky.
Alternatively, we can have a separate process for emergency that:
- Creates a branch and PR, but then uses the "skip" status checks? That would require the branch protection to allow bypassing for certain users? Or we can have a rule that if the PR has a specific label (like "emergency") then it bypasses the required reviews? But the status checks might still be required.
Given the complexity, we might decide that in an emergency, we do a direct push and then open a PR afterwards to document the rollback? But then the PR would be out of date.
Alternatively, we can have a separate branch for emergency that is set to auto-merge when pushed? That's dangerous.
Given the time, we'll stick to the non-emergency process and note that for emergency we have a separate procedure that might involve:
- A designated person with the ability to force push to main (bypassing branch protection) and then they must run the linter locally and document the rollback in a PR afterwards.
But note: the branch protection might not allow force pushes? We can allow force pushes for certain users? Or we can temporarily disable the branch protection? That's a policy decision.
K. Conclusion:
We have designed a system with:
- Git as the source of truth.
- PR gates with review and status checks (including linting).
- Schema linting in CI.
- Rollback process that creates a PR (non-emergency) or uses an emergency bypass (policy dependent).
We have provided example scripts and CI configuration.
Note: The actual implementation details (like the linter language, CI system, etc.) can be adjusted.
Let's write the rollback script for non-emergency (with PR creation via GitHub CLI) and without emergency bypass.
We assume we are using GitHub and have the gh CLI installed and authenticated.
rollback.sh:
#!/bin/bash
set -e
if [ $# -ne 1 ]; then
echo "Usage: $0 <bad-commit-hash>"
exit 1
fi
BAD_COMMIT=$1
# Check if the commit exists.
if ! git rev-parse --verify "$BAD_COMMIT" >/dev/null 2>&1; then
echo "Commit $BAD_COMMIT does not exist."
exit 1
fi
# Check if we are on the main branch and up to date.
git checkout main
git pull origin main
# Check if the bad commit is in the main branch.
if ! git merge-base --is-ancestor "$BAD_COMMIT" main; then
echo "Commit $BAD_COMMIT is not in the main branch."
exit 1
fi
# Create a new branch for the rollback.
BRANCH_NAME="rollback-$BAD_COMMIT"
git checkout -b "$BRANCH_NAME"
# Revert the bad commit. This creates a new commit that undoes the changes.
git revert "$BAD_COMMIT"
# Push the branch.
git push origin "$BRANCH_NAME"
# Create a PR using GitHub CLI.
gh pr create --base main --head "$BRANCH_NAME" \
--title "Rollback $BAD_COMMIT" \
--body "Rollback commit $BAD_COMMIT due to issues. This reverts the changes introduced in that commit."
echo "PR created. Please assign reviewers and merge after approval."
For emergency, we might have:
#!/bin/bash
set -e
if [ $# -ne 1 ]; then
echo "Usage: $0 <bad-commit-hash> [--emergency]"
exit 1
fi
BAD_COMMIT=$1
EMERGENCY=false
if [ "$2" = "--emergency" ]; then
EMERGENCY=true
fi
if ! git rev-parse --verify "$BAD_COMMIT" >/dev/null 2>&1; then
echo "Commit $BAD_COMMIT does not exist."
exit 1
fi
git checkout main
git pull origin main
if ! git merge-base --is-ancestor "$BAD_COMMIT" main; then
echo "Commit $BAD_COMMIT is not in the main branch."
exit 1
fi
if [ "$EMERGENCY" = true ]; then
# Emergency: revert and push directly to main (bypassing PR)
# Note: This may fail if branch protection requires PR.
git revert "$BAD_COMMIT"
git push origin main
echo "Emergency rollback pushed directly to main. Please document this in a PR afterwards if possible."
else
# Non-emergency: create branch and PR.
BRANCH_NAME="rollback-$BAD_COMMIT"
git checkout -b "$BRANCH_NAME"
git revert "$BAD_COMMIT"
git push origin "$BRANCH_NAME"
gh pr create --base main --head "$BRANCH_NAME" \
--title "Rollback $BAD_COMMIT" \
--body "Rollback commit $BAD_COMMIT due to issues. This reverts the changes introduced in that commit."
echo "PR created. Please assign reviewers and merge after approval."
fi
But note: the emergency push might fail if we don't have permission. Also, we are not running the linter in the emergency case? We should at least lint locally?
We can modify the emergency case to run the linter first:
if [ "$EMERGENCY" = true ]; then
# Run linter on the current state (after revert) to make sure we are not introducing invalid config?
# But note: we are reverting to a known good state, so it should be valid.
# Still, we can run the linter on the entire config directory.
echo "Running linter on the configuration after revert..."
./scripts/lint.sh
if [ $? -ne 0 ]; then
echo "Linter failed. Aborting emergency rollback."
exit 1
fi
git revert "$BAD_COMMIT"
git push origin main
...
This is getting complex. We might decide that for emergency, we do not run the linter because we are reverting to a known good state? But what if the revert doesn't apply cleanly? Then we might have conflicts and we fix them? Then we must lint again.
Given the time, we'll leave the emergency case as is (without linter) and note that it's a risk.
Alternatively, we can run the linter after the revert and before pushing, and if it fails, we abort.
Let's adjust the emergency case:
if [ "$EMERGENCY" = true ]; then
# Revert the commit (this might cause conflicts, we need to handle that? We assume it's a clean revert because we are reverting a single commit that was previously merged).
git revert "$BAD_COMMIT"
# Run linter on the entire config.
./scripts/lint.sh
git push origin main
...
But note: if there are conflicts in the revert, we have to resolve them and then stage and continue the revert? The git revert might fail and we have to handle that.
Given the complexity, we might want to avoid emergency bypass and always use the PR process.
Final note: This is a design. The actual implementation may vary.
Let me know if you have any questions.
I'll design a comprehensive git-based configuration management system with PR gates, schema validation, and safe rollback capabilities.
Git-Based Config Source of Truth Architecture
1. Repository Structure
config-repo/
├── config/
│ ├── services/
│ │ ├── auth-service.yaml
│ │ ├── payment-service.yaml
│ │ └── schemas/
│ │ ├── auth-service-schema.json
│ │ └── payment-service-schema.json
│ ├── environments/
│ │ ├── production.yaml
│ │ ├── staging.yaml
│ │ └── development.yaml
│ └── global/
│ ├── network-policy.yaml
│ └── security-baseline.yaml
├── .github/
│ ├── workflows/
│ │ ├── validate-schema.yml
│ │ ├── test-config.yml
│ │ └── deploy-approval.yml
│ └── dependabot.yml
├── scripts/
│ ├── lint-configs.sh
│ ├── validate-schema.js
│ ├── deploy.sh
│ ├── rollback.sh
│ └── diff-prod.sh
├── .pre-commit-config.yaml
├── Makefile
└── README.md
2. PR Gate Implementation
A. Branch Protection Rules (GitHub/GitLab)
# GitHub Branch Protection for main
required_pull_request_reviews:
required_approving_review_count: 1
dismiss_stale_reviews: true
require_code_owner_reviews: true
restriction: true # Only specific teams can approve
required_status_checks:
- "Schema Validation"
- "Config Lint"
- "Security Scan"
- "Integration Tests"
enforce_admins: false
restrictions:
teams:
- "platform-team"
- "sre-team"
B. Pre-commit Hooks
# .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-yaml
- id: check-merge-conflict
- id: trailing-whitespace
- repo: https://github.com/jumanjihouse/pre-commit-hook-yamlfmt
rev: v0.2.2
hooks:
- id: yamlfmt
args: [--mapping, '2', --sequence, '4', --offset, '0']
- repo: local
hooks:
- id: config-lint
name: Validate configuration files
entry: bash scripts/lint-configs.sh
language: system
pass_filenames: false
3. Schema Linting & Validation
A. JSON Schema Example (config/services/schemas/auth-service-schema.json)
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["service_name", "port", "replicas"],
"properties": {
"service_name": {
"type": "string",
"pattern": "^[a-z]+-[a-z]+$"
},
"port": {
"type": "integer",
"minimum": 1000,
"maximum": 65535
},
"replicas": {
"type": "integer",
"minimum": 1,
"maximum": 50
},
"resources": {
"type": "object",
"properties": {
"cpu": {"type": "string", "pattern": "^[0-9]+m$"},
"memory": {"type": "string", "pattern": "^[0-9]+[MG]i$"}
}
}
},
"additionalProperties": false
}
B. Linting Script (scripts/lint-configs.sh)
#!/bin/bash
set -euo pipefail
CONFIG_DIR="config"
SCHEMA_DIR="$CONFIG_DIR/services/schemas"
FAILED=0
echo "=== Starting Configuration Lint ==="
# 1. Check YAML syntax
echo "1. Validating YAML syntax..."
for file in $(find $CONFIG_DIR -name "*.yaml" -o -name "*.yml"); do
if ! yamllint "$file" > /dev/null 2>&1; then
echo "❌ YAML syntax error in $file"
FAILED=1
else
echo "✓ $file"
fi
done
# 2. Schema validation
echo -e "\n2. Validating against schemas..."
for service_dir in $CONFIG_DIR/services/*/; do
service_name=$(basename "$service_dir")
schema_file="$SCHEMA_DIR/${service_name}-schema.json"
config_file="$service_dir${service_name}.yaml"
if [[ -f "$schema_file" && -f "$config_file" ]]; then
echo "Validating $config_file against $schema_file"
if ! npx ajv compile -s "$schema_file" --strict=false; then
echo "❌ Schema compilation failed for $schema_file"
FAILED=1
fi
if ! npx ajv validate -s "$schema_file" -d "$config_file" --strict=false; then
echo "❌ Validation failed for $config_file"
FAILED=1
fi
fi
done
# 3. Cross-reference validation
echo -e "\n3. Checking cross-references..."
# Example: Ensure all services referenced in network policies exist
./scripts/validate-references.js
echo -e "\n=== Lint Complete ==="
if [[ $FAILED -eq 1 ]]; then
echo "❌ Linting failed. Fix errors before committing."
exit 1
else
echo "✅ All checks passed!"
exit 0
fi
C. CI/CD Validation Pipeline (.github/workflows/validate-schema.yml)
name: Configuration Validation
on:
pull_request:
paths:
- 'config/**'
- '.github/workflows/validate-schema.yml'
- 'scripts/**'
- '!**.md'
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: |
npm install -g ajv-cli yamllint
npm ci
- name: Lint configurations
run: bash scripts/lint-configs.sh
- name: Check for secrets
uses: trufflesecurity/trufflehog@main
with:
path: ./
base: ${{ github.event.pull_request.base.sha }}
head: ${{ github.event.pull_request.head.sha }}
- name: Diff against production
run: bash scripts/diff-prod.sh
env:
PROD_CONFIG_BRANCH: production-config
4. Deployment & Rollback System
A. Deployment Script (scripts/deploy.sh)
#!/bin/bash
set -euo pipefail
ENVIRONMENT=${1:-staging}
CONFIG_BRANCH=${2:-main}
DEPLOY_ID="deploy-$(date +%Y%m%d-%H%M%S)"
echo "🚀 Starting deployment to $ENVIRONMENT (ID: $DEPLOY_ID)"
# 1. Archive current config
mkdir -p "deploy-archives/$ENVIRONMENT"
git archive $CONFIG_BRANCH config/ > "deploy-archives/$ENVIRONMENT/$DEPLOY_ID.tar"
# 2. Validate target environment
ENV_FILE="config/environments/$ENVIRONMENT.yaml"
if [[ ! -f "$ENV_FILE" ]]; then
echo "❌ Environment file $ENV_FILE not found!"
exit 1
fi
# 3. Run pre-deployment checks
echo "Running pre-deployment checks..."
./scripts/lint-configs.sh
# 4. Deploy to target (example: kubectl)
echo "Applying configuration to $ENVIRONMENT..."
kubectl apply -f config/services/ -f config/environments/$ENVIRONMENT.yaml --dry-run=client | kubectl apply -f -
# 5. Record deployment
echo "$DEPLOY_ID $(date -u) $ENVIRONMENT $CONFIG_BRANCH $(git rev-parse $CONFIG_BRANCH)" >> deploy-history.txt
# 6. Post-deployment verification
echo "Running post-deployment smoke tests..."
./scripts/verify-deployment.sh $ENVIRONMENT
echo "✅ Deployment $DEPLOY_ID completed successfully!"
B. Automated Rollback Script (scripts/rollback.sh)
#!/bin/bash
set -euo pipefail
ENVIRONMENT=${1:-production}
TARGET_DEPLOY_ID=${2:-}
# 1. Find last known good deployment
if [[ -z "$TARGET_DEPLOY_ID" ]]; then
LAST_GOOD=$(grep "$ENVIRONMENT" deploy-history.txt | tail -1 | awk '{print $1}')
TARGET_DEPLOY_ID=${LAST_GOOD:-}
fi
if [[ -z "$TARGET_DEPLOY_ID" ]]; then
echo "❌ No deployment history found for $ENVIRONMENT"
exit 1
fi
echo "🔄 Rolling back $ENVIRONMENT to deployment $TARGET_DEPLOY_ID"
# 2. Verify archive exists
ARCHIVE="deploy-archives/$ENVIRONMENT/$TARGET_DEPLOY_ID.tar"
if [[ ! -f "$ARCHIVE" ]]; then
echo "❌ Archive $ARCHIVE not found!"
exit 1
fi
# 3. Restore configuration
tar -xf "$ARCHIVE" -C /tmp/config-restore/
# 4. Apply rollback
echo "Applying rolled back configuration..."
kubectl apply -f /tmp/config-restore/config/ --dry-run=client | kubectl apply -f -
# 5. Record rollback
ROLLBACK_ID="rollback-$(date +%Y%m%d-%H%M%S)"
echo "$ROLLBACK_ID rolled back $ENVIRONMENT from $TARGET_DEPLOY_ID $(date -u)" >> rollback-history.txt
# 6. Alert team
./scripts/alert-rollback.sh "$ENVIRONMENT" "$TARGET_DEPLOY_ID" "$ROLLBACK_ID"
echo "✅ Rollback to $TARGET_DEPLOY_ID completed!"
C. One-Click Rollback via GitHub Issue
# .github/workflows/rollback.yml
name: Emergency Rollback
on:
issues:
types: [opened]
labels: [emergency-rollback]
jobs:
rollback:
if: contains(github.event.issue.title, 'ROLLBACK')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Extract rollback target
id: extract
run: |
TARGET=$(echo "${{ github.event.issue.title }}" | grep -oP '(?<=ROLLBACK TO: ).*')
echo "target=$TARGET" >> $GITHUB_OUTPUT
- name: Execute rollback
run: |
bash scripts/rollback.sh production ${{ steps.extract.outputs.target }}
env:
KUBECONFIG: ${{ secrets.KUBECONFIG_PROD }}
- name: Comment on issue
uses: actions/github-script@v6
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
body: '✅ Rollback to ${{ steps.extract.outputs.target }} initiated. Monitor deployment status.'
})
5. Safety Mechanisms
A. Deployment Freeze Conditions
# scripts/should-deploy.sh - gates before deployment
#!/bin/bash
# 1. Time-based restrictions
HOUR=$(date +%H)
if [[ $HOUR -ge 22 || $HOUR -lt 6 ]]; then
echo "❌ Deployments only allowed 6AM-10PM"
exit 1
fi
# 2. Business hours check (configurable)
if [[ "$(date +%u)" -ge 6 ]]; then # Weekend
echo "⚠️ Weekend deployment requires approval"
# Send Slack approval request
fi
# 3. Critical period check (e.g., quarterly close)
if ./scripts/is-critical-period.sh; then
echo "❌ Critical business period - deployments frozen"
exit 1
fi
# 4. Recent failure check
if ./scripts/has-recent-failure.sh; then
echo "❌ Recent production failure detected - manual review required"
exit 1
fi
B. Configuration Diff Tool (scripts/diff-prod.sh)
#!/bin/bash
# Compare PR config against current production
PR_BRANCH=$1
PROD_BRANCH="production-config"
echo "=== Configuration Diff: PR vs Production ==="
# 1. Extract changed files
CHANGED=$(git diff --name-only $PROD_BRANCH $PR_BRANCH -- config/)
# 2. For each changed file, show diff with context
for file in $CHANGED; do
echo -e "\n📄 $file"
git diff $PROD_BRANCH $PR_BRANCH -- "$file" | \
grep -E "^[\+\-]" | \
sed 's/^/ /' | \
head -20
done
# 3. Generate impact summary
echo -e "\n=== Impact Summary ==="
echo "Services affected: $(echo "$CHANGED" | grep 'config/services/' | cut -d/ -f3 | sort -u)"
echo "Environments affected: $(echo "$CHANGED" | grep 'config/environments/' | cut -d/ -f3 | sort -u)"
echo "Total files changed: $(echo "$CHANGED" | wc -l)"
6. Monitoring & Alerting
A. Deployment Dashboard (Simple HTML/JS)
<!-- deploy-dashboard.html -->
<script>
async function loadDeployments() {
const response = await fetch('/deploy-history.json');
const data = await response.json();
// Render deployment timeline
// Show rollback buttons for recent deployments
// Display health metrics
}
</script>
B. Health Check Integration
# scripts/verify-deployment.sh
#!/bin/bash
ENVIRONMENT=$1
SERVICE_TIMEOUT=30
echo "Verifying deployment health..."
# 1. Check pod status
kubectl get pods -n $ENVIRONMENT --field-selector=status.phase!=Running
# 2. Check service endpoints
kubectl get endpoints -n $ENVIRONMENT
# 3. Run smoke tests
for service in $(kubectl get svc -n $ENVIRONMENT -o jsonpath='{.items[*].metadata.name}'); do
if ! timeout $SERVICE_TIMEOUT curl -s "http://$service.${ENVIRONMENT}.svc.cluster.local/health"; then
echo "❌ Health check failed for $service"
exit 1
fi
done
echo "✅ All services healthy!"
7. Emergency Procedures
A. Runbook for Rollback
## Emergency Rollback Procedure
1. **Identify Issue**
```bash
kubectl get pods --sort-by=.status.startTime
kubectl logs -l app=<service> --tail=100
-
Find Last Good Deployment
cat deploy-history.txt | grep production | tail -5
-
Execute Rollback
# Option A: Automated rollback to last known good
./scripts/rollback.sh production
# Option B: Rollback to specific deployment
./scripts/rollback.sh production deploy-20240101-120000
-
Verify
./scripts/verify-deployment.sh production
-
Post-Mortem
- Create incident report
- Update schema/validation rules
- Document root cause
#### **B. Circuit Breaker Pattern**
```yaml
# config/global/circuit-breaker.yaml
circuit_breakers:
- service: payment-service
threshold: 5 # failures
timeout: 30 # seconds
reset_timeout: 60
- service: auth-service
threshold: 3
timeout: 10
8. Key Features Summary
| Feature | Implementation | Tooling |
|---|
| PR Gates | Branch protection + required reviews | GitHub/GitLab protected branches |
| Schema Lint | JSON Schema validation | ajv-cli, yamllint |
| Pre-commit Hooks | Local validation before commit | pre-commit framework |
| CI/CD Gates | Automated validation pipeline | GitHub Actions/GitLab CI |
| Deployment History | Immutable archives | Git tags + tar archives |
| One-Click Rollback | GitHub Issue automation | GitHub Actions + scripts |
| Safety Checks | Time-based, health checks | Custom scripts + kubectl |
| Audit Trail | Git history + deploy logs | Git + deploy-history.txt |
| Diff Visualization | PR vs production diff | Custom diff script |
| Emergency Bypass | Special labels + approvals | Issue-based workflows |
9. Setup Commands
# Initialize repository
git init config-repo
cd config-repo
# Setup pre-commit
pre-commit install
# Install dependencies
npm install -g ajv-cli yamllint
pip install pyyaml jsonschema # Optional Python alternative
# Setup CI/CD
mkdir -p .github/workflows
# Copy workflow files from above
# First deployment
./scripts/deploy.sh staging
10. Best Practices
-
Schema-First Development
- Always update schema before config changes
- Schema changes require separate PR with migration guide
-
Immutable Deployments
- Never modify deployed config directly
- Always create new deployment archive
-
Gradual Rollout
# Deploy to canary first
ENVIRONMENT=canary ./scripts/deploy.sh
# Wait 5 minutes, verify health
# Then promote to production
-
Configuration Versioning
- Tag each deployment:
git tag deploy-20240101-120000
- Maintain
CURRENT_DEPLOYMENT file in repo
-
Access Control
- Only platform team can merge to main
- Emergency rollback requires 2 approvals
- All actions logged to audit trail
This system provides:
- Safety: Multiple validation gates, rollback capability
- Auditability: Full Git history + deployment logs
- Automation: CI/CD integration, one-click rollback
- Visibility: Dashboards, diff tools, health checks
- Control: Branch protection, approval workflows, time-based restrictions
The key principle: Every change is tracked, validated, and reversible.