
From Browser Automation to AI-Powered SRE: Putting Playwright to Work for Platform Engineers
How to combine Playwright MCP, AWS CLI, and Terraform to build AI-powered troubleshooting workflows without giving agents direct access to modify infrastructure.
Why I started handing my agent a browser
A few weeks ago I gave my AI agent a broken VPC peering connection and one extra instruction: use Playwright. It opened the AWS console, read the peering status, walked both route tables, found the missing route to the peer CIDR, and explained the fix. I had expected a toy demo. I got a correct diagnosis in a few minutes.
That result changed how I think about Playwright. Most of us file it under QA: end-to-end tests that someone else writes. Once an LLM can drive it, it becomes something else for platform teams, an instrument that lets an agent see what a user sees and what a console shows.
This post is my practitioner's take on where that instrument fits in DevOps and platform work, where it does not, and the guardrails I would insist on before letting it near anything that matters. The short version: give the agent eyes, not the keys. Diagnose in the browser, fix in code.
What changed: the browser became a tool an LLM can hold
The enabler is Playwright MCP , Microsoft's open-source MCP server for Playwright. Its key design choice is that the model reads the page as an accessibility tree, not as pixels. The agent gets a structured list of roles, names and element references, then acts on those references. No vision model has to guess where a button is, and actions are deterministic.
For platform work, three groups of its tools matter most:
- Read-only inspection.
browser_snapshot,browser_find,browser_console_messages,browser_network_requestsandbrowser_network_requestlet the agent read the page, the browser console, and every request with headers and body. That is your symptom-side telemetry.
- Opt-in capabilities. Network mocking, cookie and storage access, tracing, video and PDF export sit behind
--caps. You enable only what a given job needs.
- Session control.
--isolatedkeeps the profile in memory, and--storage-stateloads a pre-authenticated session from a file. That combination is how you avoid handing the agent a password.
One recent shift is worth knowing. The README now says coding agents may be better served by Playwright CLI with skills , because CLI calls avoid loading large tool schemas and accessibility trees into context. MCP remains the better fit for long, stateful loops such as exploratory debugging. My rule of thumb: MCP for interactive investigation, CLI or plain
@playwright/test scripts for anything that runs in a pipeline.The repo is also blunt about one thing every architect should note: Playwright MCP is not a security boundary. Origin allowlists, secret masking and file-access limits are described as conveniences, not controls. Hold that thought for the guardrails section.
The mental model: symptom side and cause side
Every production problem has two sides, and Playwright only sees one of them. The symptom side is what a user or a console experiences: a 502, a spinner that never resolves, a CORS error, a login loop. The cause side is inside the system: container logs, task events, target health, security groups, IAM policies.
The browser is excellent at the first and blind to the second. A container that crashes before it serves a byte looks like a generic error page; only logs and events tell you why. So the question is never "Playwright or CLI?" It is "which interface gives the agent the clearest signal for this step?"
Interface | Best for | Weak at | Default use |
|---|---|---|---|
Playwright (browser) | What the user sees: console errors, failed requests, auth redirects, UI-only settings | Anything inside the container or not rendered in a UI | Reproduce, observe, verify |
CLI ( aws , az , kubectl ) | Fast, structured reads of resource state and logs | Showing user-facing impact | Diagnose |
API / SDK | Bulk queries, automation, precise filters | Ad-hoc exploration | Diagnose at scale |
IaC (Terraform) | Changing state, with review and history | Investigation | Fix |
An agent can read the AWS console through the browser, and sometimes that is the right call: no CLI credentials on the box, or you want it to see exactly what a human sees. It is just slower, burns more tokens, and breaks when the console layout changes. Prefer the CLI where it exists and the browser where it does not.
Get started on AWS: configuring Playwright for platform work
The default install is built for a developer clicking around a local app. On AWS you want something tighter: a headless browser inside your VPC, a pre-authenticated session pulled from Secrets Manager, a read-only IAM identity for the cause side, and a pipeline stage that replays the journey after every
terraform apply . Here is the setup I use, in six steps.1. Add the MCP server to your agent
You need Node.js 18 or newer. In Claude Code:
claude mcp add playwright npx @playwright/mcp@latestMost other clients (VS Code, Cursor, Codex, Kiro) take the same standard config:
{ "mcpServers": { "playwright": { "command": "npx", "args": ["@playwright/mcp@latest", "--config", "./playwright-mcp.config.json"] } }}For team configs, pin a specific version instead of
@latest so a release does not change agent behaviour under you mid-incident.2. Write a config file for an AWS-hosted app
A config file keeps the settings reviewable and versioned. This is my starting point for an app behind an ALB or CloudFront, with Amazon Cognito as the login:
{ "browser": { "browserName": "chromium", "isolated": true, "launchOptions": { "headless": true }, "contextOptions": { "storageState": "./auth/dev-readonly.json" } }, "capabilities": ["core", "devtools"], "network": { "allowedOrigins": [ "https://orders.dev.example.com", "https://auth.dev.example.com" ] }, "console": { "level": "error" }, "redactUrlParams": ["access_token", "code", "id_token"], "outputDir": "./playwright-output", "saveSession": true, "timeouts": { "action": 5000, "navigation": 60000 }}What each choice buys you:
-
isolatedkeeps the profile in memory, so nothing persists between sessions except what you load deliberately.
-
storageStateloads a pre-built login. The agent never types a password.
-
capabilitiesenablesdevtoolsfor tracing and video; leavevision,storageandnetworkmocking off unless a job needs them.
-
allowedOriginslists only your app and the Cognito domain. Notice the AWS console is not on it: the agent reads AWS state through the CLI, not by clicking around the console. This list is not a security boundary, so step 4 enforces egress at the network layer.
-
redactUrlParamsmasks the OAuthcodeand tokens Cognito puts in redirect URLs.
-
saveSessionandoutputDirkeep a record of what the agent did, for review and audit.
3. Create the auth state and keep it in Secrets Manager
Log in once as a low-privilege test user and save the session:
npx playwright codegen --save-storage=auth/dev-readonly.json https://orders.dev.example.comComplete the login in the browser window that opens, then close it. Store the file in AWS Secrets Manager rather than on a laptop or in the repo:
aws secretsmanager create-secret \ --name playwright/dev-readonly-storage-state \ --secret-string file://auth/dev-readonly.jsonThe runner fetches it at session start and deletes it when done:
mkdir -p authaws secretsmanager get-secret-value \ --secret-id playwright/dev-readonly-storage-state \ --query SecretString --output text > auth/dev-readonly.jsonRefresh it with a scheduled login job (a Lambda or a small CodeBuild project) on a cadence shorter than the Cognito refresh-token lifetime. Secrets Manager caps a secret at 64 KB, which is plenty for a normal storage state.
4. Run the browser inside your VPC
Run the MCP server on an EC2 instance or ECS task in a private subnet, not on your laptop profile. Mirror Microsoft's image (
mcr.microsoft.com/playwright/mcp ) into a private ECR repository so you control the version and it is scanned like any other image. On an EC2 host:docker run -d --rm --init --name playwright-mcp \ -p 127.0.0.1:8931:8931 \ --entrypoint node \ 123456789012.dkr.ecr.eu-central-1.amazonaws.com/playwright-mcp:<pinned-version> \ /app/cli.js --headless --browser chromium --no-sandbox --port 8931 --host 0.0.0.0The port is published on the host's loopback only. To reach it from your machine, use a Session Manager port forward instead of opening a security group:
aws ssm start-session --target i-0abc123def4567890 \ --document-name AWS-StartPortForwardingSession \ --parameters '{"portNumber":["8931"],"localPortNumber":["8931"]}'Then point your MCP client at
http://localhost:8931/mcp . For egress, route the subnet through AWS Network Firewall (or an egress proxy) with a domain allowlist containing your app, the Cognito domain, and nothing else.5. Give the agent a read-only IAM identity
The cause side should be read-only from day one. Avoid attaching
ReadOnlyAccess wholesale: it can read S3 object contents, which is more than a debugging agent needs. A scoped policy for the container-debugging scenario looks like this:{ "Version": "2012-10-17", "Statement": [ { "Sid": "DiagnoseReadOnly", "Effect": "Allow", "Action": [ "ecs:Describe*", "ecs:List*", "elasticloadbalancing:Describe*", "ec2:DescribeSecurityGroups", "ec2:DescribeSecurityGroupRules", "ec2:DescribeSubnets", "ec2:DescribeRouteTables", "ec2:DescribeVpcPeeringConnections", "ec2:DescribeNetworkInterfaces", "logs:DescribeLogGroups", "logs:DescribeLogStreams", "logs:FilterLogEvents", "logs:GetLogEvents", "logs:StartQuery", "logs:GetQueryResults", "cloudwatch:GetMetricData", "cloudwatch:DescribeAlarms", "rds:DescribeDBInstances" ], "Resource": "*" } ]}Attach it to an IAM Identity Center permission set (for interactive use) or a role the runner assumes (for automation), so credentials are always short-lived. The agent then runs the CLI with a dedicated profile such as
AWS_PROFILE=agent-readonly . Add actions per scenario as you need them; never add write actions to this identity.6. Wire the pipeline after terraform apply
Agent sessions are for investigation. In CI, run plain specs. A minimal
playwright.config.ts :import { defineConfig } from '@playwright/test';
export default defineConfig({ retries: 1, reporter: [['html', { open: 'never' }]], use: { baseURL: process.env.APP_URL, storageState: 'auth/ci.json', trace: 'retain-on-failure', },});And a GitHub Actions job that runs after the apply job, using OIDC instead of stored AWS keys:
smoke: needs: apply runs-on: ubuntu-latest permissions: id-token: write contents: read steps: - uses: actions/checkout@v4 - uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789012:role/ci-smoke-readonly aws-region: eu-central-1 - run: npm ci && npx playwright install --with-deps chromium - run: | mkdir -p auth aws secretsmanager get-secret-value \ --secret-id playwright/ci-storage-state \ --query SecretString --output text > auth/ci.json - run: npx playwright test env: APP_URL: https://orders.dev.example.com - if: failure() uses: actions/upload-artifact@v4 with: name: playwright-report path: playwright-report/The CI role only needs
secretsmanager:GetSecretValue on that one secret. When a spec proves its worth, promote it to a CloudWatch Synthetics canary on the Playwright runtime and alarm on the SuccessPercent metric, so the same journey keeps running against production between deploys.
Walkthrough: a Terraform-deployed container that misbehaves
Here is the scenario I see most often. Terraform applies cleanly, the ECS service (or Kubernetes deployment) shows running tasks, and the app is still broken. Pipelines are green; users are not happy.
I give the agent two kinds of access: Playwright MCP for the app URL, and a read-only cloud role for the CLI. Then a prompt like this:
The orders app at https://orders.dev.example.com is failing after today's deploy.1. Use Playwright to load the app, log in with the stored session, and open the Orders page. Capture console errors and every failed network request with status and response body.2. Use the AWS CLI (read-only) to check the ECS service events, target group health, and the last 30 minutes of container logs for the orders-api service.3. Correlate the two. Give me the most likely root cause with evidence from both sides.4. Propose the fix as a Terraform diff. Do not change anything in the console.A typical correlation chain the agent produces:
- Browser: the Orders page calls
GET /api/orders, which returns 502 from the load balancer.
- Target group: the orders-api targets are cycling between healthy and unhealthy.
- Container logs:
connection refusedto the database on port 5432, then the health check fails and the task restarts.
- Resource state: the database security group allows the old task subnet, not the new one Terraform moved the service to.
- Fix: a Terraform change to the security group ingress, raised as a PR.
No single interface would have found this quickly. The browser alone says "502". The logs alone say "connection refused" with no indication of user impact or which endpoint matters. Together they give a defensible diagnosis in minutes.
Turn the reproduction into a regression test
The part most teams skip is the most valuable. The steps Playwright used to reproduce the failure are a test. Ask the agent to write them as a
@playwright/test spec and commit it next to the Terraform:import { test, expect } from '@playwright/test';
test('orders page loads and API returns 200', async ({ page }) => { const apiResponse = page.waitForResponse(r => r.url().includes('/api/orders')); await page.goto(process.env.APP_URL + '/orders'); expect((await apiResponse).status()).toBe(200); await expect(page.getByRole('table', { name: 'Orders' })).toBeVisible();});Run it after every
terraform apply with tracing on failure ( trace: 'retain-on-failure' ). The same bug cannot ship twice, and when something else breaks, the trace zip shows exactly where.Where this approach stops working
Be honest about the limits. If the container never starts (bad image, missing secret, OOM on boot), the browser adds almost nothing; the cause side does all the work. If the problem is intermittent, a single browser session may not reproduce it, and your metrics are the better first stop. And if the app sits behind an identity provider with phishing-resistant MFA, the agent needs a pre-built session; it should never be typing credentials.
Six platform use cases worth building

