Git in DevOps and CI/CDIntroduction and ContextDevOps connects software development, operations, security, and business delivery through shared practices and automation. Git is central to this connection because it records changes to application code, configuration, infrastructure definitions, documentation, and pipeline specifications. A Git commit is therefore more than a saved programming change: it can become the event that initiates compilation, testing, security analysis, deployment, and infrastructure reconciliation. Continuous integration (CI) is the practice of frequently integrating changes into a shared repository and automatically validating them. Continuous delivery (CD) keeps software in a releasable state, while continuous deployment automatically releases qualifying changes to production. Git provides the traceability and event model needed to coordinate these activities. This chapter explains how Git events connect with CI/CD pipelines, environments, security controls, infrastructure as code (IaC), GitOps, and rollback practices. Learning ObjectivesBy the end of this chapter, you should be able to: - explain how Git commits, branches, tags, and pull requests trigger automation;
- distinguish CI, continuous delivery, and continuous deployment;
- describe the stages and controls of a modern delivery pipeline;
- connect Git workflows with testing, security, deployment, and IaC;
- compare rollback, roll-forward, and Git-revert strategies;
- design a basic environment promotion model;
- identify governance, security, and operational risks in Git-based delivery.
1. Git as the Control Plane for DeliveryA Git repository can contain several related forms of delivery knowledge: - Application source: program code and tests.
- Build instructions: Dockerfiles, makefiles, package manifests, and build scripts.
- Pipeline definitions: YAML or declarative workflow files.
- Configuration: environment-specific settings, preferably without secrets.
- Infrastructure code: Terraform, CloudFormation, Kubernetes manifests, or similar definitions.
- Documentation: operational procedures, architecture decisions, and runbooks.
A commit identifies a precise state of these artifacts. A commit hash allows a team to answer: What was built? Which tests ran? Which dependencies were used? Who approved the change? What was deployed, and when? Common Git events include: | Git event | Typical automation use |
|---|
| Push to a feature branch | Fast checks and unit tests | | Pull request opened or updated | Review validation, integration tests, static analysis | | Merge to main | Build an official artifact and deploy to a test environment | | Creation of a tag | Release packaging and production approval | | Revert commit | Restore a known repository state through the normal pipeline | | Scheduled event | Dependency scans, drift checks, or maintenance jobs |
A webhook communicates an event from a Git hosting platform to an automation service. The automation service should authenticate the request, inspect the event type and target branch, and then select an appropriate workflow. The event itself is not sufficient evidence that a deployment is safe; policy, tests, approvals, and environment controls remain necessary. 2. CI, Continuous Delivery, and Continuous DeploymentThese terms describe related but distinct capabilities. Continuous integration validates changes frequently. Developers integrate small changes, and automated jobs compile code, run tests, and identify defects early. Continuous delivery extends CI by automatically preparing a deployable release. Deployment to production may require a human approval or a business decision. Continuous deployment removes that manual production decision for changes that satisfy defined controls. Every qualifying change may be released automatically. A useful conceptual sequence is: commit → validate → build → secure → package → deploy → observe
The sequence is not always strictly linear. For example, security checks can occur during source analysis, dependency resolution, image construction, and runtime deployment. Some systems also run tests in parallel to reduce waiting time. Pipeline stagesA practical pipeline commonly includes the following stages: - Checkout: retrieve the exact commit, preferably by immutable identifier.
- Dependency installation: resolve declared dependencies using a lock file where available.
- Static validation: check formatting, syntax, type correctness, and policy.
- Testing: execute unit, integration, contract, end-to-end, and performance tests as appropriate.
- Build: create a binary, package, or container image.
- Security analysis: scan source, dependencies, secrets, images, and IaC.
- Artifact publication: store the immutable output in an artifact repository.
- Deployment: apply the artifact to a selected environment.
- Verification: inspect health checks, logs, metrics, and business outcomes.
- Promotion or recovery: approve promotion, pause, roll back, or roll forward.
A strong design separates build once from deploy many. The artifact tested in CI should be the same artifact promoted through environments. Rebuilding separately for staging and production can produce differences and weakens traceability. 3. Branches, Pull Requests, and Release ControlsBranches provide different lines of development, but they are not themselves environments. A branch is a version-control concept; an environment is an operational target with resources, configuration, access controls, and monitoring. A lightweight workflow may use short-lived feature branches merged into main. A more controlled organization may maintain release branches for stabilization. The choice should reflect release frequency, product risk, team size, and regulatory requirements rather than tradition alone. Pull requests provide a control point for: - peer review;
- automated validation;
- change discussion;
- ownership checks;
- security and compliance evidence;
- approval before protected-branch updates.
Protected branches can require successful checks, signed commits, multiple reviewers, and restrictions on force-pushing. These controls reduce accidental changes but do not replace testing or operational observation. Tags are useful for identifying releases, for example v2.4.1. A robust release process records both the tag and the commit hash. Tags should be protected against unauthorized modification, because moving a release tag can destroy audit clarity. 4. Testing as a Delivery DecisionTesting in CI should be layered. Fast tests provide rapid feedback, while slower tests provide broader confidence. | Test type | Main purpose | Typical pipeline location |
|---|
| Unit | Validate isolated logic | Every change | | Static analysis | Detect code and style defects | Every change | | Integration | Validate component interaction | Pull request or main branch | | Contract | Check service interface compatibility | Pull request and release | | End-to-end | Validate user journeys | Main branch or pre-release | | Performance | Measure response and capacity characteristics | Scheduled or release pipeline | | Smoke/health | Confirm basic deployment operation | Immediately after deployment |
A passing pipeline does not prove that software is defect-free. Tests are samples of possible behavior. Their value depends on coverage, realism, maintenance, and the quality of assertions. Flaky tests are particularly harmful because they train teams to rerun pipelines instead of investigating failures. Test data should avoid exposing personal or confidential information. Production-like data may improve realism, but it requires masking, access control, retention limits, and documented authorization. 5. Security in Git-Based PipelinesDevSecOps embeds security throughout the delivery lifecycle rather than placing it only before production release. Important controls include: - secret scanning in commits and repositories;
- dependency and software composition analysis;
- static application security testing;
- container image scanning;
- infrastructure-as-code scanning;
- dynamic testing in a controlled environment;
- least-privilege credentials for runners;
- signed commits, artifacts, or attestations where justified;
- audit logs for approvals and deployments.
Secrets should not be stored in ordinary Git history. Removing a secret from the latest file does not remove it from earlier commits, forks, caches, or logs. If exposure occurs, the correct response includes immediate revocation and replacement, followed by history cleanup where appropriate. Pipeline code is production-sensitive code. An attacker who modifies a workflow may exfiltrate credentials, alter an artifact, or deploy unauthorized software. Workflow changes should therefore receive review, use pinned or verified action versions when possible, and run with narrowly scoped permissions. Security gates should be risk-based. A critical vulnerability in a production dependency may block release, while a low-confidence informational finding may create a ticket. Blindly blocking every finding can cause teams to disable the control. 6. Artifacts, Reproducibility, and Supply-Chain IntegrityThe pipeline should produce a traceable artifact from a known source commit and declared dependency set. Useful metadata includes: - source commit hash;
- build timestamp;
- compiler or runtime version;
- dependency versions;
- test results;
- vulnerability findings;
- builder identity;
- provenance or attestation data.
Reproducible builds aim to generate equivalent outputs when the same source and controlled inputs are used. Perfect reproducibility can be difficult because timestamps, network dependencies, operating-system differences, and nondeterministic tools may affect output. Lock files, pinned base images, isolated builds, and controlled toolchains improve consistency. An artifact repository should retain release artifacts according to a documented policy. Deleting artifacts that are still required for rollback creates operational risk. Conversely, indefinite retention can increase cost and exposure. 7. Environments and PromotionTypical environments include development, testing, staging, and production. They differ in data, scale, access, integrations, and operational risk. A promotion model should answer: - What artifact is being promoted?
- Which automated and human checks are required?
- Who can approve the transition?
- How is environment configuration supplied?
- What evidence demonstrates successful operation?
- What is the recovery procedure?
Configuration should be externalized from the artifact when it varies by environment. However, externalization must not become an excuse for undocumented manual changes. Configuration belongs under version control where practical, with secrets referenced from an approved secret manager. Deployment strategies include: - Recreate: stop the old version and start the new version; simple but may cause downtime.
- Rolling: replace instances gradually; reduces disruption but requires compatibility.
- Blue-green: maintain two production environments and switch traffic; enables rapid switching but costs more.
- Canary: send a small proportion of traffic to the new version before expanding; requires effective monitoring.
- Feature flags: deploy code while controlling feature exposure separately; flags require lifecycle management.
8. Infrastructure as Code and GitOpsInfrastructure as code represents infrastructure in declarative files. A desired state may specify networks, permissions, compute resources, databases, or Kubernetes objects. Git provides review, history, and collaboration for these definitions. A safe IaC workflow normally includes formatting, validation, security scanning, a plan or preview, peer review, and controlled application. The preview should be examined for destructive operations, unexpected permission changes, and resource replacement. GitOps applies a related principle to operations: Git stores the desired state, and an agent in the target environment continuously reconciles actual state toward that desired state. In a push model, the pipeline directly applies changes. In a pull model, an agent retrieves approved state from Git and applies it. Pull-based systems can reduce inbound access to clusters, but they still require repository protection, identity controls, and monitoring. GitOps is not merely “deploying YAML from Git.” It requires a trustworthy source of desired state, reconciliation, drift visibility, and a defined method for emergency changes. Manual production changes that are never represented in Git create configuration drift and weaken recovery. 9. Rollback, Roll-Forward, and RecoveryA rollback returns a service to a prior operational version or configuration. A Git revert creates a new commit that reverses an earlier change; it preserves history and normally triggers the pipeline again. Reverting is different from resetting a branch, which rewrites history and is generally unsuitable for shared protected branches. Rollback options include: - redeploying a previously verified artifact;
- switching traffic from blue to green;
- reverting the change in Git;
- disabling a feature flag;
- restoring a compatible database backup.
Database changes require special care. Application rollback may fail if the newer version has changed the schema incompatibly. Backward-compatible expand-and-contract migrations are safer: first add compatible structures, then deploy code using them, and remove obsolete structures only after all older versions are gone. Roll-forward means correcting the defect with a new change rather than returning to an older version. It is often preferable when data migrations or security fixes make reversal unsafe. A recovery plan should specify detection signals, decision authority, commands or workflow links, communication responsibilities, and verification steps. Recovery should be tested periodically rather than assumed to work. 10. Observability and FeedbackA delivery pipeline is incomplete without feedback after deployment. Observability combines logs, metrics, traces, health checks, and user or business indicators. Examples of useful deployment signals include error rate, latency, saturation, queue depth, crash frequency, and successful transaction rate. A deployment may be technically successful while harming a business outcome, such as payment completion or order processing. Automated progressive delivery can compare a new release with a baseline. The comparison must account for traffic volume, time window, seasonality, and normal variation. An alert should lead to a defined action: pause promotion, reduce traffic, notify an owner, or initiate recovery. 11. Illustrative Case: Online Retail Release PipelineBackground. An online retailer maintains a web application, payment service, and Kubernetes infrastructure. Developers previously built artifacts separately for testing and production. Releases were made manually, and a failed payment deployment caused several hours of disruption. Problem. The organization could not reliably identify which source version was running. Configuration differed between environments, secrets appeared in a pipeline log, and rollback was uncertain because database migrations were irreversible. Analysis. The team mapped the delivery path from pull request to production. It found that testing was incomplete, artifact identity was not recorded, production access was broadly shared, and the database migration was coupled to the application release. Approach. The retailer introduced the following process: - Pull requests run unit, integration, static, dependency, and secret scans.
- A merge to
main builds one container image identified by commit hash. - The image is signed and stored in an artifact repository.
- IaC changes produce a reviewed plan before application.
- The same image is deployed to staging and then to production.
- Production uses canary traffic with automated health and business checks.
- Database changes use expand-and-contract migrations.
- Deployment credentials are short-lived and environment-specific.
- A revert or traffic switch is available through a controlled workflow.
- Deployment records link the commit, approvals, artifact, environment, and outcome.
Outcome. Release frequency increased, manual deployment steps decreased, and incident investigation became faster. The team also discovered that pipeline success alone was insufficient: payment success rate became a required post-deployment signal. Learning points. Traceability requires immutable artifacts, not merely a branch name. Security must include pipeline permissions and logs. Rollback design begins before deployment, especially when data changes are involved. Finally, Git-based automation improves reliability only when repository governance and operational observability are also mature. 12. Governance, Ethics, and Professional PracticeAutomation affects access to systems and can influence users, employees, and customers. Professional practice therefore includes: - separation of duties for high-risk production changes;
- auditable approvals without meaningless rubber-stamping;
- protection of personal and confidential data in test systems;
- accessibility and fairness in software changes;
- documented emergency procedures;
- retention and deletion policies for logs and artifacts;
- responsible management of third-party actions and dependencies.
Regulated organizations may need evidence of who approved a change, what was tested, which version was deployed, and whether access was authorized. Compliance should be implemented through reliable technical controls and useful evidence, not by adding paperwork after the fact. AI-assisted coding and pipeline generation can accelerate development, but generated code and workflow definitions require review. AI tools may introduce insecure dependencies, licensing uncertainty, incorrect assumptions, or accidental disclosure of proprietary material. The accountable engineer remains responsible for validation and approval. 13. Best Practices and Common Failure ModesEffective Git-based CI/CD commonly follows these practices: - keep changes small and integrate frequently;
- protect the main branch and require meaningful review;
- build once and promote the same immutable artifact;
- version pipeline and infrastructure definitions;
- keep secrets out of Git and logs;
- pin important dependencies and action versions;
- make tests reliable and investigate flaky behavior;
- use least-privilege identities and short-lived credentials;
- monitor both technical and business outcomes;
- design and rehearse recovery;
- document exceptional manual changes and reconcile them to Git.
Common failure modes include treating a green build as proof of production safety, rebuilding artifacts for each environment, allowing unrestricted workflow permissions, using mutable image tags, ignoring dependency vulnerabilities, and relying on manual rollback instructions that no one has tested. Chapter SummaryGit is a coordination and traceability mechanism for DevOps, not merely a source-code archive. Git events can initiate CI/CD workflows that validate changes, build immutable artifacts, perform security analysis, apply infrastructure definitions, deploy to environments, and provide post-deployment feedback. CI validates integration; continuous delivery produces a releasable system; continuous deployment automatically releases qualifying changes. Effective practice distinguishes branches from environments, separates build from promotion, protects pipeline and repository access, and treats infrastructure and configuration as controlled code. GitOps extends these principles through declarative desired state and reconciliation. Safe delivery also requires observability, reversible deployment strategies, compatible database migrations, and tested recovery procedures. Governance, privacy, supply-chain security, and responsible use of automation remain essential professional responsibilities. Key TermsGit event: An action such as a push, merge, tag, or pull request that may initiate automation. Continuous integration: Frequent integration of changes supported by automated validation. Continuous delivery: Automated preparation of deployable software, usually with a release approval step. Continuous deployment: Automatic production release of changes that satisfy defined controls. Pipeline: An automated sequence of validation, construction, security, deployment, and verification activities. Artifact: A build output, such as a package, binary, or container image. Immutable artifact: An output whose contents are not changed after publication. Promotion: Moving a verified artifact to another environment. Environment: An operational target with resources, configuration, access, and monitoring. Pull request: A proposed change submitted for review and automated validation. Infrastructure as code: Declarative or programmatic management of infrastructure through versioned files. GitOps: An operating model in which Git stores desired state and an agent reconciles the environment to it. Drift: A difference between declared desired state and actual deployed state. Canary deployment: A release exposed initially to a limited portion of traffic. Blue-green deployment: A deployment model using two parallel environments and traffic switching. Rollback: Returning service operation to a prior version or configuration. Roll-forward: Correcting a deployed defect with a subsequent release. Secret scanning: Detection of credentials or sensitive values in code and repository history. Observability: The ability to understand system behavior through logs, metrics, traces, and related signals. Feature flag: A control that changes feature exposure independently of code deployment. Review QuestionsShort Answer Questions- What is the difference between continuous delivery and continuous deployment?
- Why should a pipeline build once and promote the same artifact?
- How does a pull request support both collaboration and control?
- What is infrastructure as code?
- Why are secrets unsuitable for ordinary Git files and history?
Long Answer Questions- Describe a complete pipeline from a merge to
main through production verification. - Explain how GitOps differs from a conventional push-based deployment model.
- Compare rolling, blue-green, and canary deployment strategies.
- Discuss why database migrations complicate rollback and explain expand-and-contract migration.
- Explain the security risks of pipeline code and propose appropriate controls.
Analytical / Application Questions- A team rebuilds its application separately for staging and production. Analyze the risks and design a corrected artifact-promotion process.
- A canary release shows normal error rates but a 12% decline in successful payments. What should the team do, and why is the business metric important?
- An emergency engineer changes production infrastructure manually while the GitOps agent continues reconciling. Analyze the risks and propose a controlled emergency-change procedure.
Multiple Choice Questions with AnswersQuestion 1Which Git event most commonly initiates release validation for a proposed change? A. Opening or updating a pull request B. Deleting a local branch C. Changing a developer’s editor theme D. Viewing a repository page Correct Answer: A. Opening or updating a pull request Question 2What does “build once, deploy many” primarily achieve? A. It eliminates the need for testing B. It ensures environments receive the same tested artifact C. It prevents all configuration differences D. It requires production to compile source code Correct Answer: B. It ensures environments receive the same tested artifact Question 3Which practice best protects a production branch? A. Allowing unrestricted force-pushes B. Disabling automated checks C. Requiring reviews and successful status checks D. Storing credentials in commit messages Correct Answer: C. Requiring reviews and successful status checks Question 4In GitOps, what normally reconciles the actual environment with the desired state in Git? A. A repository viewer B. A reconciliation agent C. A text editor D. A compiler only Correct Answer: B. A reconciliation agent Question 5Which deployment strategy initially sends only a small proportion of traffic to a new release? A. Recreate B. Canary C. Batch compilation D. Full replacement without monitoring Correct Answer: B. Canary Question 6What is the primary purpose of secret scanning? A. To increase application screen size B. To detect credentials or sensitive values in repository content C. To replace integration tests D. To select a programming language Correct Answer: B. To detect credentials or sensitive values in repository content Question 7What does a Git revert normally do? A. Creates a new commit that reverses an earlier change B. Deletes all repository history C. Changes a database backup into an image D. Automatically repairs every production defect Correct Answer: A. Creates a new commit that reverses an earlier change Question 8Which practice most improves artifact traceability? A. Using only a mutable tag such as latest B. Recording the source commit and artifact identity C. Rebuilding separately in every environment D. Removing deployment records after release Correct Answer: B. Recording the source commit and artifact identity Question 9Why can a database migration make rollback unsafe? A. Databases cannot be monitored B. The newer schema may be incompatible with the older application C. Git cannot store migration files D. Testing never uses databases Correct Answer: B. The newer schema may be incompatible with the older application Question 10Which signal is an example of a business-level post-deployment metric? A. Payment success rate B. Runner hostname C. Branch color in a user interface D. Number of text editors installed Correct Answer: A. Payment success rate
|