📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Code review: a teammate's Azure DevOps YAML pipeline builds a .NET 10 API and deploys it straight to production on every push to any branch. It has no test step, a SQL admin password in a pipeline variable, an Owner-level service connection and no environment approvals. What do you flag, in what order, and what does the fixed pipeline look like?

Reviews an unsafe Azure DevOps pipeline: missing test gate, plain-text secrets, over-privileged service connection, no environments or approvals, deploys from any branch, rebuilds per stage, and shows the corrected pipeline.

Senior CodeReview Advanced azure-devops ci-cd code-review devops least-privilege pipeline-security

🎯 Key points

  • Severity order: security holes (secret, Owner connection, any-branch prod deploy) before quality gates and design
  • SQL admin password in a variable: rotate it now, use Entra-only auth and managed identity for the app
  • Owner service connection: replace with workload identity federation scoped to the resource group, with checks on the connection
  • Trigger on any branch deploying to prod: CI on main only, PR validation via branch policy build validation
  • No tests: dotnet test covering behaviour (unit and integration), results published, deploy stage depends on it
  • Deployment job targeting an environment with approvals, branch control and exclusive lock; build once and promote the artefact
  • Deploy to a staging slot, smoke test, swap, verify with Application Insights; swap back on failure
  • Close with blocking vs suggested comments and enforce via templates and required-template checks

⏱ 30-second answer

I rank by severity. Blocking, security: the SQL admin password in a variable (rotate it now; the app should use managed identity with Entra authentication), the Owner-level service connection (replace with workload identity federation scoped to the resource group), and any-branch deploys to production (anyone who can push a branch can ship to prod).

Blocking, correctness: no test gate, so broken code reaches users, and no environment approvals or exclusive lock.

Suggested: build once and promote one artefact, deploy to a staging slot and swap, add a smoke test, and move shared steps into a template.

The fixed pipeline has a Build stage (restore, build, test, publish artefact) for PRs and main, and a Deploy stage only for main, targeting a protected environment. The trade-off is a few minutes of pipeline time for a release path that's actually controlled.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd go through it by severity, because not all of these are equal. The first three are security holes. The SQL admin password in a pipeline variable means anyone who can edit the pipeline can read it, it's probably in old logs, and it's the server admin, not an app login. I'd ask for it to be rotated today, regardless of what else we change, and for the app to use its managed identity with Entra authentication so there's no password at all. The service connection has Owner on the subscription, so this pipeline (and anyone who can change its YAML) can delete anything or grant themselves access; it should be a workload identity federation connection with Contributor on just the app's resource group. And the trigger is any branch, so pushing test-stuff deploys to production; that's a change-control failure on its own.

Then correctness. There's no dotnet test, so the pipeline proves the code compiles and nothing else. There's no environment, so no approval, no deployment history and no exclusive lock: two pushes can deploy over each other. For example, at [company] I reviewed a pipeline like this [and found the same admin password in three pipelines; we rotated it and moved the apps to managed identity within a week].

The mistake I see in these reviews is leaving twenty comments of equal weight, so the author fixes the YAML formatting and misses the Owner connection. I mark the security and gating items as blocking, the rest as suggestions, pair with the author on the rewrite, and then push the fixes into a shared template with required-template and approval checks on the production environment, so the next pipeline can't regress."


Code under review

trigger:
  branches:
    include: ['*']                       # 1 any branch triggers a prod deploy

pool:
  vmImage: windows-latest

variables:
  sqlAdminPassword: 'P@ssw0rd2024!'      # 2 plain-text admin secret in YAML