Debugging is the headline, but the steady value comes from turning one-off browser sessions into repeatable checks. These are the six I would prioritise on a platform team, roughly in order of payoff.
Use case | What Playwright does | Where it runs | Agent role |
|---|---|---|---|
Incident debugging | Reproduces the user-facing failure, captures console and network evidence | Engineer laptop or ops runner, on demand | Investigator, read-only |
Post-deploy smoke tests | Runs critical journeys after terraform apply or a release; fails the pipeline on breakage | CI/CD stage | Writes and maintains the specs |
SSO and SCIM verification | Logs test identities in through the IdP and confirms each lands with the right access | CI after identity changes, or scheduled | Generates test matrix from group config |
Synthetic monitoring | Executes journeys on a schedule against production | CloudWatch Synthetics or Azure App Testing | Turns incident repros into canaries |
Compliance evidence | Captures timestamped screenshots and PDFs of security settings | Scheduled job, output to immutable storage | Navigates and labels evidence |
UI-only admin surfaces | Reads settings that have no API (legacy servers, vendor portals, appliances) and compares them to expected config | On demand or scheduled | Drift reporter, read-only |
A few notes from building these.
Identity migrations are the sleeper hit. When you move an IdP tenant or restructure groups, the API tells you a user is assigned. Only a real login tells you they can actually reach the repo, the subscription, or the console page. A Playwright matrix of test identities, one per role, catches broken claims mappings and SCIM gaps before your users do.
Synthetic monitoring is already managed for you. AWS added a Playwright runtime to CloudWatch Synthetics in November 2024, with logs going straight to CloudWatch Logs and HAR files kept even when a canary times out. On Azure, Microsoft Playwright Testing was retired on 8 March 2026 ; the replacement is Playwright Workspaces in Azure App Testing. If your canaries still point at the old service, that is a migration item.
Compliance evidence is unglamorous and loved by auditors. A scheduled job that screenshots MFA policies, branch protection rules and guardrail settings, then writes them to object-lock storage, saves weeks at audit time. The API is still the source of truth; the screenshot is the human-readable proof.
UI-only surfaces are where the browser earns its keep. Every enterprise has a few: an on-prem server whose admin settings never got an API, a vendor portal, a firewall UI. Here the browser is not a fallback. It is the only interface.
Reference architecture: diagnose in the browser, fix in code

