<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Praveensam on Medium]]></title>
        <description><![CDATA[Stories by Praveensam on Medium]]></description>
        <link>https://medium.com/@praveensams16?source=rss-a25371fc5cc8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KmTQcH-jWHj-54Sa.png</url>
            <title>Stories by Praveensam on Medium</title>
            <link>https://medium.com/@praveensams16?source=rss-a25371fc5cc8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:08:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@praveensams16/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Built an AI-Powered Kubernetes Manager Using MCP and FastAPI]]></title>
            <link>https://medium.com/@praveensams16/how-i-built-an-ai-powered-kubernetes-manager-using-mcp-and-fastapi-7417d0bdcbe6?source=rss-a25371fc5cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7417d0bdcbe6</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Praveensam]]></dc:creator>
            <pubDate>Sun, 10 May 2026 01:58:09 GMT</pubDate>
            <atom:updated>2026-05-10T08:46:02.163Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop typing kubectl commands. Start talking to your cluster.</h3><blockquote><em>📦 </em><strong><em>GitHub Repository:</em></strong><em> </em><a href="https://github.com/praveensamca/kubernetes-mcp"><em>github.com/praveensamca/kubernetes-mcp</em></a></blockquote><h3>What is MCP (Model Context Protocol)?</h3><p>MCP is an open protocol introduced by Anthropic that standardises how AI models communicate with external tools, data sources, and services. Think of it as a universal plug — instead of building custom integrations for every AI model and every tool separately, MCP gives you one consistent interface that works across all of them.</p><p>With MCP, you define your capabilities once as an <strong>MCP Server</strong> — tools, resources, and prompts — and any MCP-compatible AI client can discover and use them automatically.</p><pre>User prompt → AI Model → MCP (tools + prompts) → Your Code → Real System</pre><p><strong>MCP is the API layer between language models and the real world.</strong></p><h3>Why MCP Matters for DevOps</h3><p><strong>1. High command surface area.</strong> Kubernetes has hundreds of kubectl subcommands. An AI layer removes the cognitive overhead of flags, namespace syntax, and manifest field names.</p><p><strong>2. Repetitive but context-sensitive tasks.</strong> Listing pods, checking service health, inspecting ingresses — perfect candidates for natural-language shortcuts.</p><p><strong>3. Dangerous operations need guardrails.</strong> MCP prompts can enforce step-by-step confirmation workflows before executing impactful operations.</p><p><strong>4. Audit and observability.</strong> Every MCP tool call is a structured, loggable event — a clean record of what the AI did, when, and with what parameters.</p><p><strong>5. Onboarding acceleration.</strong> Junior engineers can interact with a cluster in plain English while the MCP server enforces safe, well-formed API calls behind the scenes.</p><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhY2xagksJXVQPUBwui5bA.jpeg" /></figure><p>The project runs as two separate processes communicating over SSE (Server-Sent Events):</p><pre>┌──────────────────────────────────────────────────────────────┐<br>│   Browser  ·  chat.html                                      │<br>│   Dark-themed chat UI — POST /ai/query                       │<br>└───────────────────────┬──────────────────────────────────────┘<br>                        │ HTTP<br>┌───────────────────────▼──────────────────────────────────────┐<br>│   FRONTEND  ·  k8s_api.py  (port 8000)                       │<br>│   FastAPI — serves chat UI + /ai/query                       │<br>│   Connects to MCP server via SSE (127.0.0.1:8767/sse)        │<br>│   Fetches MCP Prompts as system context for OpenAI           │<br>│   OpenAI two-pass agentic loop                               │<br>└───────────────────────┬──────────────────────────────────────┘<br>                        │ MCP over SSE<br>                        │ list_tools() + list_prompts() + call_tool()<br>┌───────────────────────▼──────────────────────────────────────┐<br>│   BACKEND  ·  k8s_mcp.py  (port 8767)                        │<br>│   FastMCP — 12 @mcp.tool() + 1 @mcp.prompt()                │<br>│   MCP_TRANSPORT=sse · FASTMCP_PORT=8767                      │<br>└───────────────────────┬──────────────────────────────────────┘<br>                        │ Kubernetes Python Client<br>┌───────────────────────▼──────────────────────────────────────┐<br>│   Kubernetes Cluster                                         │<br>│   CoreV1Api · AppsV1Api · BatchV1Api · NetworkingV1Api       │<br>└──────────────────────────────────────────────────────────────┘</pre><h3>Key Design Principles</h3><p><strong>The frontend is a pure MCP client.</strong> k8s_api.py has zero direct Kubernetes code. It discovers tools and prompts dynamically from the MCP server at runtime — add a new tool to k8s_mcp.py and it&#39;s immediately available in the chat UI with no frontend changes.</p><p><strong>MCP Prompts as AI system context.</strong> This version introduces @mcp.prompt() — a new MCP primitive that delivers structured workflow instructions to the AI as a system prompt. This is how the server enforces multi-step guided workflows like resource creation.</p><h3>Repository File Structure</h3><pre>kubernetes-mcp/<br>├── k8s_mcp.py          # MCP backend — 12 tools + 1 prompt via FastMCP<br>├── k8s_api.py          # FastAPI frontend — chat UI + /ai/query via MCP SSE<br>├── openai_response.py  # Standalone OpenAI test script<br>├── templates/<br>│   └── chat.html       # Dark-themed browser chat UI<br>├── requirements.txt    # Python dependencies<br>└── Dockerfile          # Multi-stage Docker build</pre><h3>The MCP Backend (k8s_mcp.py)</h3><h3>Authentication</h3><pre>try:<br>    config.load_incluster_config()   # Inside a K8s pod → ServiceAccount token<br>except config.ConfigException:<br>    config.load_kube_config()        # Local dev → ~/.kube/config</pre><pre>v1            = client.CoreV1Api()<br>networking_v1 = client.NetworkingV1Api()<br>apps_v1       = client.AppsV1Api()<br>batch_v1      = client.BatchV1Api()</pre><h3>The New @mcp.prompt() — Guided Resource Creation</h3><p>This is the standout addition in this version. An MCP Prompt is not a chat message — it’s a reusable, parameterised instruction template that the MCP server delivers to the AI model as a system-level directive.</p><pre>@mcp.prompt()<br>def create_k8s_resource(<br>    resource_type: Optional[str] = None,<br>    namespace: Optional[str] = None,<br>    name: Optional[str] = None,<br>    image: Optional[str] = None,<br>    replicas: Optional[int] = None,<br>    schedule: Optional[str] = None,<br>) -&gt; str:<br>    &quot;&quot;&quot;Guided workflow for creating a Kubernetes Deployment, Pod, or CronJob.</pre><pre>    The assistant must walk the user through the required fields, verify the<br>    namespace exists, and only then call the matching create_* tool.<br>    &quot;&quot;&quot;<br>    return f&quot;&quot;&quot;You are helping the user create a Kubernetes resource.<br>Follow these steps strictly and in order.<br>Do NOT call any create_* tool until every required field is confirmed.</pre><pre>STEP 1 — NAMESPACE<br>    a. Call list_namespaces first.<br>    b. Pre-filled namespace: {namespace!r}<br>       - If provided AND in the list → use it.<br>       - If provided but NOT in the list → ask the user to choose a different one<br>         or fall back to &#39;default&#39;. Do NOT auto-create the namespace.<br>       - If None → silently default to &#39;default&#39;.</pre><pre>STEP 2 — RESOURCE TYPE<br>    Pre-filled resource_type: {resource_type!r}<br>    If missing → ask: &quot;What do you want to create — a Deployment, Pod, or CronJob?&quot;</pre><pre>STEP 3 — COMMON FIELDS<br>    Pre-filled name: {name!r}, image: {image!r}<br>    Ask for any that are missing.</pre><pre>STEP 4 — RESOURCE-SPECIFIC FIELDS<br>    DEPLOYMENT → ask for replicas, cpu (e.g. &#39;100m&#39;), memory (e.g. &#39;128Mi&#39;)<br>    POD        → no extra fields<br>    CRONJOB    → ask for schedule (e.g. &#39;*/5 * * * *&#39;)</pre><pre>STEP 5 — CONFIRM THEN CALL<br>    Summarise all fields → wait for user confirmation →<br>    call exactly ONE of: create_deployment / create_pod / create_cronjob<br>&quot;&quot;&quot;</pre><p><strong>Why this matters:</strong> Without the prompt, a user asking <em>“create a deployment”</em> might get a partially-formed resource if they forget to specify CPU limits or replica count. The @mcp.prompt() enforces a complete, ordered interview before any write operation executes. It&#39;s a guardrail baked into the protocol layer, not bolted on as application logic.</p><h3>Tool Surface (12 tools)</h3><p>Tool Operation API Group list_namespaces Read CoreV1Api create_namespace Write CoreV1Api list_pods Read CoreV1Api create_pod Write CoreV1Api list_services Read CoreV1Api create_service Write CoreV1Api list_ingresses Read NetworkingV1Api create_deployment Write AppsV1Api list_daemonsets Read AppsV1Api create_daemonset Write AppsV1Api list_cronjobs Read BatchV1Api create_cronjob Write BatchV1Api</p><h3>Transport Modes</h3><pre>if __name__ == &quot;__main__&quot;:<br>    transport = os.environ.get(&quot;MCP_TRANSPORT&quot;, &quot;streamable-http&quot;).strip().lower()<br>    port_env  = os.environ.get(&quot;FASTMCP_PORT&quot;) or os.environ.get(&quot;MCP_PORT&quot;)<br>    if port_env:<br>        mcp.settings.port = int(port_env)</pre><pre>    if transport in (&quot;sse&quot;, &quot;streamable-http&quot;):<br>        mcp.run(transport=transport)<br>    elif transport == &quot;stdio&quot;:<br>        mcp.run()    # for Cursor / Claude Desktop</pre><p>MCP_TRANSPORT Use case streamable-http Default — modern HTTP streaming sse Legacy SSE — used with the FastAPI frontend stdio For MCP clients (Cursor, Claude Desktop) that spawn the process directly</p><h3>The FastAPI Frontend (k8s_api.py)</h3><h3>MCP Prompt Fetching — New in This Version</h3><p>The frontend now fetches MCP prompts from the server and injects them as a system message before the user’s query:</p><pre>async def _fetch_mcp_prompts_as_system(session: ClientSession) -&gt; str:<br>    &quot;&quot;&quot;Fetch prompts with no required args and return them as a system prompt block.&quot;&quot;&quot;<br>    try:<br>        listing = await session.list_prompts()<br>    except Exception:<br>        return &quot;&quot;   # non-fatal — works fine against servers with no prompts</pre><pre>    blocks = []<br>    for p in listing.prompts:<br>        required_args = [a.name for a in (p.arguments or []) if getattr(a, &quot;required&quot;, False)]<br>        if required_args:<br>            continue   # skip prompts that need parameters<br>        res = await session.get_prompt(p.name, {})<br>        body = &quot;\n&quot;.join(_prompt_message_text(m) for m in res.messages).strip()<br>        if body:<br>            blocks.append(f&quot;# Prompt: {p.name}\n{body}&quot;)</pre><pre>    return &quot;\n\n---\n\n&quot;.join(blocks)</pre><p>This is then prepended to the OpenAI messages array as a system message:</p><pre>async def _ai_query_via_mcp_sse(sse_url: str, user_query: str) -&gt; dict:<br>    async with sse_client(sse_url) as streams:<br>        async with ClientSession(*streams) as session:<br>            await session.initialize()</pre><pre>            # Discover tools dynamically<br>            lt = await session.list_tools()<br>            openai_tools = _mcp_tools_to_openai(lt)</pre><pre>            # Fetch MCP prompts as system context<br>            system_prompt = await _fetch_mcp_prompts_as_system(session)<br>            messages = []<br>            if system_prompt:<br>                messages.append({&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt})<br>            messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_query})</pre><pre>            # Pass 1: AI selects tools<br>            resp1 = await anyio.to_thread.run_sync(<br>                lambda: _throttled_create(<br>                    model=OPENAI_MODEL,<br>                    input=messages,<br>                    tools=openai_tools,<br>                    store=True,<br>                )<br>            )</pre><pre>            # Execute tool calls through MCP session<br>            tool_results = []<br>            for item in resp1.output:<br>                if item.type == &quot;function_call&quot;:<br>                    args = json.loads(item.arguments or &quot;{}&quot;)<br>                    ctr = await session.call_tool(item.name, args)<br>                    tool_results.append({<br>                        &quot;type&quot;: &quot;function_call_output&quot;,<br>                        &quot;call_id&quot;: item.call_id,<br>                        &quot;output&quot;: json.dumps(_call_tool_result_to_plain(ctr)),<br>                    })</pre><pre>            # Pass 2: Summarise results<br>            if tool_results:<br>                resp_final = await anyio.to_thread.run_sync(...)</pre><pre>            return {&quot;answer&quot;: ..., &quot;tools_called&quot;: ..., &quot;via_mcp&quot;: True}</pre><p>The prompt fetch is <strong>non-fatal</strong> — if the MCP server exposes no prompts or the fetch fails, the query continues normally with tools only.</p><h3>Rate Limiter</h3><pre>_rpm_limit = 3    # OpenAI free-tier: 3 requests per 60-second window</pre><p>Queues requests transparently — users never see a raw 429 error.</p><h3>Getting Started</h3><h3>Prerequisites</h3><ul><li>Python 3.11+ with uv installed (pip install uv)</li><li>A running Kubernetes cluster with kubectl configured</li><li>An OpenAI API key</li><li>AWS credentials (if your cluster uses EKS/IAM auth)</li></ul><h3>Clone the Repository</h3><pre>git clone git@github.com:praveensamca/kubernetes-mcp.git<br>cd kubernetes-mcp</pre><h3>Install Dependencies</h3><pre>uv sync<br># or<br>uv pip install -r requirements.txt</pre><h3>Step 1 — Export OpenAI API Key</h3><pre>export OPENAI_API_KEY=&#39;your-openai-api-key-here&#39;</pre><p>Or add to .env in the project root (auto-loaded on startup):</p><pre>OPENAI_API_KEY=your-openai-api-key-here</pre><h3>Step 2 — Start the MCP Backend</h3><pre>MCP_TRANSPORT=sse \<br>FASTMCP_PORT=8767 \<br>AWS_ACCESS_KEY_ID=&#39;your-aws-access-key&#39; \<br>AWS_SECRET_ACCESS_KEY=&#39;your-aws-secret-key&#39; \<br>AWS_REGION=us-east-1 \<br>AWS_DEFAULT_REGION=us-east-1 \<br>uv run python k8s_mcp.py</pre><p>Expected output:</p><pre>INFO:     Uvicorn running on http://0.0.0.0:8767</pre><h3>Step 3 — Start the FastAPI Frontend</h3><p>In a <strong>second terminal</strong>:</p><pre>AWS_ACCESS_KEY_ID=&#39;your-aws-access-key&#39; \<br>AWS_SECRET_ACCESS_KEY=&#39;your-aws-secret-key&#39; \<br>AWS_REGION=us-east-1 \<br>AWS_DEFAULT_REGION=us-east-1 \<br>uv run python k8s_api.py</pre><p>Expected output:</p><pre>INFO:     Uvicorn running on http://0.0.0.0:8000</pre><h3>Step 4 — Open the Chat UI</h3><pre>http://localhost:8000</pre><p>Both processes must be running simultaneously.</p><h3>Environment Variables Reference</h3><p>Variable Process Description OPENAI_API_KEY k8s_api.py OpenAI API key (required) OPENAI_MODEL k8s_api.py Model name (default: gpt-5.4-mini) MCP_SSE_URL k8s_api.py MCP server URL (default: http://127.0.0.1:8767/sse) MCP_TRANSPORT k8s_mcp.py Transport: sse, streamable-http, stdio FASTMCP_PORT k8s_mcp.py MCP server port (set to 8767) AWS_ACCESS_KEY_ID both AWS access key for EKS auth AWS_SECRET_ACCESS_KEY both AWS secret key AWS_REGION both AWS region (e.g. us-east-1) AWS_DEFAULT_REGION both AWS default region</p><h3>Connect to Claude Desktop (stdio mode)</h3><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;kubernetes&quot;: {<br>      &quot;command&quot;: &quot;uv&quot;,<br>      &quot;args&quot;: [&quot;run&quot;, &quot;python&quot;, &quot;/path/to/kubernetes-mcp/k8s_mcp.py&quot;],<br>      &quot;env&quot;: {<br>        &quot;MCP_TRANSPORT&quot;: &quot;stdio&quot;,<br>        &quot;AWS_ACCESS_KEY_ID&quot;: &quot;your-key&quot;,<br>        &quot;AWS_SECRET_ACCESS_KEY&quot;: &quot;your-secret&quot;,<br>        &quot;AWS_REGION&quot;: &quot;us-east-1&quot;<br>      }<br>    }<br>  }<br>}</pre><p>All 12 tools and the create_k8s_resource prompt will appear in Claude Desktop.</p><h3>Deploy Inside a Cluster</h3><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: kubernetes-mcp<br>rules:<br>  - apiGroups: [&quot;&quot;, &quot;apps&quot;, &quot;batch&quot;, &quot;networking.k8s.io&quot;]<br>    resources:<br>      - namespaces<br>      - pods<br>      - services<br>      - deployments<br>      - daemonsets<br>      - cronjobs<br>      - ingresses<br>    verbs: [&quot;get&quot;, &quot;list&quot;, &quot;create&quot;]</pre><h3>Example Interactions</h3><p><strong>Guided resource creation (uses the new MCP Prompt):</strong></p><pre>Create a deployment</pre><p>→ AI runs the full guided workflow: checks namespace → asks for name, image, replicas, CPU, memory → confirms → creates</p><p><strong>Direct natural-language queries:</strong></p><pre>Show me all pods in the production namespace<br>List all services across the cluster<br>What CronJobs are running and when did they last fire?<br>Are there any DaemonSets not fully scheduled?</pre><p><strong>Full single-prompt provisioning:</strong></p><pre>Deploy nginx:latest to the staging namespace with 2 replicas</pre><p>→ AI checks if staging exists → creates it if not → creates the deployment → summarises result</p><p><strong>Via REST API:</strong></p><pre># Natural language query<br>curl -X POST http://localhost:8000/ai/query \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;query&quot;: &quot;List all pods in the default namespace&quot;}&#39;</pre><pre># Override MCP server per-request<br>curl -X POST <a href="http://localhost:8000/ai/query">http://localhost:8000/ai/query</a> \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;query&quot;: &quot;Create a deployment&quot;, &quot;mcp_sse_url&quot;: &quot;http://my-server:8767&quot;}&#39;</pre><h3>Troubleshooting</h3><p><strong>OPENAI_API_KEY is not set</strong> — Export the key or add it to .env.</p><p><strong>MCP server returned no tools</strong> — MCP backend isn&#39;t running. Confirm http://127.0.0.1:8767/sse is reachable with MCP_TRANSPORT=sse and FASTMCP_PORT=8767.</p><p><strong>Connection refused on 8767</strong> — Start the MCP backend before the frontend. Both must run simultaneously.</p><p><strong>ApiException: Forbidden</strong> — Apply the RBAC manifest. Add namespaces to the resources list for namespace operations.</p><p><strong>Rate limit (429)</strong> — Increase _rpm_limit in k8s_api.py if you have a paid OpenAI plan.</p><h3>What’s Next</h3><ul><li><strong>Delete tools</strong> — delete_namespace, delete_pod, delete_deployment with confirmation</li><li><strong>Pod log streaming</strong> — kubectl logs equivalent</li><li><strong>describe tools</strong> — detailed resource inspection</li><li><strong>More MCP Prompts</strong> — guided workflows for updates, scaling, rollbacks</li><li><strong>Multi-cluster support</strong> — switch kubeconfig contexts via natural language</li><li><strong>Swap to Claude natively</strong> — end-to-end MCP consistency with Anthropic models</li></ul><h3>Conclusion</h3><p>Each iteration of this project shows MCP maturing as a protocol. This version adds @mcp.prompt() — a mechanism to deliver structured, step-by-step AI workflows as a server-side concern. The AI doesn&#39;t need to be told how to safely create a Kubernetes resource in the system prompt of every request; the MCP server carries that knowledge and injects it automatically.</p><p>The result: a loosely coupled, extensible Kubernetes AI assistant where adding new capabilities means editing one Python file, not rebuilding a stack.</p><p><strong>Clone it, set your keys, start both processes, and talk to your cluster.</strong></p><pre>git clone git@github.com:praveensamca/kubernetes-mcp.git<br>cd kubernetes-mcp</pre><pre># Terminal 1 — Backend<br>MCP_TRANSPORT=sse FASTMCP_PORT=8767 uv run python k8s_mcp.py</pre><pre># Terminal 2 — Frontend<br>uv run python k8s_api.py</pre><pre># Open → <a href="http://localhost:8000/">http://localhost:8000</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8Yk6aPrO79opYvsIpcqUQ.png" /></figure><p><em>Tags: #Kubernetes #MCP #ModelContextProtocol #AI #DevOps #Python #FastAPI #OpenAI #LLM #PlatformEngineering #CloudNative</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7417d0bdcbe6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevOps Helpdesk with LLMs and AWS Bedrock ( Part 1)]]></title>
            <link>https://medium.com/@praveensams16/devops-helpdesk-with-llms-and-aws-bedrock-part-1-3ae6601105a8?source=rss-a25371fc5cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ae6601105a8</guid>
            <dc:creator><![CDATA[Praveensam]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 09:35:59 GMT</pubDate>
            <atom:updated>2025-12-19T09:50:37.532Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Disclaimer:</strong><br><em> This solution is currently driven by predefined prompts. Additional validation, security controls, prompt hardening, and guardrails must be carefully implemented before using this approach in a production environment. It an attempt to demonstrate how to run a model using Amazon Bedrock and to illustrate how model behavior looks when driven by prompts. It is intended for learning and experimentation rather than production use.</em></p><p>In modern DevOps teams, engineers often juggle sprawling cloud environments, complex CI/CD pipelines, and fast-moving incidents. What if you could ask an AI <em>“What’s wrong with my ECS service?”</em> or <em>“How do I troubleshoot an Azure VPN failover?”</em> and get back a clear, helpful answer?</p><p>That’s exactly the problem we tackled in <strong>devops_llm, </strong>an LLM-powered DevOps assistant that uses <strong>AWS Bedrock</strong> as the model backend, exposes a REST API, and can be queried with natural language to respond with actionable insights.</p><p>I made a project shows how to build a simple <strong>DevOps Query Responder</strong> using AWS Bedrock, AWS Lambda, API Gateway, and a lightweight web interface. The frontend allows users to type in their DevOps questions, which are then sent to an API endpoint. Behind the scenes, AWS Lambda works as the backend, passing the request to AWS Bedrock and sending the response back to the user.</p><p>I chose <strong>Anthropic Claude 3 Haiku</strong> because it is fast, cost-effective, and works well for real-time applications. For DevOps use cases, quick and clear answers are more important than long or creative responses. Claude 3 Haiku fits this need perfectly and performs reliably even when handling multiple requests.</p><p>To keep the responses focused, the backend enforces a strict DevOps-only context. The Lambda function defines the model’s role as a DevOps, SRE, and MLOps engineer and clearly limits the topics it can respond to. Since this logic is controlled by the API, the model does not return generic or unrelated answers, keeping responses accurate and relevant.</p><p>The entire setup is deployed using a simple run.sh script that triggers Terraform to create all required AWS resources. Credentials are handled securely using environment variables or IAM roles. After deployment, the application can be accessed locally at http://localhost:8080, making it easy to test and extend before moving to a cloud-based setup.</p><pre>┌──────────────────┐<br>│   Frontend UI    │<br>│ (HTML App)  │<br>│ User enters text │<br>└─────────┬────────┘<br>          │ HTTP POST (message, history)<br>          ▼<br>┌────────────────────────┐<br>│      API Gateway       │<br>│  /invoke (HTTP API)    │<br>│  CORS + routing        │<br>└─────────┬──────────────┘<br>          │<br>          ▼<br>┌──────────────────────────────────────────┐<br>│           AWS Lambda (Backend)            │<br>│                                          │<br>│ 1. Validate request &amp; CORS               │<br>│ 2. Build DevOps-only prompt              │<br>│    - Role: DevOps / SRE / MLOps           │<br>│    - Allowed topics defined              │<br>│    - Explicit refusal rules              │<br>│    - Example conditioning                │<br>│ 3. Low temperature enforcement           │<br>│ 4. Server-side control (user can’t alter)│<br>└─────────┬────────────────────────────────┘<br>          │ invoke_model()<br>          ▼<br>┌────────────────────────────────────┐<br>│       AWS Bedrock Runtime           │<br>│  Claude 3 Haiku (LLM Inference)     │<br>│  Obeys DevOps-only prompt rules     │<br>└─────────┬──────────────────────────┘<br>          │ response text<br>          ▼<br>┌──────────────────────────────────────────┐<br>│           AWS Lambda (Backend)            │<br>│ 5. Extract response text                 │<br>│ 6. Wrap JSON + CORS headers              │<br>└─────────┬────────────────────────────────┘<br>          │<br>          ▼<br>┌──────────────────┐<br>│   Frontend UI    │<br>│ Shows response   │<br>│ (DevOps only)    │<br>└──────────────────┘</pre><p><strong>Repo: </strong><a href="https://github.com/praveensamca/devops_llm.git"><strong>https://github.com/praveensamca/devops_llm.git</strong></a></p><p><strong>devops_llm</strong> is a repository that provides:</p><ul><li>A backend server (likely Python) exposing an API to accept DevOps questions.</li><li>Integration with Amazon Bedrock models for large-language model inference.</li><li>Supporting infrastructure (Terraform) to deploy necessary AWS resources.</li><li>Scripts to run and manage the application locally or in the cloud.</li></ul><h4><strong>Architecture Overview</strong></h4><p><strong>Client / Frontend</strong> — Sends user questions via an endpoint.</p><p><strong>API Server</strong> — A Python backend that accepts questions and talks to Bedrock.</p><p><strong>LLM Integration</strong> — Calls Bedrock with prompts and returns answers.</p><p><strong>Infrastructure-as-Code</strong> — Terraform files define the cloud resources.</p><p><strong>Shell Scripts</strong> — Convenient scripts to start or test the service.</p><p>Each component is designed to make queries responsive, scalable, and secure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7UDXVrzasRtfGrjHvFMfew.png" /></figure><h4>Frontend Server (Python + html render)</h4><p>Front end is small interface ( UI ) , which accept user query in natural language and pass as aguement to backend ( lambda)</p><p>The core logic lives in a Python file (likely <a href="https://github.com/praveensamca/devops_llm/blob/main/server.py">server.py</a>). This script:</p><ul><li>Spins up a HTTP API server (Flask, FastAPI, or similar)</li><li>Accepts natural language DevOps questions</li><li>Formats prompts for Bedrock</li><li>Forwards responses back to the client</li></ul><p>This approach keeps your DevOps knowledge <em>queryable</em> with AI.</p><pre># server.py<br>from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler<br>from urllib.parse import parse_qs, urlparse<br>from jinja2 import Environment, FileSystemLoader<br>import os<br>import argparse<br><br>BASE_DIR = os.path.dirname(os.path.abspath(__file__))<br><br>env = Environment(<br>    loader=FileSystemLoader(os.path.join(BASE_DIR, &quot;frontend&quot;)),<br>    autoescape=True<br>)<br>template = env.get_template(&quot;interface.html&quot;)<br><br><br>class Handler(BaseHTTPRequestHandler):<br>    api_gateway = &quot;&quot;<br><br>    def end_headers(self):<br>        self.send_header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)<br>        self.send_header(&quot;Access-Control-Allow-Methods&quot;, &quot;GET, POST, OPTIONS&quot;)<br>        self.send_header(&quot;Access-Control-Allow-Headers&quot;, &quot;Content-Type, Authorization&quot;)<br>        super().end_headers()<br><br>    def do_OPTIONS(self):<br>        self.send_response(204)<br>        self.end_headers()<br><br>    def do_GET(self):<br>        query = parse_qs(urlparse(self.path).query)<br>        name = query.get(&quot;name&quot;, [&quot;&quot;])[0]<br><br>        html = template.render(<br>            user_input=name,<br>            api_gateway_endpoint=self.api_gateway<br>        )<br><br>        self.send_response(200)<br>        self.send_header(&quot;Content-Type&quot;, &quot;text/html; charset=utf-8&quot;)<br>        self.end_headers()<br>        self.wfile.write(html.encode(&quot;utf-8&quot;))<br><br><br>def main():<br>    parser = argparse.ArgumentParser(description=&quot;Jinja UI server&quot;)<br>    parser.add_argument(<br>        &quot;--api-gateway&quot;,<br>        required=True,<br>        help=&quot;API Gateway base URL, e.g. https://snzjbnrwre.execute-api.us-east-1.amazonaws.com/prod/&quot;<br>    )<br>    parser.add_argument(&quot;--port&quot;, type=int, default=8080)<br>    args = parser.parse_args()<br>    print(args.api_gateway)<br><br>    # Make it accessible inside the handler<br>    Handler.api_gateway = args.api_gateway.rstrip(&quot;/&quot;).replace(&#39;&quot;&#39;,&#39;&#39;)  # remove trailing /<br><br>    print(f&quot;Serving at http://localhost:{args.port}&quot;)<br>    print(f&quot;API Gateway: {Handler.api_gateway}&quot;)<br><br>    ThreadingHTTPServer((&quot;0.0.0.0&quot;, args.port), Handler).serve_forever()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUoUGqdLaWoogltVttI25Q.png" /></figure><p><strong>How Lambda Acts as the Backend Server</strong></p><p>In this architecture, <strong>AWS Lambda functions as the backend server</strong> that sits between the frontend application and <strong>Amazon Bedrock</strong>.</p><p>When a user enters a question or prompt in the frontend (such as a web UI, CLI, or chatbot), the request is <strong>not sent directly to Bedrock</strong>. Instead, it follows a controlled backend flow for security, scalability, and cost management.</p><p>Here’s what happens step by step:</p><p><strong>Frontend sends a request</strong></p><ul><li>The frontend sends a HTTP request (usually via API Gateway) containing the user’s prompt.</li></ul><p><strong>API Gateway invokes Lambda</strong></p><ul><li>API Gateway receives the request and triggers the Lambda function.</li><li>This makes Lambda behave like a <strong>serverless backend API</strong>, without managing servers.</li></ul><p><strong>Lambda processes the request</strong></p><ul><li>Lambda validates and parses the input.</li><li>It enriches or formats the prompt (for example, adding DevOps context or system instructions).</li><li>Sensitive logic and credentials remain safely inside AWS.</li></ul><p><strong>Lambda forwards the request to Amazon Bedrock</strong></p><ul><li>Using IAM roles, Lambda securely calls Bedrock’s InvokeModel API.</li><li>The prompt is sent to the configured LLM (Claude, Titan, etc.).</li><li>No API keys are exposed to the frontend.</li></ul><p><strong>Bedrock generates the response</strong></p><ul><li>The LLM processes the prompt and returns a natural-language response tailored to the DevOps query.</li></ul><p><strong>Lambda returns the response to the requester</strong></p><ul><li>Lambda formats the model output as JSON.</li><li>The response is sent back through API Gateway to the frontend.</li><li>The user sees the final answer almost instantly.</li></ul><h3>Why This Design Matters</h3><p>Using Lambda as the backend provides several key advantages:</p><ul><li><strong>Security</strong> — Bedrock access is protected by IAM; the frontend never talks directly to the LLM.</li><li><strong>Scalability</strong> — Lambda automatically scales with traffic.</li><li><strong>Cost efficiency</strong> — You only pay when requests are made.</li><li><strong>Separation of concerns</strong> — Frontend handles UI, Lambda handles AI logic, Bedrock handles inference.</li><li><strong>Enterprise-ready</strong> — Fits well with compliance and cloud governance models.</li></ul><h3><strong>Model Chosen !!</strong></h3><p>I chose <strong>Anthropic’s Claude 3 Haiku</strong> on AWS Bedrock because it offers an excellent balance between speed, cost, and performance. For a DevOps query responder, low latency is critical, and Haiku delivers fast responses that feel near real-time. It is also more cost-effective than larger models, which makes it ideal for scalable workloads and frequent API calls. Despite being lightweight, the model understands technical language well and follows instructions accurately, making it suitable for tasks like troubleshooting, summarizing logs, and answering infrastructure-related questions.</p><pre>import json<br>import boto3<br>import traceback<br><br>client = boto3.client(&quot;bedrock-runtime&quot;, region_name=&quot;us-east-1&quot;)<br><br># ✅ CORS headers (allow all). If you want strict, replace &quot;*&quot; with &quot;http://localhost:8080&quot; or your domain.<br>CORS_HEADERS = {<br>    &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;,<br>    &quot;Access-Control-Allow-Methods&quot;: &quot;OPTIONS,POST&quot;,<br>    &quot;Access-Control-Allow-Headers&quot;: &quot;content-type,authorization,x-amz-date,x-api-key,x-amz-security-token,x-requested-with&quot;,<br>    &quot;Access-Control-Max-Age&quot;: &quot;86400&quot;,<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>}<br><br>def make_response(status_code: int, body: dict):<br>    return {<br>        &quot;statusCode&quot;: status_code,<br>        &quot;headers&quot;: CORS_HEADERS,<br>        &quot;body&quot;: json.dumps(body),<br>    }<br><br>def lambda_handler(event, context):<br>    try:<br>        # ✅ Handle preflight request (OPTIONS)<br>        method = event.get(&quot;requestContext&quot;, {}).get(&quot;http&quot;, {}).get(&quot;method&quot;, &quot;&quot;)<br>        if method == &quot;OPTIONS&quot;:<br>            return {<br>                &quot;statusCode&quot;: 200,<br>                &quot;headers&quot;: CORS_HEADERS,<br>                &quot;body&quot;: &quot;&quot;,<br>            }<br><br>        # ✅ Validate body<br>        if &quot;body&quot; not in event or event[&quot;body&quot;] is None:<br>            return make_response(400, {&quot;error&quot;: &quot;Request body is missing&quot;})<br><br>        # ✅ Parse JSON body<br>        raw_body = event[&quot;body&quot;]<br>        if isinstance(raw_body, str):<br>            try:<br>                body = json.loads(raw_body)<br>                # Some clients send nested {&quot;body&quot;: {...}}<br>                if isinstance(body, dict) and &quot;body&quot; in body and isinstance(body[&quot;body&quot;], dict):<br>                    body = body[&quot;body&quot;]<br>            except json.JSONDecodeError:<br>                return make_response(400, {&quot;error&quot;: &quot;Invalid JSON in request body&quot;})<br>        elif isinstance(raw_body, dict):<br>            body = raw_body<br>        else:<br>            return make_response(400, {&quot;error&quot;: &quot;Unsupported body format&quot;})<br><br>        # ✅ Extract parameters expected from the frontend<br>        message = body.get(&quot;message&quot;, &quot;&quot;)<br>        history = body.get(&quot;history&quot;, &quot;&quot;)<br>        system = body.get(&quot;system&quot;, &quot;&quot;)<br>        prefill = body.get(&quot;prefill&quot;, &quot;&quot;)<br><br>        print(&quot;Incoming message:&quot;, message)<br><br>        # ---- Prompt elements ----<br>        TASK_CONTEXT = (<br>            &quot;You are acting as a DevOps, SRE, and MLOps engineer named DevOps, &quot;<br>            &quot;created by the company by a person P. &quot;<br>            &quot;Your role is to support and answer user questions strictly related to &quot;<br>            &quot;infrastructure, cloud platforms, networking, CI/CD pipelines (including Jenkins), &quot;<br>            &quot;containerization, Kubernetes, observability, reliability, automation, and MLOps workflows. &quot;<br>            &quot;You must not provide career advice or respond outside these technical domains. &quot;<br>            &quot;All responses should be clear, practical, and focused on solving production and operational issues.&quot;<br>        )<br><br>        TONE_CONTEXT = &quot;You should maintain a friendly customer service tone.&quot;<br><br>        TASK_DESCRIPTION = &quot;&quot;&quot;Interaction rules:<br>    - Act strictly as a production-focused DevOps/SRE/MLOps engineer<br>    - Provide concise, technically accurate answers with best practices<br>    - Do not answer questions outside infrastructure, networking, CI/CD, Jenkins, Kubernetes, or MLOps<br>    - For unclear questions, ask for clarification<br>    - For unrelated questions, politely decline and restate supported topics<br>    &quot;&quot;&quot;<br>        EXAMPLES = &quot;&quot;&quot;Here is an example of how to respond in a standard interaction:<br>    &lt;example&gt;<br>    User: How can you help me?<br>    DevOps: Hello! I am DevOps, an AI DevOps/SRE/MLOps assistant created by the company by a person P.<br>    I help with infrastructure, cloud platforms, networking, CI/CD pipelines (including Jenkins),<br>    Kubernetes, reliability, observability, automation, and MLOps-related questions.<br>    &lt;/example&gt;&quot;&quot;&quot;<br><br>        INPUT_DATA = f&quot;&quot;&quot;Here is the conversational history (between the user and DevOps) prior to the question.<br>    It may be empty if there is no prior conversation:<br>    &lt;history&gt;<br>    {history}<br>    &lt;/history&gt;<br><br>    Here is the user&#39;s question:<br>    &lt;question&gt;<br>    {message}<br>    &lt;/question&gt;&quot;&quot;&quot;<br><br><br>        IMMEDIATE_TASK = &quot;How do you respond to the user&#39;s question?&quot;<br>        PRECOGNITION = &quot;Think about your answer first before you respond.&quot;<br>        OUTPUT_FORMATTING = &quot;Put your response in &lt;response&gt;&lt;/response&gt; tags.&quot;<br><br>        # If you want to support user-provided prefill, fallback to default<br>        PREFILL = prefill if prefill else &quot;[DevOPS] &lt;response&gt;&quot;<br><br>        PROMPT = &quot;\n\n&quot;.join([<br>            TASK_CONTEXT,<br>            TONE_CONTEXT,<br>            TASK_DESCRIPTION,<br>            EXAMPLES,<br>            INPUT_DATA,<br>            IMMEDIATE_TASK,<br>            PRECOGNITION,<br>            OUTPUT_FORMATTING<br>        ])<br><br>        # ---- Bedrock request body (Claude 3) ----<br>        request_body = {<br>            &quot;anthropic_version&quot;: &quot;bedrock-2023-05-31&quot;,<br>            &quot;max_tokens&quot;: 1200,<br>            &quot;messages&quot;: [<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: PROMPT},<br>                {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: PREFILL}<br>            ],<br>            &quot;temperature&quot;: 0.2,<br>            &quot;top_p&quot;: 1,<br>            # You can pass a system string from frontend; otherwise keep it empty<br>            &quot;system&quot;: system or &quot;&quot;<br>        }<br><br>        response = client.invoke_model(<br>            modelId=&quot;anthropic.claude-3-haiku-20240307-v1:0&quot;,<br>            body=json.dumps(request_body)<br>        )<br><br>        response_body = json.loads(response[&quot;body&quot;].read())<br><br>        # Extract output text (Claude 3 format)<br>        if &quot;content&quot; in response_body and response_body[&quot;content&quot;]:<br>            response_text = response_body[&quot;content&quot;][0].get(&quot;text&quot;, &quot;&quot;)<br>        elif &quot;completion&quot; in response_body:<br>            response_text = response_body[&quot;completion&quot;]<br>        else:<br>            response_text = str(response_body)<br><br>        return make_response(200, {&quot;response&quot;: response_text})<br><br>    except Exception as e:<br>        print(&quot;Error:&quot;, str(e))<br>        print(traceback.format_exc())<br>        return make_response(500, {&quot;error&quot;: f&quot;An error occurred: {str(e)}&quot;})</pre><p>Overall, Claude 3 Haiku fits perfectly for building efficient, reliable, and production-ready DevOps assistants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnCKFcuF5H-7AQB0TZpDvQ.png" /></figure><p><strong>How do we restrict model to respond Devops Query</strong></p><p>This Lambda function enforces <strong>strict DevOps-only behavior</strong> by controlling the model through prompt engineering rather than code-level filtering. The restriction is applied before the request is sent to AWS Bedrock.</p><p>Role Definition (TASK_CONTEXT)</p><p>The TASK_CONTEXT explicitly defines the model’s identity as a <strong>DevOps, SRE, and MLOps engineer</strong>. It clearly lists allowed domains such as infrastructure, cloud platforms, networking, CI/CD, Kubernetes, observability, and automation, and explicitly instructs the model <strong>not to answer questions outside these areas</strong>.</p><p>TASK_CONTEXT = (<br> “You are acting as a DevOps, SRE, and MLOps engineer…”<br>)</p><h4>Explicit Interaction Rules (TASK_DESCRIPTION)</h4><p>The TASK_DESCRIPTION enforces behavioral rules:</p><ul><li>Answer <strong>only</strong> DevOps, SRE, and MLOps topics</li><li>Ask for clarification if a question is unclear</li><li>Politely decline unrelated questions</li></ul><p>These rules act as <strong>guardrails</strong> that guide the model’s output.</p><h4>Example-Driven Conditioning (EXAMPLES)</h4><p>The EXAMPLES section shows the model how it should introduce itself and what kind of help it provides. Examples strongly influence model behavior and reinforce the DevOps-only role.</p><h4>Controlled Prompt Construction (PROMPT)</h4><p>All constraints are merged into a single prompt:</p><ul><li>Role definition</li><li>Rules</li><li>Example</li><li>User’s question</li></ul><p>This full prompt is passed as the <strong>user message</strong>, ensuring the model always sees the restrictions before responding.</p><h4><strong>Low Temperature for Deterministic Output</strong></h4><p>temperature: 0.2. ( This is sensitive which differentiate hallucination )<br>A low temperature reduces creative or off-topic responses and keeps answers precise and operational, which is ideal for DevOps use cases.</p><h4>Prefill Reinforcement</h4><p>The assistant prefill (PREFILL) nudges the model to start its response <strong>inside the expected role</strong>, reinforcing compliance.</p><h4>Backend Enforcement via Lambda</h4><p>Because the prompt is constructed <strong>server-side in Lambda</strong>, users cannot bypass or modify the DevOps restrictions from the frontend. This makes the control <strong>secure and consistent</strong>.</p><h3><strong>How to deploy</strong></h3><p>Deployment is fully automated using the run.sh script, which internally triggers Terraform to provision and configure all required AWS resources. AWS credentials are not hardcoded; instead, authentication is handled securely using environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) or by attaching an appropriate IAM role to the execution environment. This approach follows AWS security best practices and ensures safe, repeatable, and production-ready deployments.</p><p>Repo: <a href="https://github.com/praveensamca/devops_llm.git">https://github.com/praveensamca/devops_llm.git</a></p><p>.<br>├── frontend<br>│ └── interface.html<br>├── lambda.tf<br>├── module<br>│ └── lambda<br>│ ├── access.tf<br>│ ├── api-gateway-integration.tf<br>│ ├── bedrock_lambda_function.zip<br>│ ├── lambda.tf<br>│ ├── output.tf<br>│ └── run.py<br>├── provider.tf<br>├── run.sh<br>├── server.py<br>├── terraform.tfstate<br>├── terraform.tfstate.backup<br>├── testing<br>└── variable.tf</p><pre> # sh run.sh<br>Initializing the backend...<br>Initializing modules...<br>Initializing provider plugins...<br>- Reusing previous version of hashicorp/local from the dependency lock file<br>- Reusing previous version of hashicorp/archive from the dependency lock file<br>- Reusing previous version of hashicorp/aws from the dependency lock file<br>- Using previously-installed hashicorp/local v2.6.1<br>- Using previously-installed hashicorp/archive v2.7.1<br>- Using previously-installed hashicorp/aws v6.27.0<br><br>Terraform has been successfully initialized!<br><br>You may now begin working with Terraform. Try running &quot;terraform plan&quot; to see<br>any changes that are required for your infrastructure. All Terraform commands<br>should now work.<br><br>If you ever set or change modules or backend configuration for Terraform,<br>rerun this command to reinitialize your working directory. If you forget, other<br>commands will detect it and remind you to do so if necessary.<br>module.lambda.data.archive_file.bedrock_lambda_function: Reading...<br>module.lambda.data.archive_file.bedrock_lambda_function: Read complete after 0s [id=8892ca26114e268b1f0b1a437e453b7bdfbe65dd]<br>module.lambda.data.aws_iam_policy_document.lambda_logs: Reading...<br>module.lambda.data.aws_iam_policy_document.bedrock_access: Reading...<br>module.lambda.data.aws_iam_policy_document.assume_role: Reading...<br>module.lambda.aws_apigatewayv2_api.bedrock_api: Refreshing state... [id=7n7ex35p1b]<br>module.lambda.data.aws_iam_policy_document.bedrock_access: Read complete after 0s [id=269154095]<br>module.lambda.data.aws_iam_policy_document.lambda_logs: Read complete after 0s [id=16712114]<br>module.lambda.data.aws_iam_policy_document.assume_role: Read complete after 0s [id=2690255455]<br>module.lambda.aws_iam_role.lambda_execution_role: Refreshing state... [id=lambda_execution_role]<br>module.lambda.aws_apigatewayv2_stage.prod: Refreshing state... [id=prod]<br>module.lambda.aws_iam_role_policy.lambda_bedrock_policy: Refreshing state... [id=lambda_execution_role:lambda-bedrock-access]<br>module.lambda.aws_iam_role_policy.lambda_logs_policy: Refreshing state... [id=lambda_execution_role:lambda-cloudwatch-logs]<br>module.lambda.aws_lambda_function.bedrock_lambda_function: Refreshing state... [id=bedrock_lambda_function]<br>module.lambda.aws_lambda_permission.allow_apigw: Refreshing state... [id=AllowExecutionFromAPIGateway]<br>module.lambda.aws_apigatewayv2_integration.bedrock_integration: Refreshing state... [id=az6lsqg]<br>module.lambda.aws_apigatewayv2_route.invoke_route: Refreshing state... [id=9slxzw9]<br><br>No changes. Your infrastructure matches the configuration.<br><br>Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.<br><br>Apply complete! Resources: 0 added, 0 changed, 0 destroyed.<br><br>Outputs:<br><br>api_gateway_endpoint = &quot;https://7n7ex35p1b.execute-api.us-east-1.amazonaws.com/prod/invoke&quot;<br>&quot;https://7n7ex35p1b.execute-api.us-east-1.amazonaws.com/prod/invoke&quot;<br>Serving at http://localhost:8080<br>API Gateway: https://7n7ex35p1b.execute-api.us-east-1.amazonaws.com/prod/invoke</pre><p><strong>Frontend sends a request</strong></p><ul><li>The frontend sends a HTTP request (usually via API Gateway) containing the user’s prompt.</li></ul><p><strong>API Gateway invokes Lambda</strong></p><ul><li>API Gateway receives the request and triggers the Lambda function.</li><li>This makes Lambda behave like a <strong>serverless backend API</strong>, without managing servers.</li></ul><p><strong>Lambda processes the request</strong></p><ul><li>Lambda validates and parses the input.</li><li>It enriches or formats the prompt (for example, adding DevOps context or system instructions).</li><li>Sensitive logic and credentials remain safely inside AWS.</li></ul><p><strong>Lambda forwards the request to Amazon Bedrock</strong></p><ul><li>Using IAM roles, Lambda securely calls Bedrock’s InvokeModel API.</li><li>The prompt is sent to the configured LLM (Claude, Titan, etc.).</li><li>No API keys are exposed to the frontend.</li></ul><p><strong>Bedrock generates the response</strong></p><ul><li>The LLM processes the prompt and returns a natural-language response tailored to the DevOps query.</li></ul><p><strong>Lambda returns the response to the requester</strong></p><ul><li>Lambda formats the model output as JSON.</li><li>The response is sent back through API Gateway to the frontend.</li><li>The user sees the final answer almost instantly.</li></ul><h3>How it works !!!!</h3><p>After deployment, you can access the portal at http://localhost:8080 when running the application in a local environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWM8WdGRofKu3AdlPErkCg.png" /></figure><p>Since the API enforces a predefined context and strict prompt rules, the model is constrained to the intended domain and does not produce generic or unrelated responses. This ensures consistent, focused, and domain-specific outputs aligned with DevOps use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ae6601105a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up Amazon EKS with EFS as a Storage Class: Persistent Storage Made Easy ( Terraform )]]></title>
            <link>https://medium.com/@praveensams16/how-to-set-up-amazon-eks-with-efs-as-a-storage-class-persistent-storage-made-easy-eb254e59bf5f?source=rss-a25371fc5cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb254e59bf5f</guid>
            <dc:creator><![CDATA[Praveensam]]></dc:creator>
            <pubDate>Wed, 28 May 2025 05:45:03 GMT</pubDate>
            <atom:updated>2025-06-01T19:07:23.327Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why EFS + EKS = A Match Made in Cloud Heaven for ML model build</strong></p><p>When you’re running stateful workloads on Amazon EKS (Elastic Kubernetes Service), one of the biggest headaches is figuring out <strong>persistent storage</strong>. Sure, EBS works for many cases, but what if you want <strong>multi-AZ availability</strong>, <strong>shared file access</strong>, and <strong>scalable storage that just grows as you go</strong>? That’s where <strong>Amazon EFS (Elastic File System)</strong> steps in like a hero.</p><p>In this post, we’ll walk through how to set up <strong>EFS as a dynamic storage class for your EKS workloads</strong>, so your pods can mount shared volumes across nodes, zones, and deployments. Whether you’re running a CMS, data processing jobs, or multi-tenant apps — this setup gives you cloud-native flexibility with rock-solid storage.</p><p>Let’s dive in and get you from zero to persistent volume hero</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*mipCz3l_luZZcUa5zAAYXw.png" /></figure><p><strong>Why we use EFS in AWS</strong></p><p>Amazon EFS (Elastic File System) is basically your go-to when you need a <strong>shared, scalable, and managed file system</strong> that works across multiple instances and services. Think of it like a magic folder in the cloud that all your servers can read and write to at the same time.</p><p>Here are some common real-world use cases:</p><h4>1. Shared Storage for Containers (like EKS)</h4><ul><li>Pods in different AZs need access to the same files? EFS is the answer.</li><li>Great for CMS apps (like WordPress), web servers, or multi-user apps where state needs to persist and be shared.</li></ul><h4>2. Machine Learning / Data Processing</h4><ul><li>Store training data in EFS so multiple ML jobs or EC2 instances can access it at once without duplicating files.</li></ul><h4>3. Home Directories or User Storage</h4><ul><li>If you’re building a SaaS product with per-user storage (like notebooks, docs, etc.), EFS makes it easy to create isolated or shared folders that scale automatically.</li></ul><h4>4. Backup &amp; Disaster Recovery</h4><ul><li>Because EFS is replicated across multiple AZs, it’s solid for critical backups or as a secondary mount point for failover.</li></ul><h4>5. Lift-and-Shift Legacy Apps</h4><ul><li>Apps that expect a POSIX-compliant file system (like old-school enterprise stuff) can often run without code changes using EFS.</li></ul><p><strong>What made EFS so special</strong></p><ul><li><strong>Fully managed:</strong> No need to manage file servers or worry about patching.</li><li><strong>Multi-AZ and HA:</strong> Automatically scales and survives AZ failures.</li><li><strong>Auto-scaling:</strong> Grows and shrinks with your usage — no need to pre-provision.</li><li><strong>Multi-client access:</strong> Multiple EC2s or pods can mount it at the same time.</li><li><strong>POSIX-compliant:</strong> Good old Linux file system style, works with existing tools.</li></ul><p><strong>What not EFS</strong></p><p>❌ Higher Latency<br>Compared to EBS or instance storage, EFS is slower. So not ideal for apps that need ultra-fast reads/writes or IOPS-heavy workloads.</p><p>❌ Cost Can Get Wild<br>It’s expensive if you’re not careful, especially if you don’t use the Infrequent Access (IA) tier properly.</p><p>❌ No Windows Support<br>EFS is Linux-only. If your app or workload is Windows-based, it’s a no-go.</p><p>❌ Mounting Complexity<br>You need to set up access points, security groups, and ensure your instances (or EKS pods) can talk to the file system. Not hard, but not plug-and-play either.</p><p>❌ Throughput Limits<br>The throughput is tied to your storage size unless you pay for provisioned throughput. Small file systems = slow speeds unless you cough up more money.</p><p><strong>Application which prefer EFS</strong></p><p>One of the key use cases of Amazon EFS (Elastic File System) is during model training, especially when the volume of training data is large. In such scenarios, we typically opt for distributed model training. To enable distributed training, there are two main approaches: distributed model training and distributed data processing. For distributed data, it is essential to use a shared storage solution that is accessible across multiple compute instances. Amazon EFS serves this purpose well by providing a scalable and shared file system, allowing each training instance to access and process data in parallel batches, thereby facilitating efficient model training.</p><p>Kubeflow is all about running machine learning workflows on Kubernetes — you got notebooks, pipelines, models, training jobs, the whole ML lifecycle. And guess what? A lot of that stuff needs to persist data between pods, across pipelines, and between services.</p><p>So… enter EFS. In AWS-land, EFS is often chosen for Kubeflow setups when:</p><p>You need shared volumes across pods (e.g. multiple notebooks accessing the same dataset)</p><p>You want persistence even if a pod or job dies and gets rescheduled</p><p>You need your data to survive across pipelines (preprocessing ➡️ training ➡️ inference)</p><p>✅ Advantages of EFS as a StorageClass in Kubeflow<br><strong>Shared Access</strong></p><p>Multiple users (like in JupyterHub) or multiple pods can access the same files concurrently. Perfect for team collab or multi-step pipelines.</p><p><strong>Durability &amp; HA</strong></p><p>EFS lives across multiple AZs. If one zone goes down, your files don’t poof into thin air.</p><p><strong>Dynamic Provisioning</strong></p><p>You can set up EFS CSI (Container Storage Interface) driver to dynamically provision PVCs on the fly using StorageClasses.</p><p><strong>POSIX Compatibility</strong></p><p>EFS acts like a real Linux file system. You can run regular CLI tools, save notebooks, read logs — all without app changes.</p><p><strong>Elastic Scaling</strong></p><p>No sizing headaches. Your storage scales up as your datasets grow, with zero manual resizing.</p><p><strong>Perfect for Notebooks</strong></p><p>Persistent, shared, and fast enough for loading/saving Jupyter notebooks? Check ✅</p><h3><strong>Lets see EKS cluster creation</strong></h3><p>I have used EKS terraform module to create a simple cluster where number of instance are limited as per my need . Please feel free to adjust based on your need .</p><p><a href="https://github.com/praveensamca/eks-efs.git">GitHub - praveensamca/eks-efs</a></p><p>This repository offers a Terraform-based solution to deploy a robust AWS infrastructure comprising:</p><p><strong>Amazon VPC</strong>: A customizable Virtual Private Cloud with defined CIDR blocks.</p><p><strong>Amazon EKS</strong>: A managed Kubernetes cluster with tailored node group configurations.</p><p><strong>Amazon EFS</strong>: A scalable, shared file system integrated with Kubernetes via the EFS CSI driver.</p><p>— — — —</p><p>### 1. Virtual Private Cloud (VPC)</p><p><strong>Custom CIDR Block: </strong>Define your own IP address range for the VPC.<br> Subnets: Creation of public and private subnets to segregate resources.<br><strong> Internet Gateway &amp; NAT Gateway:</strong> Facilitates internet access for public subnets and controlled outbound traffic for private subnets.<br><strong> Route Tables:</strong> Configured to manage traffic flow between subnets and gateways.</p><p>### 2. Elastic Kubernetes Service (EKS)</p><p><strong>Cluster Setup:</strong> Deployment of an EKS cluster with specified Kubernetes version.<br> <strong>Node Groups:</strong> Configuration of managed node groups with desired instance types and scaling policies.<br><strong> IAM Roles:</strong> Establishes necessary IAM roles and policies for EKS and worker nodes.<br> <strong>Security Groups: </strong>Defines security groups to control inbound and outbound traffic to the cluster.</p><p>### 3. Elastic File System (EFS)</p><p><strong>File System Creation:</strong> Provisioning of an EFS file system for shared storage needs.<br><strong> Mount Targets:</strong> Setup of mount targets in each availability zone for high availability.<br><strong> Security Groups:</strong> Configured to allow NFS traffic between EFS and EKS nodes.</p><p>### 4. Kubernetes Integration</p><p><strong>EFS CSI Driver:</strong> Deployment of the EFS Container Storage Interface driver to enable Kubernetes pods to use EFS.<br><strong> Persistent Volumes (PV) and Persistent Volume Claims (PVC):</strong> Definitions to allow pods to claim storage from EFS.<br> <strong>Storage Class:</strong> Custom storage class to manage dynamic provisioning of EFS volumes.</p><p>├── efs.tf # EFS file system and mount targets<br>├── eks.tf # EKS cluster and node group configurations<br>├── eks-addon.tf # Additional EKS components (The code has enabled EFS module )<br>├── irsa.tf # IAM Roles for Service Accounts (IRSA)<br>├── output.tf # Outputs for Terraform<br>├── pods-2.yaml # Sample pod deployment using EFS<br>├── pods.yml # Another sample pod deployment<br>├── pv.yaml # Persistent Volume definition<br>├── pvc.yml # Persistent Volume Claim definition<br>├── role.tf # IAM role definitions<br>├── sc.yaml # Storage Class for EFS<br>├── security.tf # Security group configurations<br>├── variable.tf # Variable declarations<br>├── variable.tfvars # Variable values<br>└── README.md # Project documentation</p><p>## 🚀 Deployment Steps</p><p>1. Clone the Repository</p><p>```bash<br> git clone <a href="https://github.com/praveensamca/eks-efs.git">https://github.com/praveensamca/eks-efs.git</a><br> cd eks-efs<br> ```</p><p>2. Initialize Terraform</p><p>```bash<br> terraform init<br> ```</p><p>3. Review and Modify Variables</p><p>Edit `variable.tfvars` to customize values like region, VPC CIDR, EKS cluster name, etc.</p><p>4. Apply Terraform Configuration</p><p>```bash<br> terraform apply -var-file=”variable.tfvars”<br> ```</p><p>## Update fs-* id from the output to kubernete volume file</p><p>5. Update kubeconfig</p><p>```bash<br> aws eks update-kubeconfig — name my-eks-cluster ( Change if needed on the variable.tfvars file ) <br> ```</p><p>6. Deploy EFS CSI Driver and Kubernetes Resources</p><p>```bash<br> kubectl apply -f sc.yaml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yv_tv5cxdKwO-sXoTXq7jA.png" /></figure><p>kubectl apply -f pv.yaml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zz50IluATHDdFNcy9JZKxQ.png" /></figure><p>kubectl apply -f pvc.yml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtwnY4odkRMg70tbmO_uiA.png" /></figure><p>kubectl apply -f pods.yml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmKfFskLzhcc2tirzXL1rA.png" /></figure><p>Created test file on EFS location</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yc4E5n8byTPGd-Pxoz3JYw.png" /></figure><p>Creating second pod pointing same EFS filesystem which first pod is using</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQ-ANiExFiWoKH-7C1uWVA.png" /></figure><p>Validating test file created from first pod</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dH7vi7t53lt0K_tDAJ2y1Q.png" /></figure><p>We can able to see new file created from first pod</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb254e59bf5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cut Your AWS Bill by scaling down Instance During Off-Hours]]></title>
            <link>https://medium.com/@praveensams16/cost-optimisation-using-off-hour-instance-downscale-73f2b44f060c?source=rss-a25371fc5cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/73f2b44f060c</guid>
            <category><![CDATA[aws-cost-optimization]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lambda-function]]></category>
            <dc:creator><![CDATA[Praveensam]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 03:10:55 GMT</pubDate>
            <atom:updated>2024-12-02T04:38:33.697Z</atom:updated>
            <content:encoded><![CDATA[<p>This document is going to explain AWS verical scale using lambda. The overall expection is scale down ec2 instance during off hour. I have used terraform to deploy the wholesetup including python module build</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1fHV5qT9CQpSaBgfyUGIA.png" /></figure><p>Repo: <a href="https://github.com/praveensamca/ec2_vertical_scale.git">https://github.com/praveensamca/ec2_vertical_scale.git</a></p><p>Component involved:</p><p>lambda<br> dynamoDB<br> eventbridge <br> python<br> terraform<br> <br>The provided Python script implements a class, infra, which interacts with AWS resources such as DynamoDB, EC2, and SNS, eventBridge and also performs HTTP requests for application health checks after the change. The script designed for managing cloud infrastructure dynamically, including instance scaling and monitoring.</p><p>The script filters instances based on tags, such as instance_type=nonprod. Once the list of instance id is retrieved, the script updates the instance types according to the schedule.</p><p>I have considered two time periods: <strong>morning</strong> and <strong>evening</strong>.</p><ul><li>In the <strong>morning</strong>, instances will be configured to run with the type m5.2xlarge.</li><li>In the <strong>evening</strong>, instances will be switched to m5.large.</li></ul><p>Additionally, the script includes functionality to validate the system using API calls. (Please ensure to include a wait time before running the validation, which can be adjusted based on your specific requirements.)</p><p>Inorder to prevent duplicate run , I have added the function to store the events on dynamodb, which also be reference for history of last run</p><pre>import requests<br>import json<br>import boto3 , time<br>from re import search<br>import re , os , sys<br>from datetime import datetime<br>from botocore.exceptions import NoCredentialsError, PartialCredentialsError<br><br>class infra:<br><br>    def __init__(self,id=&quot;None&quot;):<br>        self.id=id<br>        self.sns_client = boto3.client(&#39;sns&#39;,<br>                aws_access_key_id=os.getenv(&quot;access_key&quot;),<br>                aws_secret_access_key=os.getenv(&quot;secret_key&quot;),<br>                region_name=os.getenv(&quot;region&quot;))<br>        self.url = &quot;https://local/profile.php&quot;<br>        self.data = {<br>            &quot;user_token&quot;: &quot;url&quot;,<br>            &quot;editId&quot;: &quot;0&quot;<br>        }<br>        self.dynamodb_client = boto3.resource(&#39;dynamodb&#39;,<br>                aws_access_key_id=os.getenv(&quot;access_key&quot;),<br>                aws_secret_access_key=os.getenv(&quot;secret_key&quot;),<br>                region_name=os.getenv(&quot;region&quot;))<br>        self.s=boto3.client(&#39;ec2&#39;, <br>            aws_access_key_id=os.getenv(&quot;access_key&quot;),<br>            aws_secret_access_key=os.getenv(&quot;secret_key&quot;),<br>            region_name=os.getenv(&quot;region&quot;))  <br>        self.ec2=boto3.resource(&#39;ec2&#39;,<br>                aws_access_key_id=os.getenv(&quot;access_key&quot;),<br>                aws_secret_access_key=os.getenv(&quot;secret_key&quot;),<br>                region_name=os.getenv(&quot;region&quot;))<br><br>    def query_dynamodb(self,table_name, partition_key_name, partition_key_value, sort_key_name=None, sort_key_value=None):<br>        try:<br>            # Initialize the DynamoDB client<br>            <br>            table = self.dynamodb_client.Table(&quot;schedular&quot;)<br>            <br>            # Build query parameters<br>            query_params = {<br>                &quot;KeyConditionExpression&quot;: boto3.dynamodb.conditions.Key(partition_key_name).eq(partition_key_value)<br>            }<br>            <br>            # Add sort key condition if provided<br>            if sort_key_name and sort_key_value:<br>                query_params[&quot;KeyConditionExpression&quot;] &amp;= boto3.dynamodb.conditions.Key(sort_key_name).eq(sort_key_value)<br>            <br>            # Execute the query<br>            response = table.query(**query_params)<br>            return response[&#39;Items&#39;][0]<br><br>        except NoCredentialsError:<br>            print(&quot;AWS credentials not found. Please configure your credentials.&quot;)<br>        except PartialCredentialsError:<br>            print(&quot;Incomplete AWS credentials configuration.&quot;)<br>        except Exception as e:<br>            print(f&quot;An error occurred: {e}&quot;)<br><br>    def stop(self):<br>        self.s.stop_instances(InstanceIds=[self.id])<br><br>    def start(self):<br>        self.s.start_instances(InstanceIds=[self.id])<br><br>    def state(self):<br>        for i in self.s.describe_instances()[&#39;Reservations&#39;]:<br>            for j in i[&#39;Instances&#39;]:<br>                if j[&#39;InstanceId&#39;] == self.id:<br>                    return j[&#39;State&#39;][&#39;Name&#39;]<br><br>    def send_email_sns(self,topic_arn, subject, message):<br>        try:<br>            response_sms = self.sns_client.publish(<br>                TopicArn=topic_arn,<br>                Subject=subject,<br>                Message=message<br>            )<br>        except Exception as e:<br>            print(&quot;Error sending email:&quot;, str(e))<br>    <br>    def update_table(self,item):<br>        table = self.dynamodb_client.Table(&quot;schedular&quot;)<br>        now = datetime.now()<br>        if now.hour &lt;= 12:<br>            topic_arn = os.getenv(&quot;topic_arn&quot;)<br>            subject = &quot;Starting instance on m5.2xlarge&quot;<br>            message = &quot;Starting instance on m5.2xlarge , Please check the url once&quot;<br>            self.scale(topic_arn, subject, message,os.getenv(&quot;regular_size&quot;))<br>            response = table.put_item(Item=item)<br>        elif now.hour &gt; 12 and now.hour &lt;24:<br>            topic_arn = os.getenv(&quot;topic_arn&quot;)<br>            subject = &quot;Starting instance on m5.large&quot;<br>            message = &quot;Starting instance on m5.large , Please check the url once&quot;<br>            self.scale(topic_arn, subject, message,os.getenv(&quot;down_size&quot;))<br>            response = table.put_item(Item=item)<br><br>    def write_dynamo(self,status):<br>        global timeofday , morning , evening<br>        now = datetime.now()<br>        if now.hour &lt; 12:<br>            timeofday=&quot;morning&quot;<br>        else:<br>            timeofday=&quot;evening&quot;<br>        item = {<br>            &quot;status&quot;: status, <br>            &quot;year&quot;: now.year,<br>            &quot;month&quot;: now.month,<br>            &quot;day&quot;: now.day,<br>            &quot;hour&quot;: now.hour,<br>            &quot;minute&quot;: now.minute,<br>            &quot;timeofday&quot;: timeofday<br>            }<br>        table = self.dynamodb_client.Table(&quot;schedular&quot;)<br>        print(&quot;Entering service&quot;)<br>        response = table.scan()  # Scan retrieves all items in the table<br>        items = response.get(&#39;Items&#39;, [])<br>        try:<br>            if now.hour &lt;= 12:<br>                morning=self.query_dynamodb(&quot;schedular&quot;,&quot;timeofday&quot;,&quot;morning&quot;)<br>                if morning[&quot;day&quot;] == now.day and morning[&quot;month&quot;] == now.month:<br>                    print(&quot;morning&quot;,morning)<br>                    print(&quot;Already morning exists&quot;)<br>                    return<br>                else:<br>                    self.update_table(item)<br>            elif now.hour &gt; 12 and now.hour &lt;24:<br>                evening=self.query_dynamodb(&quot;schedular&quot;,&quot;timeofday&quot;,&quot;evening&quot;)<br>                if evening[&quot;day&quot;] == now.day and evening[&quot;month&quot;] == now.month:<br>                    print(evening[&quot;day&quot;] , now.day)<br>                    print(&quot;evening&quot;,evening)<br>                    print(&quot;Evening already exists&quot;)<br>                    return<br>                else:<br>                    self.update_table(item)<br>            else:<br>                print(&quot;Updating table&quot;)<br>                self.update_table(item)<br><br>        except Exception as e:<br>            print(f&quot;Error reading from DynamoDB {e}&quot;)<br>            self.update_table(item)<br><br>    def scale(self,topic_arn, subject, message,size):<br>        while True:<br>            if search(r&quot;stopping&quot; ,self.state() , re.I):<br>                print(&quot;Stopping&quot;)<br>            elif search(r&quot;running&quot; ,self.state() , re.I):<br>                print(&quot;Instance is running&quot;)<br>                self.stop()<br>            elif search(r&quot;stopped&quot; ,self.state() , re.I):<br>                print(f&quot;Instance is stopped , starting now with new instance type f{size}&quot;)<br>                self.s.modify_instance_attribute(InstanceId=self.id, Attribute=&#39;instanceType&#39;, Value=size)<br>                self.start()<br>                self.send_email_sns(topic_arn, subject, message)<br>                time.sleep(5)<br>                while not search(r&quot;running&quot; ,self.state() , re.I):<br>                    print(&quot;Status :&quot;,self.state())<br>                break<br><br>    def filter_instance(self):<br>        instance_list=[]<br>        filters = [<br>            {<br>                &#39;Name&#39;: &#39;tag:instance_type&#39;, <br>                &#39;Values&#39;: [&#39;duplicate&#39;]<br>            }<br>        ]<br>        instances = self.ec2.instances.filter(Filters=filters)<br>        for i in instances:<br>            instance_list.append(i.id)<br>        return instance_list<br><br>    def validate(self):<br>        print(&quot;inside&quot;)<br>        print(os.getenv(&quot;size&quot;))<br>        try:<br>            print(&quot;Inside try&quot;)<br>            print(requests.post(self.url, json=self.data))<br>            response = requests.post(self.url, json=self.data)<br>            print(response)<br>            # Check if the request was successful<br>            if response.status_code == 200:<br>                s=json.loads(response.text)<br>                if s[&quot;status_code&quot;] == 200:<br>                    topic_arn = os.getenv(&quot;topic_arn&quot;)<br>                    subject = &quot;Aplication is up&quot;<br>                    message = f&quot;Applicaiton is up {response.text}&quot;<br>                    self.send_email_sns(topic_arn, subject, message)<br>                else:<br>                    topic_arn = os.getenv(&quot;topic_arn&quot;)<br>                    subject = &quot;Aplication is down&quot;<br>                    message = f&quot;Applicaiton is down {response.text}&quot;<br>                    self.send_email_sns(topic_arn, subject, message)<br>            else:<br>                print(f&quot;Failed with status code: {response.status_code}&quot;)<br>                print(&quot;Response:&quot;, response.text)<br>                topic_arn = os.getenv(&quot;topic_arn&quot;)<br>                subject = &quot;Aplication is down&quot;<br>                message = f&quot;Applicaiton is down {response.text}&quot;<br>                self.send_email_sns(topic_arn, subject, message)<br><br>        except Exception as e:<br>            print(&quot;An error occurred:&quot;, str(e))<br><br>        s=json.loads(response.text)<br>        if s[&quot;status_code&quot;] == 200:<br>            topic_arn = os.getenv(&quot;topic_arn&quot;)<br>            subject = &quot;Aplication is up&quot;<br>            message = f&quot;Applicaiton is up {response.text}&quot;<br>            self.send_email_sns(topic_arn, subject, message)<br>            return (&quot;Application load successfully&quot;)<br>        else:<br>            topic_arn = os.getenv(&quot;topic_arn&quot;)<br>            subject = &quot;Aplication is down&quot;<br>            message = f&quot;Applicaiton is down {response.text}&quot;<br>            self.send_email_sns(topic_arn, subject, message)<br>            return (&quot;Application load failure&quot;)<br><br><br><br>def lambda_handler(event, context):<br>    j=infra()<br>    for j in j.filter_instance():<br>        date=datetime.now()<br>        i=infra(j)<br>        i.write_dynamo(date)<br>        i.validate()</pre><h3>Class Initialization (__init__ method)</h3><p>The infra class constructor initializes:</p><ul><li>AWS clients for <strong>SNS</strong>, <strong>DynamoDB</strong>, <strong>EC2</strong>, using credentials and region information from environment variables.</li><li>A default URL and data payload for HTTP requests.</li></ul><h3>Querying DynamoDB (query_dynamodb method)</h3><ul><li>Queries the schedular table in DynamoDB using a partition key (and optionally a sort key).</li><li>Returns the first matching item or handles errors related to credentials or other issues.</li></ul><h3>EC2 Instance Management</h3><ul><li><strong>stop(self)</strong>: Stops an EC2 instance with the specified id.</li><li><strong>start(self)</strong>: Starts an EC2 instance with the specified id.</li><li><strong>state(self)</strong>: Checks and returns the current state (running, stopped, etc.) of the specified EC2 instance.</li></ul><h3>Sending Notifications via SNS (send_email_sns method)</h3><ul><li>Publishes a message to an SNS topic with a subject and message.</li><li>Handles any exceptions during the publish operation.</li></ul><p>Note: SNS is prerequisite , please create and add it in the terraform variable file</p><h3>DynamoDB Table Updates</h3><p><strong>update_table(self, item)</strong>:</p><ul><li>Inserts or updates an item in the schedular table.</li><li>Sends notifications with varying instance types (m5.2xlarge or m5.large) depending on the time of day.</li></ul><p><strong>write_dynamo(self, status)</strong>:</p><ul><li>Determines the time of day (morning or evening) and checks if records for the current day and time exist in the schedular table.</li><li>Calls update_table if no records exist or logs appropriate messages otherwise.</li></ul><h3>Scaling Instances (scale method)</h3><ul><li>Adjusts the EC2 instance type based on provided parameters:</li><li>Stops a running instance.</li><li>Modifies the instance type.</li><li>Restarts the instance and verifies it reaches the running state.</li><li>Sends an SNS notification about the operation.</li></ul><p>The function gets instance ID based on the filter match comes from the python function filter_instance</p><h3>Lambda Handler</h3><p>The lambda_handler function:</p><ul><li>Creates an infra object.</li><li>Filters EC2 instances based on tags.</li><li>For each filtered instance:</li><li>Writes DynamoDB logs with the status “started.”</li><li>Validates the application.</li></ul><p><strong>Lambda Deployment</strong></p><p>I have used Terraform to provision a complete AWS infrastructure for a serverless scheduling service using AWS Lambda, EventBridge, DynamoDB, and other services. I would like to highlight a grey area that needs explanation.</p><p>The Lambda script requires the requests Python module to validate the application endpoint. Therefore, the module needs to be created and added as part of a Lambda layer.</p><pre><br>pip3.13 install requests -t python/lib/python3.9/site-packages/</pre><p>If you dont have python 3.13 , then try to do install either using python venv or local compile</p><pre><br>cd /usr/local/src <br><br>wget -c https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tar.gz ( for linux )<br><br>tar -zxvf Python-3.13.0.tar.gz<br><br>cd Python-3.13.0<br><br>./configure --prefix=/usr/local/src/python<br><br>make <br><br>make install<br><br><br># Make sure you have GCC and related compiler package ( it takes 10 - 15 mins ) , based on resource</pre><p>Once after the compilation , run pip command to compile the module . I have coverd steps to archive and upload them to lambda layer</p><pre>resource &quot;aws_lambda_layer_version&quot; &quot;lambda_layer&quot; {<br>  filename   = &quot;requests.zip&quot;<br>  layer_name = &quot;requests&quot;<br>  compatible_runtimes = [&quot;python3.13&quot;]<br>}</pre><p>Defines two EventBridge rules triggering at specific times:</p><ul><li>Morning: cron(0 3 ? * MON-SAT *).</li><li>Evening: cron(0 15 ? * MON-SAT *).</li></ul><h3>Potential Use Cases</h3><ol><li><strong>Cloud Infrastructure Automation</strong>: Automatically manage AWS EC2 instances based on real-time requirements.</li><li><strong>Cost Optimization</strong>: Dynamically adjust instance types for cost efficiency.</li></ol><h3>Suggestions for Improvement</h3><ul><li><strong>Error Handling</strong>: Improve exception handling for edge cases (e.g., connection issues with AWS or HTTP errors).</li><li><strong>Environment Variables</strong>: Securely manage AWS credentials and other sensitive information using services like AWS Secrets Manager.</li><li><strong>Logging</strong>: Add structured logs for better monitoring and debugging.</li><li><strong>Code Optimization</strong>: Modularize repeated operations (e.g., SNS notification sending logic)</li><li><strong>IAM Role:</strong> Have to use aws role instead of keys</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73f2b44f060c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating MongoDB Backups to AWS S3 with Python and Boto3]]></title>
            <link>https://medium.com/@praveensams16/automating-mongodb-backups-to-aws-s3-with-python-and-boto3-718bfa78c9e7?source=rss-a25371fc5cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/718bfa78c9e7</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[mongodb-backup]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Praveensam]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 09:31:20 GMT</pubDate>
            <atom:updated>2024-10-27T09:31:20.007Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s world of fast-paced development and constantly growing data, reliable backup automation is essential. If you’re running MongoDB databases, frequent backups provide a safety net, enabling data restoration in case of unexpected issues. This article walks through a Python solution using boto3 that automates MongoDB dumps to AWS S3 while implementing a retention policy to delete backups older than two days.</p><h3>Why Automate Backups?</h3><p>Manual database backups are error-prone and time-consuming. By automating this process, you not only save time but also ensure consistent backups. AWS S3 offers secure and scalable storage, making it an ideal destination for backups. In addition, using S3 with Python’s boto3 library enables a seamless interface to handle uploads, deletions, and other S3 management tasks programmatically.</p><h3>Key Objectives of the Script</h3><p>This Python script performs three essential tasks:</p><ol><li><strong>Creating a MongoDB Dump</strong>: It generates a dump of the MongoDB database, which can later be restored in case of failure.</li><li><strong>Uploading to S3</strong>: After the dump is generated, the script uploads it to a specified AWS S3 bucket, allowing secure storage and access.</li><li><strong>Applying Retention Policy</strong>: To manage storage effectively, the script checks for backups older than two days and deletes them from S3, ensuring that storage costs remain low.</li></ol><h4>Install Dependencies</h4><ol><li>Python boto3</li><li>Mongodb Client</li></ol><h3>The Script</h3><p>Here’s a breakdown of the script’s main sections.</p><pre>import os<br>import shutil<br>import subprocess<br>import boto3<br>import datetime<br>import tempfile<br>import time<br>from datetime import datetime, timedelta, timezone<br><br>date=time.strftime(&#39;%l-%M%p-%b-%d-%Y&#39;)<br><br># MongoDB and AWS S3 configuration<br>MONGO_DB = &quot;service&quot;  # Replace with your database name<br>S3_BUCKET = &quot;service-backup&quot;  # Replace with your bucket name<br>S3_PATH = f&quot;service/{date}&quot;  # S3 folder path where you want to store backups<br><br># AWS S3 credentials<br>AWS_ACCESS_KEY = &quot;XXXXXXX&quot;<br>AWS_SECRET_KEY = &quot;XXX&quot;<br>AWS_REGION = &quot;ap-south-1&quot;<br><br># MongoDB and AWS S3 configuration<br><br>retention=2 #days<br><br># Create an S3 client<br>s3_client = boto3.client(<br>    &quot;s3&quot;,<br>    aws_access_key_id=AWS_ACCESS_KEY,<br>    aws_secret_access_key=AWS_SECRET_KEY,<br>    region_name=AWS_REGION,<br>)<br><br>def create_mongo_dump():<br>    &quot;&quot;&quot;Create MongoDB dump with authentication and return the dump file path.&quot;&quot;&quot;<br>    timestamp = datetime.now().strftime(&quot;%Y-%m-%d_%H-%M-%S&quot;)<br>    dump_path = os.path.join(tempfile.gettempdir(), f&quot;mongo_dump_{timestamp}.tar.gz&quot;)<br>    if os.path.exists(&quot;/home/ubuntu/dump&quot;):<br>        print(&quot;Removing existing dump folder&quot;)<br>        os.remove(dump_file)<br><br><br>    # Run mongodump command with authentication and compress the output<br>    try:<br>        subprocess.check_call([<br>            &quot;mongodump&quot;, &quot;--db=mlservice&quot;<br>        ])<br>        subprocess.check_call([&quot;tar&quot;,&quot;-zcvf&quot;,dump_path,&quot;dump&quot;])<br>        print(f&quot;MongoDB dump created at {dump_path}&quot;)<br>        return dump_path<br>    except subprocess.CalledProcessError as e:<br>        print(f&quot;Error creating MongoDB dump: {e}&quot;)<br>        return None<br><br>def upload_to_s3(file_path):<br>    &quot;&quot;&quot;Upload a file to S3.&quot;&quot;&quot;<br>    s3_file_name = os.path.join(S3_PATH, os.path.basename(file_path))<br>    try:<br>        s3_client.upload_file(file_path, S3_BUCKET, s3_file_name)<br>        print(f&quot;File uploaded to S3: s3://{S3_BUCKET}/{s3_file_name}&quot;)<br>    except Exception as e:<br>        print(f&quot;Error uploading file to S3: {e}&quot;)<br><br>def get_all_folders(bucket_name, prefix=&quot;&quot;,retention=5):<br>    &quot;&quot;&quot;Get a list of folders in an S3 bucket.&quot;&quot;&quot;<br>    folders = []<br>    response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=&#39;service/&#39;)<br>    cutoff_date = datetime.now(timezone.utc) - timedelta(days=retention)<br>    for i in response[&#39;Contents&#39;]:<br>        if ( i[&#39;LastModified&#39;] &lt; cutoff_date ):<br>            print(i[&#39;Key&#39;])<br>            folders.append(i[&#39;Key&#39;])<br>    return folders<br><br>def delete_folder(bucket_name,list_files, prefix=&quot;&quot;):<br>    response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=&#39;service/&#39;)<br>    for i in list_files:<br>        response = s3_client.delete_object(Bucket=bucket_name, Key=f&quot;{i}&quot;)<br>        print(response)<br><br><br>def main():<br>    dump_file = create_mongo_dump()<br>    if dump_file:<br>        upload_to_s3(dump_file)<br>        shutil.rmtree(&quot;/home/ubuntu/dump&quot;)<br>        os.remove(dump_file)<br>        list_files=get_all_folders(S3_BUCKET,retention=retention,prefix=&quot;&quot;)<br>        if len(list_files) &gt; 0:<br>            delete_folder(S3_BUCKET,list_files,prefix=&quot;&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()<br><br></pre><h3>Script Walkthrough</h3><ol><li><strong>Create MongoDB Dump</strong>: The create_mongodb_dump function generates a compressed MongoDB dump with a timestamp in its filename. This helps in identifying each backup uniquely and makes retrieval easier.</li><li><strong>Upload to S3</strong>: The upload_to_s3 function uploads the MongoDB dump file to the specified S3 bucket.</li><li><strong>Delete Old Backups</strong>: The delete_old_backups function applies a retention policy by identifying and deleting any backup older than the specified retention period (two days in this case).</li><li><strong>Cleanup</strong>: After the S3 upload, the local dump file is removed to save space on the server.</li></ol><h3>Running the Script</h3><p>Once the script is configured, you can schedule it to run periodically using a cron job or any other scheduler. For example, to schedule the script to run daily at midnight, add the following entry to your crontab:</p><p>0 0 * * * /usr/bin/python3 /path/to/your_script.py</p><h3>Benefits of This Approach</h3><ol><li><strong>Automation Saves Time</strong>: Once configured, this script autonomously handles the entire backup lifecycle.</li><li><strong>Cost-Effective</strong>: By regularly deleting old backups, the script helps manage S3 storage costs.</li><li><strong>Reliability</strong>: Consistent backups give peace of mind, ensuring that data can be restored even in unexpected situations.</li></ol><h3>Final Thoughts</h3><p>Automating MongoDB backups with Python and boto3 simplifies data protection while keeping storage usage in check. This solution ensures that backups are performed on time, are securely stored in S3, and adhere to a retention policy that suits your storage budget. With minimal setup, you can adapt and expand this solution to suit different backup needs across various environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=718bfa78c9e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSL Expiry alert ( prometheus | custom exporter )]]></title>
            <link>https://medium.com/@praveensams16/ssl-expirey-alert-prometheus-custom-exporter-2bed712900cc?source=rss-a25371fc5cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bed712900cc</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[alerts]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Praveensam]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 19:55:04 GMT</pubDate>
            <atom:updated>2023-02-06T17:33:14.309Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>SSL Expiry alert ( prometheus | custom exporter )</strong></p><p><strong>Why do we need ssl alert</strong></p><p>Valid SSL is needed to enable proper communication between the server and the consumer. Expired SSL distrupt customer connectivity. So an alert prior to expire prevent service disturbtion.</p><p><em>Note: We do have alternative tools in the market ( Blackbox exporter , pingdom etc) . This is an attempt to create a custom alert service where we have added additional functionalities</em></p><p>How the SSL alert work</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*kLEKxybNG4Bm05Tp-b9H2w.jpeg" /></figure><p><strong>Exporter</strong></p><p>Exporter is a service deployed in k8s which connect the endpoint and fetch the details of expirey date and gives number of days left . In the below object web_ssl you can find the details of conenctivity and certificate status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owptgJa5UsHf7qwEgMslLg.png" /><figcaption>Output on response</figcaption></figure><p>Below is the script to fetch and verify the SSL certs annotations , number of days to validate should be passed under the variable days in value.yaml. Its upto you choose the language based on our convenient . Here I used go due to its concurrency nature.</p><pre>package main<br><br>import (<br> &quot;crypto/tls&quot;<br> &quot;fmt&quot;<br> &quot;io/ioutil&quot;<br> &quot;net/http&quot;<br> &quot;strings&quot;<br> &quot;sync&quot;<br> &quot;time&quot;<br> &quot;os&quot;<br> &quot;strconv&quot;<br>)<br><br>type (<br> result struct {<br>  url_s, url   string<br>  days         int<br>  valid        bool<br>  reachability bool<br> }<br><br> stats struct {<br>  c     chan result<br>  count int<br> }<br>)<br><br>var (<br> wg sync.WaitGroup<br>)<br><br>func url_validator(url string) bool {<br> client := &amp;http.Client{Timeout: 10 * time.Second}<br> _, err := client.Get(&quot;https://&quot; + url)<br><br> if err == nil {<br><br>  return true<br> } else {<br>  return false<br> }<br><br> return true<br>}<br><br>func (s *stats) getdate(url string) {<br> defer wg.Done()<br><br> conf := &amp;tls.Config{<br>  InsecureSkipVerify: true,<br> }<br><br> url_f := fmt.Sprintf(&quot;%s:443&quot;, (url))<br><br> conn, err := tls.Dial(&quot;tcp&quot;, url_f, conf)<br> if err != nil {<br>  wg.Done()<br>  //goto SAM<br>  println(&quot;errorss&quot;)<br> }<br><br> defer conn.Close()<br> certs := conn.ConnectionState().PeerCertificates<br> cert := certs[0]<br> currentTime := time.Now()<br><br> d1, _ := time.Parse(&quot;2006-01-02 &quot;, cert.NotAfter.Format(&quot;2006-01-02&quot;))<br> d2, _ := time.Parse(&quot;2006-01-02 &quot;, currentTime.Format(&quot;2006-01-02&quot;))<br> val,_ := strconv.Atoi(os.Getenv(&quot;days&quot;))<br> if int(d1.Sub(d2).Hours()/24) &gt; val {<br>  s.c &lt;- result{url: url, url_s: &quot;Enough days&quot;, days: int(d1.Sub(d2).Hours() / 24), valid: true, reachability: true}<br>  s.count = s.count + 1<br> } else {<br>  s.c &lt;- result{url: url, url_s: &quot;Enough days&quot;, days: int(d1.Sub(d2).Hours() / 24), valid: false, reachability: true}<br>  s.count = s.count + 1<br> }<br> // }<br><br>}<br><br>func results(w http.ResponseWriter, req *http.Request) {<br><br> s := &amp;stats{c: make(chan result, 1000)}<br> files, _ := ioutil.ReadFile(&quot;/mnt/url.txt&quot;)<br> lists := strings.Split(string(files), &quot;\n&quot;)<br> for _, i := range lists {<br>  if len(i) &gt; 0 {<br>  if url_validator(i) {<br>   wg.Add(1)<br>   go s.getdate(i)<br><br>  } else {<br>   prt := fmt.Sprintf(&quot;unifonic_ssl{url=%s,days=%d,valid=%s,reachability=%s,reason=%s} = 0\n&quot;, i, 0, &quot;false&quot;, &quot;false&quot;, &quot;Unable to reach the url&quot;)<br>   fmt.Fprintf(w, prt)<br>   println(&quot;run&quot;, i)<br>  }<br>      }<br> }<br> wg.Wait()<br> for i := 0; i &lt; s.count; i++ {<br>  select {<br>  case d := &lt;-s.c:<br>   if d.valid &amp;&amp; d.reachability {<br>    prt := fmt.Sprintf(&quot;unifonic_ssl{url=%s,days=%d,valid=%t,reachability=%t,reason=\&quot;\&quot;} = 1\n&quot;, d.url, d.days, d.valid, d.reachability)<br>    fmt.Fprintf(w, prt)<br>   } else {<br><br>    prt := fmt.Sprintf(&quot;unifonic_ssl{url=%s,days=%d,valid=%t,reachability=%t,reason=\&quot;About to expire\&quot;} = 0\n&quot;, d.url, d.days, d.valid, d.reachability)<br>    fmt.Fprintf(w, prt)<br>   }<br>  }<br> }<br><br>}<br><br>func main() {<br><br> http.HandleFunc(&quot;/metrics&quot;, results)<br><br> http.ListenAndServe(&quot;:8090&quot;, nil)<br>}</pre><p><a href="https://github.com/praveensams16/ssl_alert.git">GitHub - praveensams16/ssl_alert</a></p><p>I have created the above script to run in helm chart , to deploy the code please use below command</p><pre>cd sslalert<br>helm install sam .<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sC4HqB9CV9wZotbasSqfFA.png" /></figure><p>Url to be monitord are configured under value.yaml</p><p>url:<br> — “<a href="http://www.google.com/">www.google.com</a>&quot;<br> — “<a href="http://www.yahoo.com/">www.yahoo.com</a>&quot;<br> — “<a href="http://www.testing.com/">www.testing.com</a>&quot;<br> — “<a href="http://www.dskjfflfjggl.com/">www.dskjfflfjggl.com</a>&quot;</p><p><strong>Output:<br></strong>Output from the service will be on below format , which explains url reachability , reason for connectivity failure and followed by number of days left to expire.</p><pre>web_ssl{url=www.dskjfflfjggl.com,days=0,valid=false,reachability=false,reason=Unable to reach the url} = 0<br>web_ssl{url=www.google.com,days=56,valid=true,reachability=true,reason=&quot;&quot;} = 1<br>web_ssl{url=www.yahoo.com,days=114,valid=true,reachability=true,reason=&quot;&quot;} = 1<br>web_ssl{url=www.testing.com,days=44,valid=false,reachability=true,reason=&quot;About to expire&quot;} = 0</pre><p><strong>Prometheus scrape</strong></p><ul><li>job_name: ssl<br> scrape_interval: 10s<br> scrape_timeout: 9s<br> metrics_path: /metrics<br> honor_labels: true<br> static_configs:<br> — targets:<br> — sam-sslalert.default:8090</li></ul><p>Add above conf on the prometheus configuration and followed by the alert</p><pre>      - name: SSL alert<br>        rules:<br>        - alert: ssl_alert<br>          expr: web_ssl{} = 0<br>          labels:<br>            severity: P2<br>            team: testing<br>          annotations:<br>            description: &#39;SSL Expirey alert&#39;</pre><p>Make sure you have channelised the alert to the correct reponder</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bed712900cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrive Kuberneted Pod status using Slack chat]]></title>
            <link>https://medium.com/@praveensams16/retrive-kuberneted-pod-status-using-slack-chat-d42ee6e749f9?source=rss-a25371fc5cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d42ee6e749f9</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[slackbot]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Praveensam]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 19:25:10 GMT</pubDate>
            <atom:updated>2023-01-08T19:27:09.753Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Retrive Kubernetes Pod status using Slack chat</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKr7v2pqiyaG0BiwNHMZDQ.png" /></figure><p>This document is about how we can using slack chat service to manage kubernete resource , I am going toshow an example of how to retrive pod status using a simple chat message</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*f3_xm2hTlFw5jPkDn6laVw.jpeg" /></figure><p>We going to use two simple service to handle the complete setup. One is , a service to get status of pod and exposing it through a API in service level and another a chat bot which runs in socket mode</p><p>Repo: <a href="https://github.com/praveensams16/chatbot">https://github.com/praveensams16/chatbot</a></p><p><strong>Pod status monitor</strong></p><p>First lets see about pod status monitor works</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;os/exec&quot;<br> &quot;regexp&quot;<br> &quot;strings&quot;<br>)<br><br>var (<br> files []string<br> //lines []string<br>)<br><br>func run(w http.ResponseWriter, r *http.Request) {<br><br> cmd := exec.Command(&quot;kubectl&quot;, &quot;get&quot;, &quot;pods&quot;)<br> stdout, err := cmd.Output()<br><br> if err != nil {<br>  fmt.Println(err.Error())<br>  return<br> }<br><br> s := string(stdout)<br><br> files := strings.Split(string(s), &quot;\n&quot;)<br><br> for i := 0; i &lt; len(files); i++ {<br>  if !strings.Contains(files[i], &quot;NAME&quot;) &amp;&amp; len(files[i]) &gt; 1 &amp;&amp; !strings.Contains(files[i], &quot;Completed&quot;) {<br><br>   lines := regexp.MustCompile(&quot;[^\\s]+&quot;)<br><br>   status := lines.FindAllString(files[i], -1)<br><br>   if status[2] == &quot;Running&quot; {<br>    fmt.Fprintf(w, &quot;pod=\&quot;&quot;+status[0]+&quot;\&quot; -&gt; status=\&quot;Running\&quot; -&gt;&quot; +  &quot;  ready=&quot; + status[1]  + &quot;  -&gt;  restart=&quot; + status[3]+  &quot;\n&quot;)<br>   } else {<br>    fmt.Fprintf(w, &quot;pod=\&quot;&quot;+status[0]+&quot;\&quot; -&gt; status=&quot; +status[2] +&quot;  ready=&quot; + status[1]  + &quot;  -&gt;  restart=&quot; + status[3]+ &quot; \n&quot;)<br>   }<br>  }<br> }<br><br>}<br><br>func handleRequests() {<br> http.HandleFunc(&quot;/metrics&quot;, run)<br> log.Fatal(http.ListenAndServe(&quot;:9101&quot;, nil))<br>}<br><br>func main() {<br> handleRequests()<br>}</pre><p>I am using go http api handler to expose the metrics through api , I chosen go to handle long queue in the future. I have used direct kubectl binary to run on the namespace , but it is upto you to decide the language on your convenient as long as it satisfy the need</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYK7SnhXRbs46-AvpNPfYg.png" /></figure><p>Repo: <a href="https://github.com/praveensams16/chatbot/tree/main/charts/pod-status">https://github.com/praveensams16/chatbot/tree/main/charts/pod-status</a></p><p>To make the monitor pod to query the pod status on the namespace , it has to attach with expected role</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  name: role-pod<br>rules:<br>- apiGroups: [&quot;*&quot;] # &quot;&quot; indicates the core API group<br>  resources: [&quot;pods&quot;,&quot;deployment&quot;]<br>  verbs: [&quot;get&quot;, &quot;watch&quot;, &quot;list&quot;]</pre><p>Here I have restricted with only list and get . Add other needed fuctionality like restart or delete when you plan to expand its capability.</p><p><strong>Slack Bot</strong></p><p>The bot is the controller for all the chat we recieve in the channel . I have used bolt api and running on socket mode , So I dont have to expose the endpoint</p><p><strong>Channel</strong></p><p>First and foremost is the permission on the channel , We should have admin permission to the channel to deploy our bot .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljQSLyGTxWSzyKwTHZcm9Q.png" /></figure><p>Next steps is to create and add app to our slack account ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6i61nLp0RpqSc55w1TMS8g.png" /></figure><p>I followed the developer guidence to create new app , steps are very stright forward</p><p><a href="https://slack.dev/bolt-python/tutorial/getting-started">Slack | Bolt for Python</a></p><p>One thing not mentions in the document is adding permission to events subscription, which is very important for the bot to read the message</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdasoCgtyWnbK2VRCATVQA.png" /></figure><p>The outcome of the steps give two to token SLACK_APP_TOKEN. SLACK_BOT_TOKEN , make sure you copied both in some where</p><p>Please make sure you added both in the value file</p><p><a href="https://github.com/praveensams16/chatbot/blob/main/charts/kubernetes-bot/values.yaml">chatbot/values.yaml at main · praveensams16/chatbot</a></p><p>creds:<br> SLACK_APP_TOKEN: <br> SLACK_BOT_TOKEN:</p><pre>import os , requests<br>from re import search as find<br>from slack_bolt import App<br>from slack_bolt.adapter.socket_mode import SocketModeHandler<br><br># Initializes your app with your bot token and socket mode handler<br>app = App(token=os.environ.get(&quot;SLACK_BOT_TOKEN&quot;))<br><br><br>@app.message(&quot;.&quot;)<br>def message_hello(message, say):<br>    # say() sends a message to the channel where the event was triggered<br>    say(f&quot;Hey there &lt;@{message[&#39;user&#39;]}&gt;!&quot; )<br>    namespace=[&#39;praveen&#39;,&#39;testing&#39;]<br>    if find(&quot;namespace|name.*space|pods&quot;,message[&#39;text&#39;]):<br>        result=find(&quot;namespace\s(.*)&quot;,message[&#39;text&#39;])<br>        if result.group(1)  in namespace:<br>            say(f&quot;Requested namespace:   { result.group(1) }&quot;)<br>            url=&#39;http://pod-monitor.&#39; + result.group(1) + &#39;/metrics&#39;<br>            say(url)<br>            response = requests.get(url)<br>            say(&quot;Pod Status \n################################\n&quot;)<br>            for i in str(response.content).split(&quot;\\n&quot;):<br>                say(f&quot;{i}&quot;)<br>        else:<br>            say(&quot;Namespace not available&quot;)<br>    else:<br>        say(&quot;&quot;&quot;To proceed with service please mention namespace in the message ,<br>        Example<br>         namespace testing &quot;&quot;&quot;)<br><br># Start your app<br>if __name__ == &quot;__main__&quot;:<br>    SocketModeHandler(app, os.environ[&quot;SLACK_APP_TOKEN&quot;]).start()</pre><p>The above is sample script which read the message in the channel and trigger pod-monitor api and response of the channel will be sent back to channel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytR5z-ZhmD4SU97sN37g5A.png" /></figure><p>You can easily change your logic based on your need</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d42ee6e749f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notifying Pod Status to Slack Channel]]></title>
            <link>https://medium.com/@praveensams16/notifying-pod-status-to-slack-channel-50e5b03ae2eb?source=rss-a25371fc5cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/50e5b03ae2eb</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[slac]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Praveensam]]></dc:creator>
            <pubDate>Sat, 06 Aug 2022 19:28:03 GMT</pubDate>
            <atom:updated>2022-08-06T19:29:49.487Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Notifying Pod Status to Slack Channel using script</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ysaR_JMm-vy7B2R28C5dQ.png" /></figure><p>This post is for some one who want their namespace component to be monitored and notified when the status of the pod is unhealthy through a slack channel . The script is deployed as a cronjob, configurable based on your convenient schedule( cronjob ).</p><p>Example , on below namespace we see some of them are not in the running state , so when we deploy pod status monitor , it checks the status of each pods and notify it over the slack channel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etEfCFElvSFqtdYoOCX3Ww.png" /></figure><p>Below is sample post made by the script and post only if there are any faulty pod</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-_MimIaQLuuDPITitUlIw.png" /></figure><p>Repo URL</p><p><a href="https://github.com/praveensams16/pod-status-monitor.git">GitHub - praveensams16/pod-status-monitor</a></p><pre>package main</pre><pre>import (<br>    _ &quot;io/ioutil&quot;<br>     &quot;log&quot;<br>     &quot;os/exec&quot;<br>     &quot;regexp&quot;<br>     &quot;strings&quot;<br>     &quot;os&quot;<br>     &quot;fmt&quot;<br>    )</pre><pre>func validate() bool {<br>     s := exec.Command(&quot;kubectl&quot;,&quot;get&quot;,&quot;pods&quot;)<br>     x:=0<br>     sw, _ := s.Output()<br>     lst := strings.Split(string(sw), &quot;\n&quot;)<br>     for i := 0; i &lt; len(lst); i++ {<br>      if e, _ := regexp.MatchString(&quot;(Completed|Running|NAME)&quot;, lst[i]); e == false &amp;&amp; len(lst[i]) &gt; 0 {<br>       pack := strings.Fields(lst[i])<br>       b := pack[0] + &quot; =&gt; &quot; + pack[2] + &quot;\n&quot;<br>       file, err := os.OpenFile(&quot;/tmp/info.txt&quot;, os.O_APPEND|os.O_WRONLY, 0644)<br>       x=x+1<br>                 if err != nil {<br>                     log.Fatal(err)<br>                 }<br>                 //nl := &quot;\nText appended to the second line&quot;<br>          _, err = fmt.Fprintln(file, b)<br>                 if err != nil {<br>                     log.Fatal()<br>                 }<br>               }<br>              }<br>     if x &gt; 0 {<br>      return true<br>     } else  {<br>      return false<br>     }</pre><pre>}</pre><pre>func main() {</pre><pre>if validate() {<br>      s := exec.Command(&quot;cat&quot;,&quot;/tmp/info.txt&quot;)<br>            sw, _ := s.Output()<br>     cmd := exec.Command(&quot;sh&quot;,&quot;run.sh&quot;,string(sw))</pre><pre>err := cmd.Run()</pre><pre>if err != nil {<br>            log.Fatal(err)<br>        }<br>        } else {<br>         fmt.Println(&quot;No error&quot;)<br>        }<br>    }</pre><p>Code designed to execute kubectl command and results will be filtered. Based on match final list will be posted over the channel. Neccessary permission for executing the kubectl command are designed based on the below role and bindings , feel free to add privilege if needed but limited always be safe</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  name: modify-pods<br>rules:<br>  - apiGroups: [&quot;&quot;]<br>    resources:<br>      - pods<br>    verbs:<br>      - get<br>      - list<br>      - delete</pre><p>By default I have configured the cronjob to run on every 1min but please changed based on your need</p><pre>apiVersion: batch/v1<br>kind: CronJob<br>metadata:<br>  name: code<br>spec:<br>  schedule: &quot;* * * * *&quot;<br>  jobTemplate:<br>    spec:<br>      template:<br>        spec:<br>          restartPolicy: OnFailure<br>          serviceAccountName: internal-kubectl<br>          volumes:<br>          - name: code<br>            configMap:<br>              name: code<br>          containers:<br>            - name: internal-kubectl<br>              image: ubuntu:latest<br>              command: [&quot;bash&quot;]<br>              args: [&quot;/mnt/start.sh&quot;]<br>              volumeMounts:<br>              - name: code<br>                mountPath: &quot;/mnt&quot;<br>                readOnly: true</pre><p>Also I have chosen ubuntu as the base image and required packages are installed on run time and since we are running the script as cronjob ,resource consumption will be less</p><p>I have made the service to run only on the namespace where you do the chart deployment. For monitoring multiple namespace , please do the deployment on each</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ei_LvLzUa72rb7Gl1MwHxw.png" /></figure><p>Channel webhook</p><p>Slack channel webhook will be added on the values file under the variable webhook</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_Oftx6qkiYkoKJtCIv8UA.png" /></figure><p>Once you modify webhook change please follow steps to do the deployment</p><p>To install:</p><p>git clone <a href="https://github.com/praveensams16/pod-status-monitor.git">https://github.com/praveensams16/pod-status-monitor.git</a></p><p>cd pod-status-monitor</p><p>helm -n namespace upgrade -i “pod-monitor” .</p><p>To verify</p><p>k -n namespace get cronjobs</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50e5b03ae2eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pod Status monitor /]]></title>
            <link>https://medium.com/@praveensams16/pod-status-monitor-2a6bfe0c8c13?source=rss-a25371fc5cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a6bfe0c8c13</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[kubernetes-operator]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Praveensam]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 15:57:37 GMT</pubDate>
            <atom:updated>2022-07-10T12:02:45.618Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Pod Status monitor</strong></p><p>This document describe how we going to use golang to monitor pod status and scrape the metrics to display over prometheus . How different it is from traditional metrics , this scraper display pod status using single call retriver . Also it will be easy to make the alert based on status conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*W76IgT8lH6NcGstp-FGUSA.png" /></figure><p><strong>Container Image</strong></p><p>Container image need kubectl and golang , below dockerfile covers both . Please feel free to comment terraform if you are not going to use</p><p>https://github.com/praveensams16/pod-monitor/blob/main/images/Dockerfile</p><p><strong>Charts</strong></p><p>Code is under configMap and to make the service connect kubernetes we have to bind the roles with required permission ( mostly designed to have limited privilege )</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br> name: role-pod<br>rules:<br>- apiGroups: [“*”] # “” <br> resources: [“pods”,”deployment”]<br> verbs: [“get”, “watch”, “list”]</pre><p>Ex, in the above definition we have only get , watch and list , So please add neccessary to extend the feature like deployment and status ( Changes should also be modified in the golang script if condition and command execution )</p><p><strong>Code</strong></p><pre>package main</pre><pre>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;os/exec&quot;<br> &quot;regexp&quot;<br> &quot;strings&quot;<br>)</pre><pre>var (<br> files []string<br> //lines []string<br>)</pre><pre>func run(w http.ResponseWriter, r *http.Request) {</pre><pre>cmd := exec.Command(&quot;kubectl&quot;, &quot;get&quot;, &quot;pods&quot;)<br> stdout, err := cmd.Output()</pre><pre>if err != nil {<br>  fmt.Println(err.Error())<br>  return<br> }</pre><pre>s := string(stdout)</pre><pre>files := strings.Split(string(s), &quot;\n&quot;)</pre><pre>for i := 0; i &lt; len(files); i++ {<br>  if !strings.Contains(files[i], &quot;NAME&quot;) &amp;&amp; len(files[i]) &gt; 1 &amp;&amp; !strings.Contains(files[i], &quot;Completed&quot;) {</pre><pre>lines := regexp.MustCompile(&quot;[^\\s]+&quot;)</pre><pre>status := lines.FindAllString(files[i], -1)</pre><pre>if status[2] == &quot;Running&quot; {<br>    fmt.Fprintf(w, &quot;unifonic_pod{pod=\&quot;&quot;+status[0]+&quot;\&quot;,status=\&quot;Running\&quot;}  1\n&quot;)<br>   } else {<br>    fmt.Fprintf(w, &quot;unifonic_pod{pod=\&quot;&quot;+status[0]+&quot;\&quot;,status=\&quot;&quot;+status[2]+&quot;\&quot;} 0\n&quot;)<br>   }<br>  }<br> }</pre><pre>}</pre><pre>func handleRequests() {<br> http.HandleFunc(&quot;/metrics&quot;, run)<br> log.Fatal(http.ListenAndServe(&quot;:9101&quot;, nil))<br>}</pre><pre>func main() {<br> handleRequests()<br>}</pre><p>The code designed to listen on 9101 and called by route /metrics , which in turn calls sub function run.</p><p>Right. after the deployment please make sure the service able to generate expected results on calling the function</p><p>Once the job generates the expected output , try to add the scraper in the prometheus and also in the alertmanager for generating alerts. In the below code I added the prometheus scraper to fetch the metrics for every 5 mins . Duration of collection depends on the SLA of the service to monitored and try to tune if you want to get less then .</p><p><strong>Alerts</strong></p><pre>- name: Pod Service down <br>      rules:<br>      - alert: PodServiceDown<br>        for: 5m<br>        expr:  status_pod == 0<br>        labels:<br>          severity: P3<br>          <br>        annotations:<br>          description: &#39;Prod Service {{ $labels.exported_instance }} down for 5 minutes&#39;<br>          summary: &#39;Prod Service {{ $labels.exported_instance }} down for 5 minutes&#39;</pre><p>I have added the alert in alertmager , configured to run on every 5 mins , Please make sure the scraper time less then alert trigger</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a6bfe0c8c13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalling Kafka consumer ( statefulset ) based on Kafka events]]></title>
            <link>https://medium.com/@praveensams16/scalling-kafka-consumer-statefulset-based-on-kafka-events-4ac973676861?source=rss-a25371fc5cc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ac973676861</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[scalling]]></category>
            <category><![CDATA[statefulsets]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Praveensam]]></dc:creator>
            <pubDate>Sun, 19 Jun 2022 07:23:46 GMT</pubDate>
            <atom:updated>2022-06-19T07:23:46.874Z</atom:updated>
            <content:encoded><![CDATA[<p>We have seen lot of auto scalling based on metrics , this document attempt to explain how we can scaleup and scale down pods based on kafka queue. It horizantaliy scale consumer group if we have lag in the topic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMQ4hMcDSY307235I9RbpA.png" /></figure><p><strong>How it works</strong></p><p>scale up validator is the controller pod which constantly monitor kafka topic ( topic configured) and scale up the target statefulset based on the lag count. Number of pod calculated based on the lag count , here in the document we are adding each pod on every 10K lag</p><p>scale up validor is a chart which we have to deploy on the same name space where we have running the consumer group statefulset . It is basically a golang service running on pod and have capability to manupulate k8s cluster</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: kafka-scalling<br>data:<br>  code.go: |<br>    package main</pre><pre>import (<br>        &quot;fmt&quot;<br>      &quot;time&quot;<br>        &quot;os/exec&quot;<br>        &quot;strconv&quot;<br>        &quot;strings&quot;<br>    )</pre><pre>func run() int {<br>        cmd := exec.Command(&quot;kafka-consumer-groups.sh&quot;, &quot;--bootstrap-server&quot;, &quot;kafka.ekalya.in:9092&quot;, &quot;--group&quot;, &quot;logstash&quot;, &quot;--describe&quot;)<br>        stdout, err := cmd.Output()</pre><pre>if err != nil {<br>                fmt.Println(err.Error())<br>                return 0<br>        }</pre><pre>s := string(stdout)</pre><pre>d := strings.Split(string(s), &quot;\n&quot;)</pre><pre>count := 0<br>        for i := 0; i &lt; len(d); i++ {<br>                lines := strings.Fields(d[i])<br>                if len(d[i]) &gt; 0 &amp;&amp; (lines[1] == &quot;topic&quot; || lines[1] == &quot;topic&quot;) {<br>                        lag, e := strconv.Atoi(lines[5])<br>                        if e == nil {<br>                                count = lag + count<br>                        }<br>                }</pre><pre>}<br>        return count</pre><pre>}</pre><pre>func kubes(i int) interface{} {<br>      i=3+i<br>        cmd := exec.Command(&quot;sh&quot;, &quot;-x&quot;, &quot;/mnt/sam.sh&quot;,strconv.Itoa(i))<br>        stdout, err := cmd.Output()</pre><pre>if err != nil {<br>                fmt.Println(err.Error())<br>                return 0<br>        }</pre><pre>s := string(stdout)</pre><pre>d := strings.Split(string(s), &quot;\n&quot;)<br>        return d<br>    }</pre><pre>func main() {<br>      for {<br>        count := run()/10000<br>      runs:=run()<br>        fmt.Println(count)<br>        if count &gt; 0 &amp;&amp; count &lt; 6 {<br>                fmt.Println(&quot;Value is greater then 10000 and count going to be&quot;,runs,count)<br>                kubes(count)<br>       } else if count &gt; 5 {<br>        fmt.Println(&quot;value greater the 10000 and count hount to be&quot;,runs,&quot;6&quot;)<br>        kubes(6)<br>        } else {<br>                fmt.Println(&quot;Values is less then 10000&quot;, runs,count)<br>        kubes(0)<br>        }<br>        time.Sleep(300*time.Second)<br>      }<br>    }<br>  sam.sh: |<br>    cd /mnt<br>    echo $1<br>    kubectl -n namespace scale statefulset/name --replicas=$1  &gt; /tmp/logs 2&gt;&amp;1</pre><p>Please make sure the topics are modified on above script</p><p><strong>Pod Permission and Roles</strong></p><p>This pod going to run scalable command on the cluster , so we need to provide necessary permission to the role</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  name: modify-scalling<br>rules:<br>  - apiGroups: [&quot;*&quot;]<br>    resources:<br>      - pods<br>      - deployments<br>      - namespace<br>      - deployments/scale<br>      - statefulset<br>      - statefulsets<br>      - statefulsets/scale<br>    verbs:<br>      - get<br>      - list<br>      - delete<br>      - scale<br>      - patch</pre><p>And bindings are</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: modify-pods-to-scalling<br>subjects:<br>  - kind: ServiceAccount<br>    name: sa-kafka<br>roleRef:<br>  kind: Role<br>  name: modify-scalling<br>  apiGroup: rbac.authorization.k8s.io</pre><p><strong>Charts</strong></p><p>charts contents are below</p><p><a href="https://github.com/praveensams16/kafka-scalling">https://github.com/praveensams16/kafka-scalling</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ac973676861" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>