steps:
- script: dotnet build -c Release        # 3 no restore lock, no tests at all
- script: dotnet publish src/Orders.Api -c Release -o $(Build.ArtifactStagingDirectory)
- task: AzureCLI@2
  inputs:
    azureSubscription: 'Owner-Connection' # 4 Owner on the whole subscription
    scriptType: pscore
    scriptLocation: inlineScript
    inlineScript: |
      az webapp config connection-string set -g rg-orders -n app-orders-prod `
        -t SQLAzure --settings Default="Server=sql-orders.database.windows.net;User ID=sqladmin;Password=$(sqlAdminPassword)"  # 5 admin login used by the app, value passes through the pipeline
- task: AzureWebApp@1
  inputs:
    azureSubscription: 'Owner-Connection'
    appName: app-orders-prod              # 6 straight to the production slot; no environment, approval or lock
    package: $(Build.ArtifactStagingDirectory)
                                          # 7 no smoke test, no rollback path

Findings, ranked by severity

# Severity Finding Fix
2, 5 Blocking: security SQL admin password in YAML, written into a connection string by the pipeline Rotate now; Entra-only auth on SQL; app uses managed identity (Authentication=Active Directory Default)
4 Blocking: security Owner service connection Workload identity federation connection, Contributor on rg-orders-prod only; approvals and branch control on the connection
1 Blocking: security / change control Any branch deploys to production trigger: main; PRs run a validation build only
3 Blocking: correctness No tests dotnet test with results published; deploy stage depends on it
6 Blocking: correctness No environment, approval or exclusive lock; deploys to production slot directly deployment job targeting orders-prod environment; deploy to staging slot and swap
7 Suggested: diagnostics No smoke test or rollback Health/smoke check after swap; swap back on failure
– Suggested: design Single stage, Windows agent for a Linux app, no NuGet lock or cache Build/Deploy stages, ubuntu-latest, --locked-mode, Cache@2

The rewrite

(See the code example section for the full YAML.) Shape:

PR ──► Build stage (restore, build, test, publish artefact)            ← branch policy: must pass
main ─► Build stage ─► Deploy stage (environment orders-prod: approval, branch control, exclusive lock)
                         └─ deploy artefact to staging slot ─► smoke test ─► swap ─► smoke test

How I'd close the review

  • Blocking comments: items 1–6, each with the reason and the fix. Ask for the password rotation to happen immediately, separate from the PR.
  • Suggestions: stages, Linux agent, caching, template extraction.
  • Make it stick: move the build and deploy into a shared template; add a required template check, approvals, branch control and exclusive lock on the production environment and service connection; turn on secret scanning for the repo; run an access review on service connections.
  • Follow up: pair with the author on the rewrite rather than leaving them with a wall of comments.

Production example

After a review like this, a team replaced four Owner-level connections with federated, resource-group-scoped ones, removed SQL authentication entirely, and added PR validation builds; failed production deployments dropped from roughly two a month to one a quarter.

🔍 What the interviewer is checking

Checks whether the candidate reviews pipelines with a security-first severity order, knows the Azure DevOps controls that enforce safe delivery, and can produce a corrected pipeline.

Green flags

  • Ranks secrets, over-privileged identity and any-branch prod deploys as top issues
  • Insists on rotating the leaked password immediately and removing SQL auth
  • Uses environments with approvals, branch control and exclusive lock, plus build-once artefacts
  • Proposes templates and resource checks so the fix sticks

Red flags

  • Starts with formatting or agent choice
  • Moves the password to a secret variable and calls it done
  • Doesn't mention who can deploy to production

📚 Learn in depth

1. Why severity order matters

Reviews have limited attention. Rank by impact:

1. Can this leak data or let someone take over resources?   (secrets, privileges, who can deploy)
2. Can this ship broken code or corrupt data?               (tests, approvals, concurrency)
3. Can we see and undo problems?                             (smoke tests, monitoring, rollback)
4. Is it maintainable and fast?                              (stages, templates, caching)

2. The secret problem, properly fixed

  • Rotate first. The password is in Git history; deleting the line doesn't un-leak it.
  • Remove the need. Azure SQL supports Microsoft Entra authentication; with Entra-only auth enabled, SQL logins (including sqladmin) stop working. The app's managed identity becomes a contained database user with only the roles it needs (db_datareader, db_datawriter, or custom).
  • Connection string without a password: Server=tcp:sql-orders.database.windows.net;Database=orders;Authentication=Active Directory Default;Encrypt=True with Microsoft.Data.SqlClient picks up the managed identity.

3. Service connections and least privilege

Setting Bad Good
Auth Service principal secret Workload identity federation
Scope Subscription, Owner Resource group, Contributor (or custom role)
Pipeline access "Grant access to all pipelines" Only named pipelines
Checks None Approval, branch control (refs/heads/main), required template

Checks on the service connection apply even if someone writes a new pipeline that uses it.

4. Triggers and PR validation in Azure DevOps

  • The YAML trigger: controls CI runs on pushes. Set it to main so feature branches never start the deploy path.
  • For repos in Azure Repos, PR validation is not configured with the YAML pr: keyword (that applies to GitHub and Bitbucket repos). It is configured with a branch policy on main: Build validation runs the pipeline for every PR targeting main, and the PR can't complete until it passes. Add minimum reviewers and linked work items policies in the same place.
  • Deploy stages get condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main')) as a second guard, and branch control on the environment as the real control.

5. Environments

A deployment job targeting an environment gives you:

  • approval and check gates before the job starts,
  • deployment history (which run, which commit, who approved),
  • exclusive lock so only one run deploys at a time (others queue or are cancelled).

6. Build once, verify after

Publish the build output as a pipeline artefact in the Build stage; the Deploy stage downloads it automatically. Never rebuild in the Deploy stage.

After deploying to the staging slot, a smoke test hits /health/ready (which checks the database with the app's managed identity). After the swap, a second check and Application Insights confirm production is healthy: an Azure Monitor alert on 5xx ratio and a release annotation make it obvious if the new build is the cause. If either check fails, swap back; the previous build is still warm in staging.

artefact ─► staging slot ─► smoke test ─► swap ─► post-swap check + App Insights alert
                                               │ fail
                                               └──► swap back (rollback in < 1 min)

7. Enforcing it organisation-wide

Put the approved build/deploy in a template repo, and add a required template check on the production environment so only pipelines that extends the template can deploy. Combine with periodic reviews of service connections and their role assignments.

Try it yourself

  1. Create a federated service connection scoped to one resource group and confirm it can't list resources elsewhere.
  2. Enable Entra-only authentication on a test Azure SQL server and connect from an app with managed identity.
  3. Add an environment with approval, branch control and exclusive lock; trigger two runs and watch the second queue.
  4. Configure build validation on main so PRs can't merge without a passing build and test run.
  5. Add a required template check and try to deploy from a pipeline that doesn't extend the template.

💻 Code

The rewritten pipeline (azure-pipelines.yml):

trigger:
  branches: { include: [main] }   # PR validation comes from the branch policy on main

variables:
  buildConfiguration: Release
  NUGET_PACKAGES: $(Pipeline.Workspace)/.nuget/packages

stages:
- stage: Build
  jobs:
  - job: build
    pool: { vmImage: ubuntu-latest }
    steps:
    - task: UseDotNet@2
      inputs: { useGlobalJson: true }
    - task: Cache@2
      inputs:
        key: 'nuget | "$(Agent.OS)" | **/packages.lock.json'
        path: $(NUGET_PACKAGES)
    - script: dotnet restore --locked-mode
    - script: dotnet build -c $(buildConfiguration) --no-restore
    - script: dotnet test -c $(buildConfiguration) --no-build --logger trx --collect "XPlat Code Coverage"
      displayName: Test (gate)
    - task: PublishTestResults@2
      condition: always()
      inputs: { testResultsFormat: VSTest, testResultsFiles: '**/*.trx' }
    - script: dotnet publish src/Orders.Api -c $(buildConfiguration) --no-build -o $(Build.ArtifactStagingDirectory)/app
    - publish: $(Build.ArtifactStagingDirectory)/app
      artifact: app                # build once; Deploy uses these exact bytes

- stage: Deploy
  dependsOn: Build
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  jobs:
  - deployment: deploy
    environment: orders-prod       # approvals, branch control, exclusive lock, required template
    pool: { vmImage: ubuntu-latest }
    strategy:
      runOnce:
        deploy:
          steps:
          - task: AzureWebApp@1
            inputs:
              azureSubscription: sc-orders-prod-wif   # workload identity federation, Contributor on rg-orders-prod only
              appType: webAppLinux
              appName: app-orders-prod-aue
              deployToSlotOrASE: true
              resourceGroupName: rg-orders-prod-aue
              slotName: staging
              package: $(Pipeline.Workspace)/app
          - script: curl --fail --retry 10 --retry-delay 6 https://app-orders-prod-aue-staging.azurewebsites.net/health/ready
            displayName: Smoke test staging
          - task: AzureAppServiceManage@0
            inputs:
              azureSubscription: sc-orders-prod-wif
              action: Swap Slots
              webAppName: app-orders-prod-aue
              resourceGroupName: rg-orders-prod-aue
              sourceSlot: staging

The app connects to Azure SQL with its managed identity, so no password exists anywhere (Program.cs):

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// appsettings: "Server=tcp:sql-orders-aue.database.windows.net;Database=orders;
//               Authentication=Active Directory Default;Encrypt=True"
builder.Services.AddDbContext<OrdersDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Orders"),
        sql => sql.EnableRetryOnFailure()));
builder.Services.AddHealthChecks().AddDbContextCheck<OrdersDbContext>(tags: ["ready"]);

var app = builder.Build();
app.MapHealthChecks("/health/ready", new() { Predicate = r => r.Tags.Contains("ready") });
app.Run();

public sealed class OrdersDbContext(DbContextOptions<OrdersDbContext> options) : DbContext(options);
-- Run once by an Entra admin: the app's identity gets only what it needs
CREATE USER [app-orders-prod-aue] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [app-orders-prod-aue];
ALTER ROLE db_datawriter ADD MEMBER [app-orders-prod-aue];

⚠ Common mistakes

  • Mistake: Treating the leaked password as fixed once it's removed from YAML. Why it is wrong: It remains in Git history and old logs. Instead: Rotate it immediately and move to managed identity.
  • Mistake: Giving every review comment equal weight. Why it is wrong: The author may fix style and miss the Owner connection. Instead: Mark security and gating issues as blocking and rank by severity.
  • Mistake: Replacing the plain-text variable with a secret variable and stopping there. Why it is wrong: The admin password still exists and passes through the pipeline. Instead: Remove the need for it with Entra authentication.
  • Mistake: Narrowing the trigger but leaving the service connection open to all pipelines. Why it is wrong: Another pipeline can still deploy to production. Instead: Restrict pipeline access and add checks on the connection and environment.
  • Mistake: Adding a dotnet test step that runs a handful of trivial tests. Why it is wrong: A green gate that only proves the code compiles gives false confidence. Instead: Gate on meaningful unit tests plus WebApplicationFactory integration tests for the main API paths, and track coverage of critical code.
  • Mistake: Adding tests but not publishing results or failing on them. Why it is wrong: Failures get ignored. Instead: Make the deploy stage depend on a passing test step and publish results.
  • Mistake: Rebuilding in the deploy stage. Why it is wrong: Production gets bytes that weren't tested. Instead: Publish an artefact once and deploy it.
  • Mistake: Deploying with no post-deploy verification or rollback path. Why it is wrong: A broken release looks green and stays live until users complain. Instead: Smoke test the staging slot, swap, check Application Insights, and swap back on failure.
  • Mistake: Fixing one pipeline and moving on. Why it is wrong: The next team copies the old one. Instead: Provide a template and enforce it with a required template check.

🏛 Senior insight: trade-offs

A pipeline is production infrastructure with the keys to production, so I review it like security-sensitive code. The worst issues aren't missing tests; they're identities and secrets that let anyone with repo access act as an administrator. Those get fixed first, and the leaked secret gets rotated immediately, outside the PR cycle.

The lasting fix is structural: controls on resources (environment and service connection checks, required templates) instead of good intentions in each YAML file. I measure success by how many identities can deploy to production, how many stored secrets exist, and change failure rate.

Option When it fits Cost When not to
Fix this pipeline only One-off, small team Low Many teams copying patterns
Shared template + required template check Many services, platform team Template ownership and versioning Very early prototypes (still use approvals)
Checks on environment and connection Always for production A few minutes of setup Never skip for prod
Entra-only SQL + managed identity Azure SQL with Azure-hosted apps Role setup, migration of logins Legacy tools that only support SQL auth (isolate them)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the password must be rotated and removed. Why: Checks deeper knowledge of secretless pipelines and leak response.
    How to answer

    My rule is to remove secrets rather than protect them. The pipeline authenticates to Azure with OIDC / workload identity federation: the CI platform issues a short-lived token that Entra trusts, so no client secret is stored. The app authenticates to SQL, Storage and Key Vault with managed identity. Remaining secrets (third-party API keys) live in Key Vault; the pipeline deploys only a Key Vault reference such as @Microsoft.KeyVault(VaultName=...;SecretName=...) as an app setting, and the platform resolves it with the app's identity, so the value never passes through the pipeline.

    Pipeline identities are least privilege: one per environment, roles on a resource group, protected by environment approvals. Secret scanning with push protection blocks committed secrets.

    If a secret leaks, I revoke and rotate first, then clean logs, then check access logs. The trade-off is up-front identity setup in exchange for nothing worth stealing in the pipeline.

  2. When: Candidate uses Azure DevOps environments and checks fluently. Why: Checks whether the candidate can map these controls to GitHub Actions.
    How to answer

    Both run YAML pipelines as code. Azure Pipelines has a genuine stage level (stages → jobs → steps), and its environments and other resources carry approvals and checks (manual approval, branch control, business hours, exclusive lock, Azure Monitor gates), with templates for reuse. GitHub Actions has no stage concept: workflows → jobs → steps, chained with needs:, plus environments with required reviewers, wait timers and branch rules, and reusable workflows and composite actions.

    Both authenticate to Azure without secrets: Azure DevOps through workload identity federation service connections, GitHub through OIDC with azure/login.

    I choose mostly by where the code, backlog and audit evidence already live. Both are actively developed: GitHub tends to get developer-experience features first (Copilot, the marketplace), while Azure DevOps keeps strong enterprise traceability (Boards, Test Plans, resource checks) that many Australian enterprises and government teams depend on.

  3. When: Candidate adds a staging slot and swap to the rewrite. Why: Checks the deployment strategy choice behind the slot swap.
    How to answer

    Rolling replaces instances in batches: no extra capacity, but old and new versions serve traffic together and rolling back means another rollout. Blue-green runs a full second environment and switches all traffic at once; rollback is switching back. Canary sends a small share of traffic (say 5%) to the new version, compares error rate and latency, then widens or aborts. App Service deployment slots are blue-green in a box: deploy to staging, warm it up, swap, and swap back to roll back.

    The catch is the same for all of them: for a while two versions run against one database, so schema changes must be expand/contract and backward compatible. The trade-off is cost and complexity (blue-green and canary) against blast radius and rollback speed.

🛠 Real-world problems: how you handle them

Admin password found in three pipelines during a review
Situation
A team of [eight] developers deploying a .NET 10 orders API to App Service in Australia East; pipelines had grown by copy-paste over [two years], and one handled [customer contact details].
Signals
During a routine PR review the SQL admin password was visible in YAML; a search of the project's repos found the same value in [three] pipelines, and the service connection had Owner on the subscription.
Investigation
Searched repos and pipeline definitions via the Azure DevOps REST API for the password and connection name; listed role assignments with `az role assignment list --assignee <sp-id> --all`; checked Azure SQL auditing logs in Log Analytics for logins by `sqladmin` from unexpected IPs.
Resolution
Immediate: rotated the admin password, restricted the SQL firewall, and confirmed from audit logs [no unexpected logins]. Long term: enabled Entra-only authentication, moved apps to managed identity, replaced the Owner connection with federated resource-group-scoped connections, and rewrote pipelines on a shared template.
Prevention
Required template and approval checks on production environments; secret scanning enabled for the repos; quarterly service connection access reviews; Azure Policy requiring Entra-only auth on SQL servers.

How to tell it (STAR)

**S:** I was reviewing a pipeline change and saw the SQL admin password in plain YAML, deploying from any branch with an Owner-level connection. **T:** I needed to close the exposure and stop it recurring across the team. **A:** I had the password rotated that day, checked the SQL audit logs for misuse, then led the move to managed identity with Entra-only SQL auth, federated resource-group-scoped connections, and a shared template enforced by required-template and approval checks. **R:** We removed [all] stored database passwords, cut production-capable identities from [four to one per service], and failed production deployments dropped from [about two a month to one a quarter].

More in CI/CD

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me