The browser and the CLI only read. The single path that changes infrastructure is a Terraform PR a human approves, and the original reproduction becomes the check that closes the loop.
Security: the browser is the most hostile input you will give an agent
Every page the agent reads is untrusted input, and some of it can talk back. OWASP LLM01 calls this indirect prompt injection: instructions hidden in a web page or file that change the model's behaviour, even when a human cannot see them. OWASP is candid that no fool-proof prevention is known. In a chatbot, injection makes the model say something wrong. With a browser and cloud credentials, it can make the model do something wrong.
In platform terms, the dangerous pages are not exotic. They are your own: an issue description, a log viewer rendering attacker-controlled user agents, a wiki page, a vendor status page. Design as if one of them will eventually carry a payload.
The controls I use, in order of how much risk they remove:
- Least privilege on the cause side. The agent's cloud role is read-only. It can describe, list and read logs. It cannot modify. If an injection succeeds, the blast radius is information, not infrastructure.
- No interactive credentials. Load a short-lived session with
--isolated --storage-state, generated by a separate login job. The model never sees a password or MFA code. Rotate the state file often.
- Network scoping outside the tool.
--allowed-originshelps, but the README says plainly it is not a security boundary and does not cover redirects. Put the browser in a container or runner whose egress is restricted by proxy or security group to the domains it needs.
- Capabilities off by default. Enable
--capsonly per job. Keepbrowser_run_code_unsafeout of agent sessions; the README describes it as RCE-equivalent.
- Human approval for anything that writes. Fixes leave as Terraform PRs. A human reviews the plan before apply. No exceptions for "small" changes.
- Audit trail. Record traces and save sessions to an output directory that the agent cannot delete. Ship them to the same retention store as your CloudTrail or Activity Log.
- Secret hygiene on the way out.
secretsand--redact-url-paramsmask tokens in tool responses. Use them, but treat them as conveniences; the README says so too.
If you take one thing from this section: separate the agent that browses from the agent that can change things. The browsing agent reports; a different, reviewed path acts.
Anti-patterns I would stop on sight
Most failures with browser agents are not model failures. They are architecture decisions that felt harmless in a demo.
- ClickOps by proxy. The agent fixes the security group in the console, the incident closes, and the next
terraform applysilently reverts it. Drift you created with an AI is still drift.
- Running the agent in your own browser profile. The extension mode that reuses your logged-in tabs is convenient on a laptop. It also hands the agent every session you have open, including production consoles and email.
- Browser for everything. Reading a 40-row route table through the AWS console costs far more tokens and time than one
aws ec2 describe-route-tablescall, and breaks when the UI changes. Use the browser where it adds signal.
- Snapshots as the source of truth. A screenshot or accessibility snapshot shows what the UI rendered, which can lag or hide state. For anything you will act on, confirm through the API.
- Agent sessions in CI. Non-deterministic, token-hungry and hard to debug. In pipelines, run plain
@playwright/testspecs. Let the agent write those specs; do not let it improvise in the pipeline.
- One shared state file forever. A long-lived storage state for a privileged account is a credential sitting on disk. Scope it to a low-privilege test identity and expire it.
- No regression test after the fix. If the reproduction never becomes a spec, you paid for the investigation and threw away the asset.
Prompt patterns I keep reusing
The quality of the evidence depends almost entirely on the prompt. A vague "check why the app is broken" gets a vague tour of the UI. A prompt that names the symptom, the interfaces, the read-only boundary and the output format gets a diagnosis you can paste into an incident ticket. These four cover most of what I run.
Every one follows the same skeleton: reproduce in the browser, inspect the cause side read-only, correlate, then propose in code.
1. 502 or 503 behind a load balancer
Open <APP_URL>/<PATH> with the stored session. List every request that returned 5xx,with URL, status and response body. Then, read-only: target group health for <SERVICE>,last 20 service events, last 30 minutes of container logs filtered for errors.Return: timeline of events, most likely root cause, confidence, and the Terraform changeyou would make. Do not modify anything.What it catches: failing health checks, wrong container port, security group gaps between tasks and dependencies, tasks killed by memory limits.
2. Login or SSO redirect loop
Open <APP_URL> in a fresh isolated session and attempt login as <TEST_IDENTITY>.Record every redirect with URL and status, and any console errors. Redact tokens and codes.Compare the callback URL and audience you observe with the app registration in <IDP>.Return: the step where the flow breaks and the config value that does not match.What it catches: callback URL mismatches after a domain change, cookie
SameSite issues behind a proxy, missing group claims after an IdP migration.3. Slow page after a deploy
Load <APP_URL>/<PATH> three times. For each load, list the five slowest requests withtiming and size. Then check, read-only, the latency and error metrics for the backingservice and database over the last hour, before and after deploy <VERSION>.Return: which request regressed, by how much, and which component it maps to.What it catches: a new N+1 call, a cache that stopped hitting, a downstream dependency moved to a different region.
4. Post-change verification
This Terraform change was just applied: <PR_LINK>. Using the stored session, run thejourney <JOURNEY> end to end and confirm each step succeeds. Then write the journey as a@playwright/test spec with web-first assertions, no fixed sleeps, and locators by role.Return: pass or fail per step, and the spec file.This is the one that turns an investigation into an asset. The spec goes into the repo next to the module it protects.
What makes these work
- Placeholders, not prose. Templated prompts in the repo give consistent evidence across engineers and incidents.
- An explicit output format. Timeline, root cause, confidence, proposed change. Easy to review, easy to paste.
- The read-only line written out. Say "do not modify anything" even when permissions already enforce it. The agent plans better when it knows the boundary.
Closing thought
Playwright did not become a platform tool because it changed. It became one because agents can now read a page the way an engineer does, and the browser is where users feel every failure we cause. Used well, it closes the gap between "the pipeline is green" and "the product works."
The discipline is old and familiar: least privilege, changes through code, evidence you can replay. Give the agent eyes. Keep the keys in the pipeline.
Sources
- microsoft/playwright-mcp README : tools, flags, MCP vs CLI guidance, security note
- microsoft/playwright-cli : CLI and skills for coding agents
About the author
Ashish Kasaudhan is a DevSecOps Architect at Giesecke+Devrient (G+D) and a DevOps and platform engineer with 17 years of experience across cloud infrastructure, containerization, CI/CD and enterprise automation.
He is a member of the AWS Community Builders program and writes practitioner-focused posts on cloud, DevOps, AIOps and MLOps.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article