<?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 Luiz Meier on Medium]]></title>
        <description><![CDATA[Stories by Luiz Meier on Medium]]></description>
        <link>https://medium.com/@lfmmeier?source=rss-3b52148ccc9f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WphPZMihsbN6rtryRZmB7g.jpeg</url>
            <title>Stories by Luiz Meier on Medium</title>
            <link>https://medium.com/@lfmmeier?source=rss-3b52148ccc9f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:52:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lfmmeier/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[Como construí meu primeiro MCP para operações de DNS]]></title>
            <link>https://medium.com/@lfmmeier/como-constru%C3%AD-meu-primeiro-mcp-para-opera%C3%A7%C3%B5es-de-dns-026532c61353?source=rss-3b52148ccc9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/026532c61353</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[infoblox]]></category>
            <category><![CDATA[did]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Luiz Meier]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 14:42:32 GMT</pubDate>
            <atom:updated>2026-04-09T14:46:13.487Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Como construí um MCP para operações de DNS focado em intenção em vez de endpoints, aplicando IA em cenários reais de DDI.</em></p><p><em>[</em><a href="https://medium.lmeier.net/how-i-built-my-first-mcp-for-dns-operations-373a3c61fc1e"><em>Read in English</em></a><em>]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhtF4b0j6myxJpIWCPa2WA.png" /><figcaption>Gerada pelo DALL-E</figcaption></figure><p><em>Obs: Se você não é um membro Medium, pode ler este post </em><a href="https://blog.lmeier.net/pt-BR/posts/how-i-built-my-first-mcp-for-dns-operations/"><em>aqui</em></a><em>.</em></p><p>Estamos em 2026 e eu já nem sei mais se as pessoas ainda se importam tanto com MCPs.</p><p>Pelo que tenho acompanhado, outras abordagens já começam a ganhar mais espaço (skills) e formas mais diretas de integrar contexto e capacidades aos assistentes.</p><p>O mercado de IA anda tão rápido que é praticamente impossível acompanhar tudo e, ao mesmo tempo, manter a rotina de trabalho, os projetos pessoais e a vida funcionando normalmente.</p><p>Então, se MCPs já estiverem ficando para trás, tudo bem.</p><p>Ainda assim, quis escrever este post porque o processo de construir esse projeto foi útil para mim — e talvez também seja útil para alguém tentando resolver um problema parecido.</p><p>Além disso, esse blog anda um tanto abandonado…</p><h3><strong>💡 A ideia</strong></h3><p>Esse MCP surgiu quando eu estava estudando IA e quis conectar o aprendizado com algo do meu dia a dia: operações de DDI, especialmente DNS.</p><p>A ideia era simples:</p><blockquote>Criar um assistente que respondesse intenções — não que exigisse conhecimento da API.</blockquote><p>Eu queria parar de pensar em endpoints, filtros e formatos de resposta, e começar a interagir de forma mais natural, como:</p><p>- “Esse IP está em uso?”</p><p>- “Me mostra um resumo dessa zona.”</p><p>- “Tem algum problema no grid?”</p><p>Ok, eu poderia fazer isso desenvolvendo algum script, mas eu não queria ter que ficar criando código pra consumir API e conseguir informações do dia a dia.</p><h3><strong>🧩 O problema real</strong></h3><p>Quem trabalha com DNS/DDI sabe como isso normalmente funciona: você precisa saber dados do servidor, zona, registros e tem que ou chamar a API ou acessar a GUI da solução. dige nslookup mostram que o que o DNS responde mas não mostram o que está acontecendo no ambiente.</p><p>Para uma visão operacional ou gerencial, isso simplesmente não basta.</p><h4><strong>❌ Antes (API direta)</strong></h4><p>O cenário antes de começar a usar o MCP era:</p><ul><li>Descobrir qual endpoint usar</li><li>Montar filtros corretamente</li><li>Fazer a chamada</li><li>Interpretar a resposta</li><li>Correlacionar dados</li></ul><p>Tudo isso para responder perguntas relativamente simples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLe2myl7fZ31vBg8vkZE8A.png" /></figure><h4><strong>✅ Depois (com MCP)</strong></h4><p>Depois o cenário mudou para:</p><ul><li>“Esse IP está em uso?”</li></ul><p>E pronto. Essa foi a mudança principal:</p><blockquote>Subir o nível de abstração da API para intenção operacional.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32x2Q6uzYJD9P286RcV4ZQ.png" /></figure><h3><strong>⚙️ O que esse MCP faz hoje</strong></h3><p>Na prática, ele funciona como uma camada intermediária entre o Infoblox DDI e uma interface orientada a tools para LLMs. Eu uso o meu próprio VSCode pra falar com o MCP enquanto estou desenvolvendo qualquer rotina/automação ou se preciso de qualquer informação rápida. Principalmente situações de troubleshooting, onde normamente eu teria que navegar pela GUI ou chamar a API para validar alguma coisa.</p><p>O importante é: não é um wrapper de API.</p><blockquote>Eu não transformei endpoints em tools. Eu transformei operações reais em interface consumida via linguagem natural.</blockquote><p>As principais capacidades hoje são:</p><h4><strong>🔎 Consulta básica</strong></h4><ul><li>list_zones</li><li>list_records</li></ul><h4><strong>🔍 Busca</strong></h4><ul><li>search_dns_record</li><li>check_ip_usage</li></ul><h4><strong>📊 Visão agregada</strong></h4><ul><li>get_zone_summary</li><li>get_dns_overview</li><li>get_grid_status</li><li>list_grid_members</li></ul><p>Isso permite responder coisas como:</p><ul><li>“Quais zonas existem hoje?”</li><li>“Esse IP já está sendo usado?”</li><li>“Tem algum membro do grid degradado?”</li><li>“Como está a saúde geral do serviço de DNS?”</li></ul><h3><strong>🏗️ Decisões de arquitetura</strong></h3><p>Algumas decisões foram importantes para manter o projeto simples e útil:</p><h4><strong>1. Read-only primeiro</strong></h4><p>Como estamos falando de DNS e infraestrutura, comecei apenas com leitura.</p><p>Antes de pensar em automação ou escrita, eu queria validar:</p><ul><li>Utilidade</li><li>Formato das respostas</li><li>Interação com o modelo</li></ul><h4><strong>2. Separação de camadas</strong></h4><p>A estrutura ficou propositalmente simples:</p><ul><li>MCP (interface)</li><li>Service (lógica operacional)</li><li>Client (integração com WAPI)</li><li>Models (estrutura de dados)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*d7VBrL8jHTwpj_R_-Rx99A.png" /></figure><p>Isso ajudou muito na clareza e evolução do projeto.</p><h3><strong>🧠 O principal aprendizado</strong></h3><p>A maior lição foi essa:</p><blockquote>Integrar IA com infraestrutura não é sobre conectar APIs, e sim sobre desenhar interfaces.</blockquote><p>Se você expõe endpoints crus, o modelo precisa descobrir muita coisa sozinho. Se você expõe intenção, o resultado melhora drasticamente.</p><p>Foi nesse ponto que comecei a pensar em algo diferente: facilidade operacional.</p><h3><strong>🤖 Um aprendizado inesperado</strong></h3><p>Curiosamente, uma das partes mais difíceis não foi construir o projeto, e sim evitar que a IA construísse tudo por mim.</p><p>Eu usei o Codex como apoio, mas precisei controlar o ritmo:</p><ul><li>Pedindo passo a passo</li><li>Solicitando explicações</li><li>Evitando soluções prontas</li></ul><p>Porque o objetivo aqui não era só construir — era entender.</p><h3><strong>🚀 Como usar</strong></h3><p>Se quiser baixar, testar ou até contribuir com a evolução do projeto, o repositório está aqui: [github.com/LuizMeier/mcp-ddi](https://github.com/LuizMeier/mcp-ddi).</p><p>Para testar:</p><h4><strong>1. Configure as variáveis</strong></h4><pre>WAPI_URL<br>WAPI_USER<br>WAPI_PASS<br>WAPI_VERIFY_SSL</pre><h4><strong>2. Suba o ambiente</strong></h4><pre>python3 -m venv .venv<br>source .venv/bin/activate<br>pip install -r requirements.txt<br>python3 main.py</pre><p>Depois disso, conecte a um cliente MCP e use prompts como:</p><ul><li>“Liste as zonas DNS disponíveis”</li><li>“Mostre os registros da zona example.com”</li><li>“Verifique se o IP 10.10.10.15 está em uso”</li><li>“Me dê um resumo da zona example.com”</li><li>“Qual o status do grid?”</li></ul><h3><strong>📐 Consistência das respostas</strong></h3><p>Uma coisa que cuidei desde o início foi padronizar o retorno das tools.</p><p>Todas seguem um formato parecido:</p><ul><li>operação</li><li>sucesso</li><li>quantidade</li><li>dados</li><li>mensagem</li></ul><p>Isso reduz ambiguidade e ajuda bastante quando o consumidor é um LLM.</p><h3><strong>🔭 Próximos passos</strong></h3><p>Algumas evoluções que penso:</p><ul><li>IPAM</li><li>DHCP</li><li>mais contexto nas respostas</li><li>fluxos mais completos de troubleshooting</li></ul><h3><strong>🧭 Conclusão</strong></h3><p>Talvez MCP seja só mais um nome que vai mudar mas o aprendizado fica.</p><blockquote>A diferença não está no modelo — está na interface que você entrega para ele.</blockquote><p>No fim essa brincadeira foi sobre aprender a abstrair solução técnica para algo que faça sentido para humanos e IA.</p><p>Espero que seja útil. Grande abraço!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=026532c61353" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built my first MCP for DNS operations]]></title>
            <link>https://medium.com/@lfmmeier/how-i-built-my-first-mcp-for-dns-operations-373a3c61fc1e?source=rss-3b52148ccc9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/373a3c61fc1e</guid>
            <category><![CDATA[did]]></category>
            <category><![CDATA[infoblox]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Luiz Meier]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 14:42:29 GMT</pubDate>
            <atom:updated>2026-04-09T14:45:27.030Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How I built my first MCP for DNS operations</strong></p><p><em>How I built an MCP for DNS operations focused on intent instead of endpoints, applying AI to real-world DDI scenarios.</em></p><p><em>[</em><a href="https://medium.lmeier.net/como-constru%C3%AD-meu-primeiro-mcp-para-opera%C3%A7%C3%B5es-de-dns-026532c61353"><em>Leia em Português</em></a><em>]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhtF4b0j6myxJpIWCPa2WA.png" /><figcaption>Gerada pelo DALL-E</figcaption></figure><p><em>PS: if you are not a Medium member, you can read this story </em><a href="https://blog.lmeier.net/posts/how-i-built-my-first-mcp-for-dns-operations/"><em>here</em></a><em>.</em></p><p>It is 2026, and I am not even sure people care that much about MCPs anymore.</p><p>From what I have seen, other approaches are already gaining traction, such as skills and more direct ways of integrating context and capabilities into assistants.</p><p>The AI market moves so fast that it is practically impossible to keep up with everything while still keeping your work routine, personal projects, and life running normally.</p><p>So if MCPs are already starting to fall behind, that is fine.</p><p>Even so, I wanted to write this post because the process of building this project was useful to me, and maybe it can help someone trying to solve a similar problem too.</p><p>Besides, this blog has been a little neglected lately…</p><h3><strong>💡 The idea</strong></h3><p>This MCP came out of a moment when I was studying AI and wanted to connect that learning to something in my day-to-day work: DDI operations, especially DNS.</p><p>The idea was simple:</p><blockquote>Build an assistant that responds to intentions, not one that requires API knowledge.</blockquote><p>I wanted to stop thinking about endpoints, filters, and response formats, and start interacting more naturally, with prompts like:</p><ul><li>“Is this IP in use?”</li><li>“Show me a summary of this zone”</li><li>“Is there any issue in the grid?”</li></ul><p>Sure, I could have done that by writing a script, but I did not want to keep writing code just to consume an API and retrieve routine operational information.</p><h3><strong>🧩 The real problem</strong></h3><p>Anyone who works with DNS/DDI knows how this usually goes: you need to know server details, zones, and records, and then either call the API or access the product GUI. `dig` and `nslookup` show what DNS is returning, but they do not show what is happening inside the environment.</p><p>For an operational or managerial view, that is simply not enough.</p><h4><strong>❌ Before (direct API)</strong></h4><p>Before I started using the MCP, the workflow looked like this:</p><ul><li>Figure out which endpoint to use</li><li>Build the filters correctly</li><li>Make the request</li><li>Interpret the response</li><li>Correlate the data</li></ul><p>All of that just to answer relatively simple questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gBJdbqn1p5ae8zQZVrYog.png" /></figure><h4><strong>✅ After (with MCP)</strong></h4><p>Afterward, the workflow became:</p><ul><li>“Is this IP in use?”</li></ul><p>And that was it. That was the main shift:</p><blockquote>Raise the level of abstraction from API calls to operational intent.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsmesSSVG3diNgm4hWEywA.png" /></figure><h3><strong>⚙️ What this MCP does today</strong></h3><p>In practice, it works as an intermediate layer between Infoblox DDI and a tool-oriented interface for LLMs. I use VSCode itself to talk to the MCP while I am building automations or whenever I need quick information, especially in troubleshooting scenarios where I would otherwise have to navigate the GUI or call the API to validate something.</p><p>The key point is this: it is not an API wrapper.</p><blockquote>I did not turn endpoints into tools. I turned real operations into an interface consumed through natural language.</blockquote><p>Its main capabilities today are:</p><h4><strong>#🔎 Basic lookup</strong></h4><ul><li>list_zones</li><li>list_records</li></ul><h4><strong>🔍 Search</strong></h4><ul><li>search_dns_record</li><li>check_ip_usage</li></ul><h4><strong>📊 Aggregated view</strong></h4><ul><li>get_zone_summary</li><li>get_dns_overview</li><li>get_grid_status</li><li>list_grid_members</li></ul><p>That makes it possible to answer questions such as:</p><ul><li>“Which zones exist today?”</li><li>“Is this IP already in use?”</li><li>“Is any grid member degraded?”</li><li>“What is the overall DNS service health?”</li></ul><h3><strong>🏗️ Architecture decisions</strong></h3><p>Some decisions were important to keep the project simple and useful:</p><h4><strong>1. Read-only first</strong></h4><p>Since we are talking about DNS and infrastructure, I started with read-only operations.</p><p>Before thinking about automation or write actions, I wanted to validate:</p><ul><li>Usefulness</li><li>Response format</li><li>Interaction with the model</li></ul><h4><strong>2. Layer separation</strong></h4><p>The structure was intentionally simple:</p><ul><li>MCP (interface)</li><li>Service (operational logic)</li><li>Client (WAPI integration)</li><li>Models (data structure)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*as9CVrvegwz31gb5mZ8ogQ.png" /></figure><p>That helped a lot with clarity and made the project easier to evolve.</p><h3><strong>🧠 The main lesson</strong></h3><p>The biggest lesson was this:</p><blockquote>Integrating AI with infrastructure is not about connecting APIs. It is about designing interfaces.</blockquote><p>If you expose raw endpoints, the model has to figure out too much on its own. If you expose intent, the outcome improves dramatically.</p><p>That was the point where I started thinking about something slightly different: operational usability.</p><h3><strong>🤖 An unexpected lesson</strong></h3><p>Interestingly, one of the hardest parts was not building the project itself, but stopping AI from building everything for me.</p><p>I used Codex for support, but I had to control the pace:</p><ul><li>Asking for step-by-step guidance</li><li>Requesting explanations</li><li>Avoiding ready-made solutions</li></ul><p>Because the goal here was not just to build it, but to understand it.</p><h3><strong>🚀 How to use it</strong></h3><p>If you want to download it, try it out, or even contribute to the project, the repository is here: [github.com/LuizMeier/mcp-ddi](https://github.com/LuizMeier/mcp-ddi).</p><p>To test it:</p><h4><strong>1. Configure the variables</strong></h4><pre>WAPI_URL<br>WAPI_USER<br>WAPI_PASS<br>WAPI_VERIFY_SSL</pre><p><strong>### 2. Start the environment</strong></p><pre>python3 -m venv .venv<br>source .venv/bin/activate<br>pip install -r requirements.txt<br>python3 main.py</pre><p>After that, connect it to an MCP client and use prompts such as:</p><ul><li>“List the available DNS zones”</li><li>“Show me the records for the zone example.com”</li><li>“Check whether IP 10.10.10.15 is in use”</li><li>“Give me a summary of the zone example.com”</li><li>“What is the status of the grid?”</li></ul><h3><strong>📐 Response consistency</strong></h3><p>One thing I cared about from the beginning was standardizing the output format of the tools.</p><p>They all follow a similar structure:</p><ul><li>operation</li><li>success</li><li>count</li><li>data</li><li>message</li></ul><p>That reduces ambiguity and helps a lot when the consumer is an LLM.</p><h3><strong>🔭 Next steps</strong></h3><p>Some improvements I am considering:</p><ul><li>IPAM</li><li>DHCP</li><li>More context in the responses</li><li>More complete troubleshooting flows</li></ul><h3><strong>🧭 Conclusion</strong></h3><p>Maybe MCP is just another label that will eventually change, but the learning stays.</p><blockquote>The difference is not in the model. It is in the interface you give it.</blockquote><p>In the end, this whole experiment was about learning how to abstract a technical solution into something that makes sense to both humans and AI.</p><p>I hope it is useful. See you around!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=373a3c61fc1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Backstage and Azure DevOps]]></title>
            <link>https://medium.com/@lfmmeier/integrating-backstage-and-azure-devops-aa39d2f29297?source=rss-3b52148ccc9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa39d2f29297</guid>
            <category><![CDATA[backstage]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[pipeline]]></category>
            <dc:creator><![CDATA[Luiz Meier]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 17:26:34 GMT</pubDate>
            <atom:updated>2025-03-06T18:19:21.059Z</atom:updated>
            <content:encoded><![CDATA[<p>Automate the resource delivery in Azure integrating Backstage and Azure DevOps. A step-by-step guide about configuring, templates and pipelines.</p><p><em>[</em><a href="https://medium.lmeier.net/fe10f45376e5"><em>Leia em Português</em></a><em>]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lZonTnOVm6kHCPyb.png" /><figcaption>Gerado pelo DALL-E</figcaption></figure><p><em>Note: if you are not a Medium member, you can check this content </em><a href="https://blog.lmeier.net/posts/integrating-backstage-azure-devops-en/"><em>h</em>ere</a><em>.</em></p><h3>Introduction</h3><p>This is the second post I am writing about Backstage. Check out the first one, where I discuss integration with Entra ID <a href="https://blog.lmeier.net/posts/authentication-backstage-entra-id-en">here</a>. Now, let’s walk through all the steps to integrate Backstage and Azure DevOps to automate resource delivery in Azure using a CI/CD pipeline. Be prepared, because this one is going to be long!</p><h3>Sumário</h3><p>1️⃣Introduction</p><p>2️⃣Summary</p><p>3️⃣Create a PAT for use</p><p>4️⃣Configure Backstage to use the PAT</p><ul><li>Add the PAT to Backstage</li><li>Test the integration functioning</li></ul><p>5️⃣Install the Azure DevOps Plugin</p><p>6️⃣Create the template for use by Backstage</p><p>7️⃣Create the Terraform code</p><p>8️⃣Create the pipeline to execute the code</p><ul><li>Create a service connection</li><li>Create the pipeline in Azure DevOps</li></ul><p>9️⃣Final Test</p><p>🔟Conclusion</p><p>💡 <strong>Note</strong>: Having Entra ID as an IDP is not a prerequisite for working with Azure DevOps. However, it is common for both solutions to be used in a Microsoft environment.</p><p>For this post, I created a new project in Azure DevOps called Backstage, where we will store our Backstage template, Terraform code, and the yaml file to create our pipeline.</p><p>⚠️ <strong>Attention</strong>: I will assume that you already know how to create a project, repository, and use the minimum necessary git commands.</p><p><a href="https://backstage.io/docs/integrations/azure/locations">In this link</a> you can check the Backstage documentation for this integration. Backstage supports the use of managed identity, service principal, and PAT. For the purpose of this post, I will use PAT as it is simpler.</p><h3>Create a PAT for use</h3><p>1. To create your token, go to the upper right corner of Azure DevOps and click on <strong>User settings</strong> and then <strong>Personal access tokens</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*9faGZ2-4e0zUVsCW.png" /><figcaption>PAT</figcaption></figure><p>2. Click on <strong>New Token</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*RsYhtwfo5HY1g68j.png" /><figcaption>New token</figcaption></figure><p>3. Give a name to the PAT and configure the necessary permissions. Then confirm the creation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*XobwJvEb4AK7t4B_.png" /><figcaption>PAT permissions</figcaption></figure><p>4. Copy the token and save it somewhere, as you will not be able to retrieve it again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/0*kI22TGhFqGBQr5g1.png" /><figcaption>Successfull creation</figcaption></figure><h3>Configure Backstage to use the PAT</h3><h4>Add the PAT to Backstage</h4><p>Now let’s go back to the Backstage code to modify the app-config.yaml file. With it open, add the code snippet below to the integrations section:</p><pre>integrations:<br>  azure:<br>    - host: dev.azure.com<br>      credentials:<br>        - personalAccessToken: ${PERSONAL_ACCESS_TOKEN}</pre><h4>Test the integration functioning</h4><p>With that configured, it should already be possible to test Backstage’s access to your Azure DevOps repository. To test this, let’s store a test template file inside our repository, in a folder called template. After that, we will try to import this template into Backstage. Below, I’ll provide a sample file that I took from the Backstage documentation and only changed the name field.</p><pre>apiVersion: backstage.io/v1alpha1<br>kind: Component<br>metadata:<br>  name: test-lab<br>  description: |<br>    Backstage is an open-source developer portal that puts the developer experience first.<br>  links:<br>    - title: Website<br>      url: http://backstage.io<br>    - title: Documentation<br>      url: https://backstage.io/docs<br>    - title: Storybook<br>      url: https://backstage.io/storybook<br>    - title: Discord Chat<br>      url: https://discord.com/invite/EBHEGzX<br>  annotations:<br>    github.com/project-slug: backstage/backstage<br>    backstage.io/techdocs-ref: dir:.<br>    lighthouse.com/website-url: https://backstage.io<br>spec:<br>  type: library<br>  owner: CNCF<br>  lifecycle: production</pre><p>1. Now, go to Azure DevOps and create a folder called templates and create a new file, adding the code above and naming it test.yaml. Confirm the Commit to create the file and copy the URL that leads directly to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/0*aK4uIkGRemLqJSsJ.png" /><figcaption>Test</figcaption></figure><p>2. After copying the URL, go back to Backstage and go to the <strong>Create…</strong> menu and click on the <strong>Register Existing Component</strong> option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YcxSlzWJgB--Yi60.png" /><figcaption>Component registration</figcaption></figure><p>3. Paste the URL of the file we just created and select <strong>Analyze</strong>. If the integration is functional, Backstage will be able to read the file from Azure DevOps and import it. Confirm the import.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/0*dCN8ugMt4boLuat1.png" /><figcaption>File Validation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/0*UEmX4f-YI5Ztjur4.png" /><figcaption>Importing component</figcaption></figure><p>4. Clicking on <strong>View Component</strong> you will be able to see the information of the component you just imported, named test-lab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/0*-a2G4nCGdPGt4Zft.png" /><figcaption><em>Checking create dcomponent</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KawDeZO0yrCarIGt.png" /><figcaption>Properties of the created component</figcaption></figure><p>Congratulations, the integration with Azure DevOps is working!</p><h3>Install the Azure DevOps Plugin</h3><p>For our Backstage template to work properly, we will need the actions azure:repo:clone, azure:repo:push, and azure:repo:pr. These actions will be taken by the template to download the code, then push it, and finally create a pull request. To check if they are already installed, you can go to <strong>Create</strong> and then, in the upper right corner, select <strong>Installed Actions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jIN3apMAMvxJvd8v.png" /><figcaption>Finding installed actions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6-Az5583Oh87KiN_.png" /><figcaption>Listing actions</figcaption></figure><p>To enable them, run the command below from the root of your project. Here is the <a href="https://www.npmjs.com/package/@parfuemerie-douglas/scaffolder-backend-module-azure-repositories">plugin page</a>.</p><pre>yarn --cwd packages/backend add @parfuemerie-douglas/scaffolder-backend-module-azure-repositories</pre><p>Then, add the code below to the packages/backend/src/index.ts file:</p><pre>// Azure DevOps<br>backend.add(import(&#39;@parfuemerie-douglas/scaffolder-backend-module-azure-repositories&#39;))</pre><h3>Create the template for use by Backstage</h3><p>Now that we have Backstage ready to communicate with Azure DevOps and the necessary plugins installed, let’s create the template, which is nothing more than the form that will receive the requester’s data for resource provisioning. I will provide a very simple template model, where the user will be asked to provide their name and the name of the resource group they want to create.</p><p>One of the things I had the most difficulty with was finding the necessary information to achieve the expected result using the template. Here is a very simple template model.</p><pre># Template for creating a new Azure DevOps repository and pushing a new Backstage component to it.</pre><pre>apiVersion: scaffolder.backstage.io/v1beta3<br>kind: Template<br>metadata:<br>  name: azure-repo-demo<br>  title: Azure Repository Test<br>  description: Clone and push to an Azure repository example.<br>spec:<br>  owner: parfuemerie-douglas<br>  type: service</pre><pre>  parameters:<br>    - title: Fill in some steps<br>      required:<br>        - name<br>      properties:<br>        name:<br>          title: RG Name<br>          type: string<br>          description: Choose a unique resource-group name.</pre><pre>  steps:<br>    - id: cloneAzureRepo<br>      name: Clone Azure Repo<br>      action: azure:repo:clone<br>      input:<br>        remoteUrl: &quot;https://&lt;MY_AZURE_ORGANIZATION&gt;@dev.azure.com/&lt;MY_AZURE_ORGANIZATION&gt;/&lt;MY_AZURE_PROJECT&gt;/_git/&lt;MY_AZURE_REPOSITORY&gt;&quot;<br>        branch: &quot;main&quot;<br>        targetPath: ./sub-directory</pre><pre>    - id: fetch<br>      name: Template Skeleton<br>      action: fetch:template<br>      input:<br>        url: https://dev.azure.com/&lt;MY_AZURE_ORGANIZATION&gt;/&lt;MY_AZURE_PROJECT&gt;/_git/&lt;MY_AZURE_REPOSITORY&gt;?path=/terraform/base<br>        targetPath: ./sub-directory/terraform/changed<br>        replace: true<br>        values:<br>          name: ${{ parameters.name }}</pre><pre>- id: pushAzureRepo<br>      name: Push to Remote Azure Repo<br>      action: azure:repo:push<br>      input:<br>        branch: &lt;MY_AZURE_REPOSITORY_BRANCH&gt;<br>        sourcePath: ./sub-directory<br>        gitCommitMessage: Add ${{ parameters.name }} project files</pre><pre>    - id: pullRequestAzureRepo<br>      name: Create a Pull Request to Azure Repo<br>      action: azure:repo:pr<br>      input:<br>        sourceBranch: &lt;MY_AZURE_REPOSITORY_BRANCH&gt;<br>        targetBranch: &quot;main&quot;<br>        repoId: &lt;MY_AZURE_REPOSITORY&gt;<br>        title: ${{ parameters.name }}<br>        project: &lt;MY_AZURE_PROJECT&gt;<br>        organization: &lt;MY_AZURE_ORGANIZATION&gt;<br>        description: &quot;This is a pull request from Backstage&quot;<br>        supportsIterations: false</pre><pre>  output:<br>    links:<br>      - title: Repository<br>        url: &quot;dev.azure.com?owner=&lt;MY_AZURE_PROJECT&gt;&amp;repo=&lt;MY_AZURE_REPOSITORY&gt;&amp;organization=&lt;MY_AZURE_ORGANIZATION&gt;&quot;<br>      - title: Open in catalog<br>        icon: catalog<br>        entityRef: ${{ steps.register.output.entityRef }}</pre><blockquote><em>⚠️</em><strong><em>Important Note about Templates</em></strong><em>⚠️:</em></blockquote><blockquote><em>When using relative paths for file handling in Backstage, it </em><strong><em>always</em></strong><em> starts from the location where </em><strong><em>the template was imported</em></strong><em>.</em></blockquote><blockquote><em>In other words, it always concatenates the path you provide with the path from where the template was imported. Thus, either you keep the files to be handled in the same location as the file from which you imported the template or use a URL from an external location, which is the approach I used here in the </em><em>fetch:template action. More about this can be seen </em><a href="https://backstage.io/docs/features/software-templates/"><em>here</em></a><em> and </em><a href="https://backstage.io/docs/tooling/cli/templates/"><em>here</em></a><em>.</em></blockquote><p>Returning to our process, create the template file in Azure DevOps (replacing the necessary fields) and then go to Backstage and follow the same import process we did before in the integration test. When importing the template, you might encounter the error below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*JVxiztT8ulx43FhK.png" /><figcaption>Error importing template</figcaption></figure><p>If this happens, it is because Backstage is not allowing resources of type <strong>Template</strong> to be imported. To fix this, edit the app-config.yaml file, adding Template to the allow list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*qLibSphLINM8ZrvK.png" /><figcaption>Enabling template</figcaption></figure><p>Once the template is imported, it should appear in the <strong>Create…</strong> menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g_9VCp5GMOI25MiN.png" /><figcaption>New template available</figcaption></figure><h3>Create the Terraform code</h3><p>Okay, now that we know Backstage and Azure DevOps are communicating, let’s create a simple code that will be used by our pipeline to create a resource in Azure. There is nothing simpler than a resource group, so let’s go this route.</p><p>The minimum code for this to work is as follows:</p><pre>provider &quot;azurerm&quot; {<br>  features {}<br>}<br>resource &quot;azurerm_resource_group&quot; &quot;example&quot; {<br>  name     = &quot;${{ values.name }}&quot;<br>  location = &quot;&lt;AZ_LOCATION&gt;&quot;<br>}</pre><p>⚠️ I am not using a storage account here to store your Terraform state! For production environments, I suggest storing the state in a secure location.</p><p>Pay attention to the name variable, as it will be filled with the value coming from Backstage. Here we are making a very simple example using only one variable, but extrapolate this idea to any code you want to execute.</p><p>Once the Terraform code is created, upload it to our Azure DevOps repository.</p><p>💡 <strong>Important</strong>: since the idea is for Backstage to handle this file and then upload it and subsequently create a Pull Request of code, this (containing the name variable) will be replaced by the value coming from Backstage, making the code <strong>non-reusable</strong>. To avoid this, we will separate the code with the variable, which we will call base, from the code that will have the variable filled, which we will call changed, for simplicity. This way, we will always have a place with the code ready to be used.</p><p>Below is the approach I find the simplest, but feel free to adapt it to your needs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*8jv4QvMTWisG2LVB.png" /><figcaption>Terraform files</figcaption></figure><h3>Create the pipeline to execute the code</h3><p>Finally, let’s create a pipeline that will be triggered whenever there is a change in the code. This will only happen when someone approves the pull request that Backstage will create.</p><h4>Create a service connection</h4><p>A service connection is required for Azure DevOps to create resources in Azure.</p><ol><li>In the left menu, click on <strong>Service connections</strong> and then click on <strong>Create service connection</strong>. Then, in the right panel, select the <strong>Azure Resource Manager</strong> type:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ede74OmDJVraoJr9.png" /><figcaption>Creating service connection</figcaption></figure><p>2. You will need to authenticate in Azure to authorize the connection. Follow the process and fill in the left panel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*Nhh8uOsjpI7xzjK_.png" /><figcaption>Configuring connection</figcaption></figure><p>3. If everything went well, you will see the created connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*-SB1f9uRMprnWad6.png" /><figcaption>Connection created</figcaption></figure><h4>Create the pipeline in Azure DevOps</h4><ol><li>Go to Azure DevOps, in Pipelines. Then click on <strong>Create Pipeline</strong>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x1IW4F1MjHlBRKpv.png" /><figcaption>Creating pipeline</figcaption></figure><p>2. Select the location where your code is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*ZAAZd6j3UHKBdK1N.png" /><figcaption>Selecting repository location</figcaption></figure><p>3. Select the repository in question:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*kTfLZXiqkBMRfcXA.png" /><figcaption>Select the repository in question</figcaption></figure><p>4.Select the existing yaml option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*GBfjBWBsU9wtrgJt.png" /><figcaption>Selecting option</figcaption></figure><p>5. Paste the yaml below, replacing the necessary values (even if you do not store the terraform state somewhere, you will need to provide these details to use the TerraformTaskV4@4 action):</p><pre>trigger:<br>- main<br><br>pool:<br>  vmImage: ubuntu-latest<br><br>steps:<br>- task: TerraformTaskV4@4<br>  displayName: Terraform Init<br>  inputs:<br>    provider: &#39;azurerm&#39;<br>    command: &#39;init&#39;<br>    backendServiceArm: &#39;&lt;SERVICE_CONNECTION_NAME&gt;&#39;<br>    backendAzureRmResourceGroupName: &#39;&lt;AZ_RG_NAME&gt;&#39;<br>    backendAzureRmStorageAccountName: &#39;&lt;AZ_SA_NAME&gt;&#39;<br>    backendAzureRmContainerName: &#39;&lt;AZ_SA_CONTAINER_NAME&gt;&#39;<br>    backendAzureRmKey: &#39;&lt;AZ_KEY_NAME&gt;&#39;<br>    workingDirectory: $(System.DefaultWorkingDirectory)/terraform/changed<br>- task: TerraformTaskV4@4<br>  displayName: Terraform Validate<br>  inputs:<br>    provider: &#39;azurerm&#39;<br>    command: &#39;validate&#39;<br>    workingDirectory: $(System.DefaultWorkingDirectory)/terraform/changed<br>- task: TerraformTaskV4@4<br>  displayName: Terraform Plan<br>  inputs:<br>    provider: &#39;azurerm&#39;<br>    command: &#39;plan&#39;<br>    environmentServiceNameAzureRM: &#39;&lt;SERVICE_CONNECTION_NAME&gt;&#39;<br>    workingDirectory: $(System.DefaultWorkingDirectory)/terraform/changed<br>- task: TerraformTaskV4@4<br>  displayName: Terraform Apply<br>  inputs:<br>    provider: &#39;azurerm&#39;<br>    command: &#39;apply&#39;<br>    workingDirectory: &#39;$(System.DefaultWorkingDirectory)/terraform/changed&#39;<br>    environmentServiceNameAzureRM: &#39;&lt;SERVICE_CONNECTION_NAME&gt;&#39;</pre><h3>Final Test</h3><p>Well, with everything in place, we can finally test our entire environment. Go to Backstage, click on <strong>Create…</strong>, enter the name of the resource group you want to create, and confirm. This should make Backstage download the code, add the data you provided, and create a pull request in Azure DevOps, which you will need to approve. Once approved, the pipeline should run automatically. Let’s see this happen?</p><ol><li>Go to the template and enter the name you want for the resource group:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HCKH9Dn8STzDAnXK.png" /><figcaption>Resource Group Name</figcaption></figure><p>2.Review what you entered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FfjoUfiGrEdiS4vD.png" /><figcaption>Validating Information</figcaption></figure><p>3. If everything is okay, confirm and wait for the execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xpqLvyUNLWfXaT0I.png" /><figcaption>Complete Execution</figcaption></figure><p>4. After the execution, go to Azure DevOps and see the created Pull Request. You can even validate the files that were changed and included in the PR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wcwX7_0jEr-Owvng.png" /><figcaption>Pull Requests</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KBuiOT-_0LRmF7Dc.png" /><figcaption>Changed files</figcaption></figure><p>5. If everything is okay, approve the PR and complete it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*52HPidu4IjhaZlEl.png" /><figcaption>PR approval</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/0*gJ8tyeQIHJN8lzCE.png" /><figcaption>Completing the merge</figcaption></figure><p>Here it is interesting to mention that the setup model is very customizable. Your company may prefer not to have approval, or it may want more than one approval. For all these scenarios, you should adjust the environment to the need. The intention here was to show the concept and how to put it into practice.</p><p>6. After the change is approved, go to the pipeline and follow the result. It should run without problems and create your resource in Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KTcMt6ssAUC2-ooM.png" /><figcaption>Pipeline</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/0*RC8NbWgGJHT4rm6s.png" /><figcaption>Pipeline execution</figcaption></figure><p>If everything went as expected, you should see your resource created in the Azure console.</p><h3>Conclusion</h3><p>In this post, you learned how to integrate Backstage with Azure DevOps and set up an automated workflow for resource provisioning. We covered everything from configuring the PAT, integrating Backstage with Azure DevOps, to validating the connection with a sample template.</p><p>With this foundation, you can expand this implementation to meet the specific needs of your environment, further automating the infrastructure management process.</p><p>Now, it’s your turn to explore new possibilities and adapt this workflow to make development and operations more efficient.</p><p>If you have any questions or suggestions, share them in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa39d2f29297" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrando Backstage com Azure DevOps]]></title>
            <link>https://medium.com/@lfmmeier/integrando-backstage-com-azure-devops-fe10f45376e5?source=rss-3b52148ccc9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe10f45376e5</guid>
            <category><![CDATA[backstage]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[automação]]></category>
            <dc:creator><![CDATA[Luiz Meier]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 17:25:54 GMT</pubDate>
            <atom:updated>2025-03-06T18:22:29.486Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Automatize a entrega de recursos na Azure integrando o Backstage com o Azure DevOps. Um guia passo a passo sobre configuração, templates e pipelines.</em></p><p><em>[</em><a href="https://medium.lmeier.net/integrating-backstage-and-azure-devops-aa39d2f29297"><em>Read in English</em></a><em>]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lZonTnOVm6kHCPyb.png" /><figcaption>Gerado pelo DALL-E</figcaption></figure><p><em>Obs.: se você não é um membro Medium, pode acessar este conteúdo </em><a href="https://blog.lmeier.net/posts/integrando-backstage-azure-devops-pt-BR/"><em>aqui</em></a><em>.</em></p><h3>Introdução</h3><p>Este é o segundo post que faço abordando o Backstage. Confira o primeiro, onde falo de integração com o Entra ID <a href="https://blog.lmeier.net/posts/autenticacao-backstage-entra-id-pt-BR/">aqui</a>. Agora, vamos abordar todos os passos para a integração do Backstage ao Azure DevOps para automatizar a entrega de recursos na Azure por meio de uma pipeline. Se prepare, porque vai ser longo!</p><h3>Sumário</h3><p>1️⃣Introdução</p><p>2️⃣Sumário</p><p>3️⃣Crie um PAT para uso</p><p>4️⃣Configure o Backstage para usar o PAT</p><ul><li>Adicione o PAT ao Backstage</li><li>Teste o funcionamento da integração</li></ul><p>5️⃣Instale o plugin do Azure DevOps</p><p>6️⃣Crie o template para uso pelo Backstage</p><p>7️⃣Crie o código Terraform</p><p>8️⃣Crie a pipeline para execução do código</p><ul><li>Crie uma conexão de serviço</li><li>Crie a pipeline no Azure DevOps</li></ul><p>9️⃣Teste final</p><p>🔟Conclusão</p><p>💡 <strong>Nota</strong>: Ter o Entra ID como IDP não é um pré-requisito para o funcionamento com o Azure DevOps. Porém, é comum que as duas soluções sejam usadas em ambiente Microsoft.</p><p>Para este post, criei um projeto novo no Azure DevOps chamado Backstage, que é onde armazenaremos nosso template do Backstage, nosso código Terraform e o arquivo yaml para criarmos a nossa pipeline.</p><p>⚠️ <strong>Atenção</strong>: Assumirei que você já sabe como criar um projeto, repositório e usar o mínimo de git necessário.</p><p><a href="https://backstage.io/docs/integrations/azure/locations">Neste link</a> você pode checar a documentação do Backstage para fazer esta integração. O Backstage suporta uso de identidade gerenciada, service principal e PAT. Para o propósito do post, vou usar PAT por ser mais simples.</p><h3>Crie um PAT para uso</h3><p>1. Para criar o seu token, vá no campo superior direito do Azure DevOps e clique em <strong>User settings</strong> e depois em <strong>Personal access tokens</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*9faGZ2-4e0zUVsCW.png" /><figcaption>PAT</figcaption></figure><p>2. Clique em <strong>New Token</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*RsYhtwfo5HY1g68j.png" /><figcaption>Novo token</figcaption></figure><p>3. Dê um nome para o PAT e configure as permissões necessárias. Depois confirme a criação:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*XobwJvEb4AK7t4B_.png" /><figcaption>Permissões do PAT</figcaption></figure><p>4. Copie o token e salve-o em algum lugar, pois você não poderá reavê-lo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/0*kI22TGhFqGBQr5g1.png" /><figcaption>Criação com sucesso</figcaption></figure><h3>Configure o Backstage para usar o PAT</h3><h4>Adicione o PAT ao Backstage</h4><p>Agora voltamos ao código do backstage para alterar o arquivo app-config.yaml. Com ele aberto, adicione o trecho de código abaixo à seção integrations:</p><pre>integrations:<br>  azure:<br>    - host: dev.azure.com<br>      credentials:<br>        - personalAccessToken: ${PERSONAL_ACCESS_TOKEN}</pre><h4>Teste o funcionamento da integração</h4><p>Com isto configurado, já deve ser possível testar o acesso do Backstage ao seu repositório do Azure DevOps. Para testar, vamos armazenar um arquivo de template de teste, dentro do nosso repositório, numa pasta chamada template. Depois, vamos tentar importar este template para dentro do Backstage. Abaixo vou deixar um arquivo de modelo, que peguei da documentação do Backstage e só alterei o campo name:</p><pre>apiVersion: backstage.io/v1alpha1<br>kind: Component<br>metadata:<br>  name: test-lab<br>  description: |<br>    Backstage is an open-source developer portal that puts the developer experience first.<br>  links:<br>    - title: Website<br>      url: http://backstage.io<br>    - title: Documentation<br>      url: https://backstage.io/docs<br>    - title: Storybook<br>      url: https://backstage.io/storybook<br>    - title: Discord Chat<br>      url: https://discord.com/invite/EBHEGzX<br>  annotations:<br>    github.com/project-slug: backstage/backstage<br>    backstage.io/techdocs-ref: dir:.<br>    lighthouse.com/website-url: https://backstage.io<br>spec:<br>  type: library<br>  owner: CNCF<br>  lifecycle: production</pre><p>1. Agora, vá ao Azure DevOps e crie uma pasta chamada templates e crie um novo arquivo, adicionando o código acima e nomeando-o como teste.yaml. Confirme o Commit para criação do arquivo e copie a url que leva diretamente a ele.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/0*aK4uIkGRemLqJSsJ.png" /><figcaption>Teste</figcaption></figure><p>2. Após copiar a url, volte no Backstage e vá ao menu <strong>Create…</strong> e clique na opção <strong>Register Existing Component</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YcxSlzWJgB--Yi60.png" /><figcaption><em>Registro de componente</em></figcaption></figure><p>3. Cole a url do arquivo que acabamos de criar e vá selecione <strong>Analyze</strong>. Se a integração estiver funcional, o Backstage será capaz de ler o arquivo do Azure DevOps e importá-lo. Confirme a importação.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/0*dCN8ugMt4boLuat1.png" /><figcaption>Validação do arquivo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/0*UEmX4f-YI5Ztjur4.png" /><figcaption>Importando componente</figcaption></figure><p>4. Clicando em <strong>View Component</strong> você será capaz de ver as informações do componente que acabou de importar, com o nome test-lab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/0*-a2G4nCGdPGt4Zft.png" /><figcaption><em>Verificando componente criado</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KawDeZO0yrCarIGt.png" /><figcaption>Propriedades do componente criado</figcaption></figure><p>Parabéns, a integração com o Azure DevOps está funcionando!</p><h3>Instale o plugin do Azure DevOps</h3><p>Para que o nosso template do Backstage funcione adequadamente, precisaremos das ações azure:repo:clone, azure:repo:push e azure:repo:pr. Estas ações serão tomadas pelo template para fazer o download do código, depois push e então criar um pull request. Para checar se elas já estão instaladas, você pode ir em <strong>Create</strong> e, então, no canto superior direito, selecionar <strong>Installed Actions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jIN3apMAMvxJvd8v.png" /><figcaption>Encontrando as ações instaladas</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6-Az5583Oh87KiN_.png" /><figcaption>Listando ações</figcaption></figure><p>Para habilitá-las, execute o comando abaixo, da raiz do seu projeto. Aqui está a <a href="https://www.npmjs.com/package/@parfuemerie-douglas/scaffolder-backend-module-azure-repositories">página do plugin</a>.</p><pre>yarn --cwd packages/backend add @parfuemerie-douglas/scaffolder-backend-module-azure-repositories</pre><p>Depois, adicione o código abaixo ao arquivo packages/backend/src/index.ts:</p><pre>// Azure DevOps<br>backend.add(import(&#39;@parfuemerie-douglas/scaffolder-backend-module-azure-repositories&#39;))</pre><h3>Crie o template para uso pelo Backstage</h3><p>Agora que temos o Backstage pronto para falar com o Azure DevOps e, além disso, os plugins necessários instalados, vamos criar o template, que nada mais é que o formulário que receberá os dados do requisitante para provisionamento do recurso. Vou deixar um modelo de template bem simples, em que o usuário será solicitado a dizer o próprio nome e o nome do grupo de recursos que deseja que seja criado.</p><p>Uma das coisas com a qual mais tive dificuldade foi conseguir encontrar as informações necessárias para conseguir chegar ao resultado esperado usando o template. Aqui segue um modelo de template bem simples.</p><pre># Template for creating a new Azure DevOps repository and pushing a new Backstage component to it.<br><br>apiVersion: scaffolder.backstage.io/v1beta3<br>kind: Template<br>metadata:<br>  name: azure-repo-demo<br>  title: Azure Repository Test<br>  description: Clone and push to an Azure repository example.<br>spec:<br>  owner: parfuemerie-douglas<br>  type: service<br><br>  parameters:<br>    - title: Fill in some steps<br>      required:<br>        - name<br>      properties:<br>        name:<br>          title: RG Name<br>          type: string<br>          description: Choose a unique resource-group name.<br><br>  steps:<br>    - id: cloneAzureRepo<br>      name: Clone Azure Repo<br>      action: azure:repo:clone<br>      input:<br>        remoteUrl: &quot;https://&lt;MY_AZURE_ORGANIZATION&gt;@dev.azure.com/&lt;MY_AZURE_ORGANIZATION&gt;/&lt;MY_AZURE_PROJECT&gt;/_git/&lt;MY_AZURE_REPOSITORY&gt;&quot;<br>        branch: &quot;main&quot;<br>        targetPath: ./sub-directory<br><br>    - id: fetch<br>      name: Template Skeleton<br>      action: fetch:template<br>      input:<br>        url: https://dev.azure.com/&lt;MY_AZURE_ORGANIZATION&gt;/&lt;MY_AZURE_PROJECT&gt;/_git/&lt;MY_AZURE_REPOSITORY&gt;?path=/terraform/base<br>        targetPath: ./sub-directory/terraform/changed<br>        replace: true<br>        values:<br>          name: ${{ parameters.name }}<br><br>    - id: pushAzureRepo<br>      name: Push to Remote Azure Repo<br>      action: azure:repo:push<br>      input:<br>        branch: &lt;MY_AZURE_REPOSITORY_BRANCH&gt;<br>        sourcePath: ./sub-directory<br>        gitCommitMessage: Add ${{ parameters.name }} project files<br><br>    - id: pullRequestAzureRepo<br>      name: Create a Pull Request to Azure Repo<br>      action: azure:repo:pr<br>      input:<br>        sourceBranch: &lt;MY_AZURE_REPOSITORY_BRANCH&gt;<br>        targetBranch: &quot;main&quot;<br>        repoId: &lt;MY_AZURE_REPOSITORY&gt;<br>        title: ${{ parameters.name }}<br>        project: &lt;MY_AZURE_PROJECT&gt;<br>        organization: &lt;MY_AZURE_ORGANIZATION&gt;<br>        description: &quot;This is a pull request from Backstage&quot;<br>        supportsIterations: false<br><br>  output:<br>    links:<br>      - title: Repository<br>        url: &quot;dev.azure.com?owner=&lt;MY_AZURE_PROJECT&gt;&amp;repo=&lt;MY_AZURE_REPOSITORY&gt;&amp;organization=&lt;MY_AZURE_ORGANIZATION&gt;&quot;<br>      - title: Open in catalog<br>        icon: catalog<br>        entityRef: ${{ steps.register.output.entityRef }}</pre><blockquote><em>⚠️</em><strong><em>Nota Importante sobre os templates</em></strong><em>⚠️:</em></blockquote><blockquote><em>Quando utilizamos caminho relativo na tratativa de arquivos no Backstage, ele </em><strong><em>sempre</em></strong><em> levará como local de partida o local de onde </em><strong><em>o template foi importado</em></strong><em>.</em></blockquote><blockquote><em>Em outras palavras, ele sempre concatenará o caminho que você informar com o caminho de onde o template foi importado. Dessa forma, ou você mantém os arquivos a serem tratados no mesmo local do arquivo de onde importou o template ou utiliza uma url de um lugar externo, que foi a abordagem que usei aqui na ação </em><em>fetch:template. Mais sobre isso pode ser visto </em><a href="https://backstage.io/docs/features/software-templates/"><em>aqui</em></a><em> e </em><a href="https://backstage.io/docs/tooling/cli/templates/"><em>aqui</em></a><em>.</em></blockquote><p>Voltando ao nosso processo, crie o arquivo do template no Azure DevOps (substituindo os campos devidos) e então vá até o Backstage e siga o mesmo processo de importação que fizemos antes no teste de integração. Na hora em que for importar o template, pode ser que se depare com o erro abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*JVxiztT8ulx43FhK.png" /><figcaption>Erro ao aplicar o template</figcaption></figure><p>Caso isso aconteça, o motivo é o Backstage, que não está permitindo que recursos do tipo <strong>Template</strong> sejam importados. Para corrigir, edite o arquivo app-config.yaml, adicionando Template na lista allow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*qLibSphLINM8ZrvK.png" /><figcaption>Habilitando template</figcaption></figure><p>Uma vez importado o template, ele deve aparecer no menu <strong>Create…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g_9VCp5GMOI25MiN.png" /><figcaption><em>Novo template disponível</em></figcaption></figure><h3>Crie o código Terraform</h3><p>Ok, agora que sabemos que o Backstage e Az DevOps estão conversando, vamos criar um código simples, que vai ser usado pela nossa pipeline para criar um recurso no Azure. Não há nada mais simples que um grupo de recursos, então vamos por este caminho.</p><p>O código mínimo para que isto funcione segue abaixo:</p><pre>provider &quot;azurerm&quot; {<br>  features {}<br>}<br><br>resource &quot;azurerm_resource_group&quot; &quot;example&quot; {<br>  name     = &quot;${{ values.name }} &quot;<br>  location = &quot;&lt;AZ_LOCATION&gt;&quot;<br>}</pre><p>⚠️ Eu não estou usando aqui uma conta de armazenamento para que você guarde o estado do seu Terraform! Para ambientes de produção, sugiro armazenar o estado em algum lugar seguro.</p><p>Atenção para a variável values.name, pois ela será preenchida pelo valor que vier do Backstage. Aqui estamos fazendo um exemplo bem simples, usando somente uma variável, mas extrapole essa ideia para qualquer código que você queira executar.</p><p>Uma vez criado o código terraform, vamos fazer o upload dele para o nosso repositório do Azure DevOps.</p><p>💡 <strong>Importante</strong>: como a ideia é que o Backstage faça a tratativa deste arquivo e depois faça o upload e subsequente criação de um Pull Request de código, este (contendo a variável values.name) será substituído pelo valor que virá do Backstage, tornando o código <strong>não-reutilizável</strong>. Para evitar isso, vamos separar o código com a variável, que chamaremos de base, do código que terá a variável preenchida, que chamaremos de changed, para facilitar. Assim, sempre teremos um lugar com o código pronto para ser utilizado.</p><p>Abaixo segue a abordagem que entendo ser a mais simples, mas fique a vontade para adaptar à sua necessidade:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*8jv4QvMTWisG2LVB.png" /><figcaption>Arquivos Terraform</figcaption></figure><h3>Crie a pipeline para execução do código</h3><p>Por último, vamos criar uma pipeline que será disparada cada vez que houver uma alteração no código. Isso só acontecerá quando alguém aprovar o pull request que o Backstage criará.</p><h4>Crie uma conexão de serviço</h4><p>Uma conexão de serviço é obrigatória para que o Azure DevOps possa criar recursos na Azure.</p><p>1. No menu à esquerda, clique em <strong>Service connections</strong> e então clique em <strong>Create service connection</strong>. Então, no painel à direita, selecioneo tipo <strong>Azure resource Manager</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ede74OmDJVraoJr9.png" /><figcaption>Criando conexão de serviço</figcaption></figure><p>2. Você precisará se autenticar na Azure para autorizar a conexão. Siga o processo e preencha o panel à esquerda:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*Nhh8uOsjpI7xzjK_.png" /><figcaption>Configurando conexão</figcaption></figure><p>3. Se tudo correu adequadamente, você verá a conexão criada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*-SB1f9uRMprnWad6.png" /><figcaption>Conexão criada</figcaption></figure><h4>Crie a pipeline no Azure DevOps</h4><ol><li>Vá até o Azure DevOps, em Pipelines. Então clique em <strong>Create Pipeline</strong>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x1IW4F1MjHlBRKpv.png" /><figcaption>Criando pipeline</figcaption></figure><p>2. Selecione o local onde está seu código:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*ZAAZd6j3UHKBdK1N.png" /><figcaption>Selecionando local do repositório</figcaption></figure><p>3. Selecione o repositório em questão:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*kTfLZXiqkBMRfcXA.png" /><figcaption>Selecione o repositório em questão</figcaption></figure><p>4. Selecione a opção de yaml já existente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*GBfjBWBsU9wtrgJt.png" /><figcaption>Selecionando opção</figcaption></figure><p>5. Cole o yaml abaixo, subtituindo os valores necessários (mesmo que você não armazene o estado do terraform em algum lugar, você terá que informar estes dados para usar a ação TerraformTaskV4@4):</p><pre>trigger:<br>- main<br><br>pool:<br>  vmImage: ubuntu-latest<br><br>steps:<br>- task: TerraformTaskV4@4<br>  displayName: Terraform Init<br>  inputs:<br>    provider: &#39;azurerm&#39;<br>    command: &#39;init&#39;<br>    backendServiceArm: &#39;&lt;SERVICE_CONNECTION_NAME&gt;&#39;<br>    backendAzureRmResourceGroupName: &#39;&lt;AZ_RG_NAME&gt;&#39;<br>    backendAzureRmStorageAccountName: &#39;&lt;AZ_SA_NAME&gt;&#39;<br>    backendAzureRmContainerName: &#39;&lt;AZ_SA_CONTAINER_NAME&gt;&#39;<br>    backendAzureRmKey: &#39;&lt;AZ_KEY_NAME&gt;&#39;<br>    workingDirectory: $(System.DefaultWorkingDirectory)/terraform/changed<br><br>- task: TerraformTaskV4@4<br>  displayName: Terraform Validate<br>  inputs:<br>    provider: &#39;azurerm&#39;<br>    command: &#39;validate&#39;<br>    workingDirectory: $(System.DefaultWorkingDirectory)/terraform/changed<br><br>- task: TerraformTaskV4@4<br>  displayName: Terraform Plan<br>  inputs:<br>    provider: &#39;azurerm&#39;<br>    command: &#39;plan&#39;<br>    environmentServiceNameAzureRM: &#39;&lt;SERVICE_CONNECTION_NAME&gt;&#39;<br>    workingDirectory: $(System.DefaultWorkingDirectory)/terraform/changed<br><br>- task: TerraformTaskV4@4<br>  displayName: Terraform Apply<br>  inputs:<br>    provider: &#39;azurerm&#39;<br>    command: &#39;apply&#39;<br>    workingDirectory: &#39;$(System.DefaultWorkingDirectory)/terraform/changed&#39;<br>    environmentServiceNameAzureRM: &#39;&lt;SERVICE_CONNECTION_NAME&gt;&#39;</pre><h3>Teste Final</h3><p>Bom, com tudo no lugar, agora podemos finalmente testar todo o nosso ambiente. Vá até o Backstage, clique em <strong>Create…</strong>, informe o nome do grupo de recursos que deseja criar e confirme. Isso deve fazer com que o Backstage baixe o código, adicione os dados que você informou e crie um pull-request lá no Azure DevOps, que você terá de aprovar. Uma vez aprovado, a pipeline deve ser executada automaticamente. Vamos ver isso acontecer?</p><ol><li>Vá até o template e coloque o nome que deseja para o grupo de recursos:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HCKH9Dn8STzDAnXK.png" /><figcaption>Nome do RG</figcaption></figure><p>2. Revise o que digitou:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FfjoUfiGrEdiS4vD.png" /><figcaption>Validando informações</figcaption></figure><p>3. Se tudo ok, confirme e aguarde a execução:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xpqLvyUNLWfXaT0I.png" /><figcaption>Execução completa</figcaption></figure><p>4. Após a execução, vá ao Azure DevOps e veja o Pull Request criado. Você pode, inclusive, validar os arquivos que foram alterados e incluídos no PR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wcwX7_0jEr-Owvng.png" /><figcaption>Pull Requests</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KBuiOT-_0LRmF7Dc.png" /><figcaption>Arquivos alterados</figcaption></figure><p>5. Se tudo estiver ok, aprove o PR e complete-o.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*52HPidu4IjhaZlEl.png" /><figcaption>Aprovação do PR</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/0*gJ8tyeQIHJN8lzCE.png" /><figcaption>Completando o merge</figcaption></figure><p>Aqui é interessante falar que fica muito a gosto do freguês o modelo de setup. Pode ser que a sua empresa prefira não ter aprovação. Ou pode ser que até queira ter mais de uma aprovação. Para todos estes cenários você deverá ajustar o ambiente à necessidade. O intuito aqui era mostrar o conceito e a forma de colocá-lo em prática.</p><p>6. Depois de aprovada a alteração, vá até a pipeline e acompanhe o resultado. Ela deve executar sem problemas e criar o seu recurso no Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KTcMt6ssAUC2-ooM.png" /><figcaption>Pipeline</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/0*RC8NbWgGJHT4rm6s.png" /><figcaption>Execução da pipeline</figcaption></figure><p>Se tudo correu conforme o esperado, você deve ver seu recurso criado na console da Azure.</p><h3>Conclusão</h3><p>Neste post, você aprendeu como integrar o Backstage ao Azure DevOps e configurar um fluxo automatizado para provisionamento de recursos. Exploramos desde a configuração do PAT, a integração do Backstage com o Azure DevOps, até a validação da conexão com um template de exemplo.</p><p>Com essa base, você pode expandir essa implementação para atender às necessidades específicas do seu ambiente, automatizando ainda mais o processo de gerenciamento de infraestrutura.</p><p>Agora, é sua vez de explorar novas possibilidades e adaptar esse fluxo para tornar o desenvolvimento e a operação mais eficientes.</p><p>Caso tenha dúvidas ou sugestões, compartilhe nos comentários!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe10f45376e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication on Backstage with MS Entra ID]]></title>
            <link>https://medium.com/@lfmmeier/authentication-on-backstage-with-ms-entra-id-a6147510a582?source=rss-3b52148ccc9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6147510a582</guid>
            <category><![CDATA[identity-provider]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[microsoft-entra-id]]></category>
            <category><![CDATA[backstage]]></category>
            <dc:creator><![CDATA[Luiz Meier]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 19:31:27 GMT</pubDate>
            <atom:updated>2025-02-07T19:33:27.953Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Configure the Entra ID as an IDP on Backstage, centralizing the users authentication.</em></p><p>[<a href="https://medium.lmeier.net/autentica%C3%A7%C3%A3o-no-backstage-com-ms-entra-id-1895af41ec1b">Leia em Português</a>]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqRb4MktkLaanYGE0gxvMA.png" /><figcaption>Generated by DALL-E</figcaption></figure><p><em>Note: if you are not a Medium member, you can check this content </em><a href="https://blog.lmeier.net/posts/authentication-backstage-entra-id-en/"><em>here</em></a><em>.</em></p><p>I’ve been hearing for a while about how Backstage is a revolutionary tool and how it can give developers more freedom when requesting cloud resources.</p><p>If you are a DevOps or cloud operator, you’ve likely encountered a situation where you receive a ticket to provision a resource but can’t always deliver it as quickly as the squad expects.</p><p>I had to explore how Backstage works to address this exact challenge. What I discovered is that, while the tool is powerful, its documentation is not the most user-friendly.</p><p>Since I found it difficult to locate online resources on authentication with Entra ID, I decided to create this post explaining what I believe is the simplest way to set it up. This tutorial will guide you through setting up Backstage from scratch and configuring Microsoft Entra ID as its identity provider (IDP) for secure and efficient authentication.</p><h3>What is the Backstage?</h3><p>According to their official <a href="https://backstage.io/docs/overview/what-is-backstage/">description</a>:</p><blockquote><a href="https://backstage.io/">Backstage</a> is an open source framework for building developer portals. Powered by a centralized software catalog, Backstage restores order to your microservices and infrastructure and enables your product teams to ship high-quality code quickly — without compromising autonomy.</blockquote><blockquote>Backstage unifies all your infrastructure tooling, services, and documentation to create a streamlined development environment from end to end.</blockquote><p>💡<strong><em>Note: </em></strong>Backstage is entirely <strong>developer-focused</strong>. If you, like me, come from an infrastructure background, you may find it challenging since all configurations are done through system files — there is no admin interface for managing users, permissions, integrations, or plugins.</p><h4>Step 1: Start a new Backstage Instance</h4><p>The setup <a href="https://backstage.io/docs/getting-started/">documentation </a>is quite simple and self-explanatory, so I will let you follow those steps on your own.</p><p>Once the initial setup is completed, you should be able to run the application locally:</p><pre>yarn dev</pre><p>You can then access Backstage locally at http://localhost:3000, signing in as a <strong>guest user</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*nKU1yomd3UnfC3keVDm6SQ.png" /><figcaption>Backstage’s home page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*tc1XzOoPuYKTmn7ySNrFHQ.png" /><figcaption>Guest home page</figcaption></figure><p>💡 <strong>Guest access is meant for development purposes only and is not recommended for production.</strong> However, if you still want to enable full guest access, you can find the documentation <a href="https://backstage.io/docs/auth/guest/provider/">here</a>.</p><h4>Step 2: Create an App Registration on Entra ID</h4><p>To enable authentication, you must create an <strong>App Registration</strong> in <strong>Microsoft Entra ID</strong>, which will be used by Backstage. The documentation to create the resource is on <a href="https://backstage.io/docs/auth/microsoft/provider">this</a> page.</p><p>1️⃣To start, go to the corresponding menu for Entra ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*lM0m-QVHxSQU_6fyp43T_A.png" /><figcaption>Selecting Entra ID</figcaption></figure><p>2️⃣Then select App Registrations, then click New registration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6jiA4VRJZLmT1RJMLh7tlw.png" /><figcaption>Creating a new app</figcaption></figure><p>3️⃣Choose the appropriate settings for your use case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b12ekJ4caLTaXsWq-11rUg.png" /><figcaption>Creating app registration</figcaption></figure><p>For development, use http://localhost:7007/api/auth/microsoft/handler/frame as the <strong>redirect URL</strong>. (You can add additional URLs for production later.)</p><p>4️⃣Go to Manage &gt; API Permissions and add the following Delegated permissions to Microsoft Graph:</p><ul><li>email</li><li>offline_access</li><li>openid</li><li>profile</li><li>User.Read</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*RPgX7l0AnLDVqmNtOSykMA.png" /><figcaption>Applying permissions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*4JDMpPp-k-COip-YPuHIyA.png" /><figcaption>Selecting permissions</figcaption></figure><h4>Step 3: Configure Backstage to use Entra ID</h4><p>Add your <strong>App Registration</strong> details to the app-config.yaml file, located in your project&#39;s root directory.</p><pre>auth:<br>  environment: development<br>  providers:<br>    microsoft:<br>      development:<br>        clientId: ${AZURE_CLIENT_ID}<br>        clientSecret: ${AZURE_CLIENT_SECRET}<br>        tenantId: ${AZURE_TENANT_ID}<br>        domainHint: ${AZURE_TENANT_ID}<br>        signIn:<br>          resolvers:<br>            # See https://backstage.io/docs/auth/microsoft/provider#resolvers for more resolvers<br>            - resolver: userIdMatchingUserEntityAnnotation</pre><p>📌 The values for clientId, tenantId, and domainHint can be found on the <strong>Overview</strong> page of your App Registration in Entra ID.</p><p>📌 The clientSecretis created under <strong>Certificates &amp; Secrets</strong>.</p><p>⚠️ <strong>Security Warning:</strong> Never store clientSecret directly in the code. Use <strong>environment variables</strong> for production environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*tud8UJ9tFCj1vvxp2LCkTw.png" /><figcaption>clientId, tenantId and domainHint</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*jh3GfcC0P3HzR0JeWNu_eQ.png" /><figcaption>Creating password (clientSecret)</figcaption></figure><h4>Step 4: Configure the backend</h4><p>Install the Microsoft provider module by running the following command in the project’s root directory:</p><pre>yarn --cwd packages/backend add @backstage/plugin-auth-backend-module-microsoft-provider</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*z7Pqhqoq5yiSp3LkYwxuRg.png" /><figcaption>Installing module</figcaption></figure><p>Then, edit packages/backend/src/index.ts and add the line to import the module. The goal is to have something similar to this:</p><pre>import { createBackend } from &#39;@backstage/backend-defaults&#39;;<br><br>const backend = createBackend();<br><br>...<br><br>// microsoft provider<br>// See https://backstage.io/docs/auth/microsoft/provider<br>backend.add(import(&#39;@backstage/plugin-auth-backend-module-microsoft-provider&#39;));<br><br>...<br><br>backend.start();</pre><h4>Step 5: Configure the Frontend</h4><p><a href="https://backstage.io/docs/auth/#sign-in-configuration">This</a> page contains the documentation to add the IDP to the frontend. To do so, modify the file packages/app/src/App.tsx in order to take two actions:</p><ol><li>Import a component;</li><li>Add the MS Entra ID button in the GUI.</li></ol><p>To make it easier, the code excerpt below includes the changes already in place. Identify and replace the code as needed:</p><pre>import { microsoftAuthApiRef } from &#39;@backstage/core-plugin-api&#39;;<br><br>const app = createApp({<br>  apis,<br>  bindRoutes({ bind }) {<br>    bind(catalogPlugin.externalRoutes, {<br>      createComponent: scaffolderPlugin.routes.root,<br>      viewTechDoc: techdocsPlugin.routes.docRoot,<br>      createFromTemplate: scaffolderPlugin.routes.selectedTemplate,<br>    });<br>    bind(apiDocsPlugin.externalRoutes, {<br>      registerApi: catalogImportPlugin.routes.importPage,<br>    });<br>    bind(scaffolderPlugin.externalRoutes, {<br>      registerComponent: catalogImportPlugin.routes.importPage,<br>      viewTechDoc: techdocsPlugin.routes.docRoot,<br>    });<br>    bind(orgPlugin.externalRoutes, {<br>      catalogIndex: catalogPlugin.routes.catalogIndex,<br>    });<br>  },<br>  components: {<br>    SignInPage: props =&gt; (<br>      &lt;SignInPage<br>        {...props}<br>        providers={[<br>          &#39;guest&#39;,<br>          {<br>            id: &#39;microsoft-auth-provider&#39;,<br>            title: &#39;Microsoft&#39;,<br>            message: &#39;Sign in using EntraID&#39;,<br>            apiRef: microsoftAuthApiRef,<br>          },<br>        ]}<br>      /&gt;<br>    ),<br>  },<br>});</pre><p>Once this is done, you should see the <strong>Microsoft login button</strong> on the Backstage UI.</p><p>🚨 However, authentication will <strong>fail</strong> at this point because Backstage does not recognize the user in its catalog. This leads us to the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*wWC-Bw-cOTAIbJtr9Rm-yQ.png" /><figcaption>Authentication error</figcaption></figure><h4>Step 6: Add Users to the Backstage Catalog</h4><p>For this tutorial, we will <strong>manually create a user</strong> in the catalog. However, you can automate user ingestion via <strong>Microsoft Graph</strong> (check documentation <a href="https://backstage.io/docs/integrations/azure/org/">here</a>).</p><p>Edit the file examples/org.yaml, adding the following snippet at the end:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CJZlAodFth8t6zMjoCscOA.png" /><figcaption>User information</figcaption></figure><pre>apiVersion: backstage.io/v1alpha1<br>kind: User<br>metadata:<br>  name: johndoe<br>  annotations:<br>    graph.microsoft.com/user-id: aaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa<br>spec:<br>  profile:<br>    displayName: John Doe<br>    email: johndoe@mydomain.com<br>  memberOf:<br>    - guests</pre><p>📌 <strong>Notes:</strong></p><ul><li>metadata.name: Mail nickname (value before @yourdomain.com).</li><li>metadata.annotations.graph.microsoft.com/user-id: Object IDof the user.</li><li>displayName: Full name of the user.</li><li>email: Full email address.</li></ul><h4>Final Thoughts</h4><p>If everything is configured correctly, you should now be able to <strong>run Backstage locally</strong> and authenticate via Entra ID. 🎉</p><p>🚀 <strong>Next Steps:</strong> In the upcoming post, we’ll explore <strong>integrating Backstage with Azure DevOps</strong> and setting up templates to further automate your developers’ workflows.</p><p>📩 <strong>Questions or suggestions? Drop them in the comments!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6147510a582" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autenticação no Backstage com MS Entra ID]]></title>
            <link>https://medium.com/@lfmmeier/autentica%C3%A7%C3%A3o-no-backstage-com-ms-entra-id-1895af41ec1b?source=rss-3b52148ccc9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1895af41ec1b</guid>
            <category><![CDATA[microsoft-entra-id]]></category>
            <category><![CDATA[autenticação]]></category>
            <category><![CDATA[identity-provider]]></category>
            <category><![CDATA[backstage]]></category>
            <dc:creator><![CDATA[Luiz Meier]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 19:30:52 GMT</pubDate>
            <atom:updated>2025-02-07T19:33:17.549Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Configure o Entra ID como IDP no Backstage, centralizando a autenticação de usuários.</em></p><p>[<a href="https://medium.lmeier.net/authentication-on-backstage-with-ms-entra-id-a6147510a582">Read in English</a>]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqRb4MktkLaanYGE0gxvMA.png" /><figcaption>Generated by DALL-E</figcaption></figure><p><em>Obs.: se você não é um membro Medium, pode acessar este conteúdo </em><a href="https://blog.lmeier.net/posts/autenticacao-backstage-entra-id-pt-BR/"><em>aqui</em></a><em>.</em></p><p>Há algum tempo venho ouvindo sobre como o Backstage é uma ferramenta revolucionária e como pode ajudar a dar mais liberdade aos desenvolvedores na solicitação de recursos em nuvem.</p><p>Se você é um DevOps ou operador de nuvem, com certeza já passou pela situação de receber um ticket para provisionar algum recurso, mas nem sempre consegue entregá-lo na velocidade esperada pela squad.</p><p>Tive o desafio de entender como o Backstage funciona para atender exatamente esse tipo de demanda. O que descobri é que, apesar de a ferramenta ser poderosa, sua documentação não é das mais amigáveis.</p><p>Como tive dificuldades para encontrar recursos sobre autenticação com o Entra ID, resolvi criar este post explicando o que considero a maneira mais simples de configurá-lo. Este tutorial guiará você na configuração do Backstage do zero e na integração com o Microsoft Entra ID como provedor de identidade (IDP) para garantir autenticação segura e eficiente.</p><h4>O que é o Backstage?</h4><p>De acordo com a <a href="https://backstage.io/docs/overview/what-is-backstage">descrição</a> inicial:</p><blockquote><a href="https://backstage.io/">Backstage</a> é uma estrutura de código aberto para construção de portais de desenvolvedores. Alimentado por um catálogo de software centralizado, o Backstage restaura a ordem de seus microsserviços e infraestrutura e permite que suas equipes de produto enviem códigos de alta qualidade rapidamente, sem comprometer a autonomia.<br>O Backstage unifica todas as ferramentas, serviços e documentação de sua infraestrutura para criar um ambiente de desenvolvimento simplificado de ponta a ponta.</blockquote><p>💡 <strong>Nota:</strong> o Backstage é totalmente <strong>focado em desenvolvedores</strong>. Se você, assim como eu, vem da área de infraestrutura, pode estranhar o fato de que toda a configuração é feita via arquivos de sistema — não há uma interface administrativa para gerenciar usuários, permissões, integrações ou plugins.</p><h4>Passo 1: Iniciar uma nova instância do Backstage</h4><p>A documentação de <a href="https://backstage.io/docs/getting-started/">configuração</a> é bastante simples e autoexplicativa, então deixarei que você siga esses passos por conta própria.</p><p>Após concluir a configuração inicial, você deve ser capaz de executar a aplicação localmente:</p><pre>yarn dev</pre><p>Você pode então acessar o Backstage localmente em http://localhost:3000, entrando como <strong>usuário convidado</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*nKU1yomd3UnfC3keVDm6SQ.png" /><figcaption>Página inicial do Backstage</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tc1XzOoPuYKTmn7ySNrFHQ.png" /><figcaption>Página inicial de convidado</figcaption></figure><p>💡 <strong>O acesso de convidado é destinado apenas para desenvolvimento e não é recomendado para produção.</strong> No entanto, se desejar habilitá-lo, consulte a documentação <a href="https://backstage.io/docs/auth/guest/provider/">aqui</a>.</p><h4>Passo 2: Criar um App Registration no Entra ID</h4><p>Para ativar a autenticação, você deve criar um <strong>App Registration</strong> no <strong>Microsoft Entra ID</strong>, que será utilizado pelo Backstage. A documentação para criação do recurso está <a href="https://backstage.io/docs/auth/microsoft/provider">nesta</a> página.</p><p>1️⃣ Para iniciar, acesse o Entra ID no portal do Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lM0m-QVHxSQU_6fyp43T_A.png" /><figcaption>Selecionando o MS Entra ID</figcaption></figure><p>2️⃣Selecione App registrations e clique em New registration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*6jiA4VRJZLmT1RJMLh7tlw.png" /><figcaption>Criando um novo aplicativo</figcaption></figure><p>3️⃣Selecione a opção que melhor se adequa a você:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*b12ekJ4caLTaXsWq-11rUg.png" /><figcaption>Criação do app registration</figcaption></figure><p>Para desenvolvimento, utilize <a href="http://localhost/">http://localhost</a>:7007/api/auth/microsoft/handler/frame como <strong>URL de redirecionamento</strong> (você pode adicionar URLs adicionais para produção depois).</p><p>4️⃣Vá em Manage &gt; API Permissions e adicione as permissões a seguir como Delegated ao Microsoft Graph :</p><ul><li>email</li><li>offline_access</li><li>openid</li><li>profile</li><li>User.Read</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPgX7l0AnLDVqmNtOSykMA.png" /><figcaption>Adicionando permissões</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*4JDMpPp-k-COip-YPuHIyA.png" /><figcaption>Selecionando permissões</figcaption></figure><h4>Passo 3: Configurar o Backstage para usar o Entra ID</h4><p>Adicione os dados do seu app ao arquivo app-config.yaml, localizado na raiz do seu projeto.</p><pre>auth:<br>  environment: development<br>  providers:<br>    microsoft:<br>      development:<br>        clientId: ${AZURE_CLIENT_ID}<br>        clientSecret: ${AZURE_CLIENT_SECRET}<br>        tenantId: ${AZURE_TENANT_ID}<br>        domainHint: ${AZURE_TENANT_ID}<br>        signIn:<br>          resolvers:<br>            # See https://backstage.io/docs/auth/microsoft/provider#resolvers for more resolvers<br>            - resolver: userIdMatchingUserEntityAnnotation</pre><p>📌 Os valores para clientId, tenantId e domainHint podem ser encontrados na <strong>página Overview</strong> do seu App Registration no Entra ID.<br>📌 O clientSecreté gerado na seção <strong>Certificates &amp; Secrets</strong>.</p><p>⚠️ <strong>Aviso de Segurança:</strong> Nunca armazene clientSecret diretamente no código. Utilize <strong>variáveis de ambiente</strong> em produção.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tud8UJ9tFCj1vvxp2LCkTw.png" /><figcaption>clientId, tenantId e domainHint</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jh3GfcC0P3HzR0JeWNu_eQ.png" /><figcaption>Criando a senha (clientSecret)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPTGunU9hQB7YsDUTiAw5A.png" /><figcaption>Copiando senha</figcaption></figure><h4>Passo 4: Configurar o backend</h4><p>Aqui iremos instalar o módulo microsoft-provider. Para isso, executemos o comando abaixo na raiz do projeto:</p><pre>yarn --cwd packages/backend add @backstage/plugin-auth-backend-module-microsoft-provider</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7Pqhqoq5yiSp3LkYwxuRg.png" /><figcaption>Instalando provedor</figcaption></figure><p>Em seguida, edite packages/backend/src/index.ts e adicione a linha para importar o módulo. O objetivo é ter algo parecido com o código abaixo.</p><pre>import { createBackend } from &#39;@backstage/backend-defaults&#39;;<br><br>const backend = createBackend();<br><br>...<br><br>// microsoft provider<br>// See https://backstage.io/docs/auth/microsoft/provider<br>backend.add(import(&#39;@backstage/plugin-auth-backend-module-microsoft-provider&#39;));<br><br>...<br><br>backend.start();</pre><h4>Passo 5: Configurar o frontend</h4><p><a href="https://backstage.io/docs/auth/#sign-in-configuration">Esta</a> página contém a documentação para adicionar o IDP ao frontend. Para fazer isso, vamos alterar o arquivo packages/app/src/App.tsx e tomar duas ações:</p><ol><li>Importar um componente;</li><li>Adicionar o botão de login via Entra ID à interface gráfica.</li></ol><p>Para facilitar, vou colocar o trecho já pronto para evitar erros na hora de colar. Identifique o trecho e o substitua pelo abaixo:</p><pre>import { microsoftAuthApiRef } from &#39;@backstage/core-plugin-api&#39;;<br><br>const app = createApp({<br>  apis,<br>  bindRoutes({ bind }) {<br>    bind(catalogPlugin.externalRoutes, {<br>      createComponent: scaffolderPlugin.routes.root,<br>      viewTechDoc: techdocsPlugin.routes.docRoot,<br>      createFromTemplate: scaffolderPlugin.routes.selectedTemplate,<br>    });<br>    bind(apiDocsPlugin.externalRoutes, {<br>      registerApi: catalogImportPlugin.routes.importPage,<br>    });<br>    bind(scaffolderPlugin.externalRoutes, {<br>      registerComponent: catalogImportPlugin.routes.importPage,<br>      viewTechDoc: techdocsPlugin.routes.docRoot,<br>    });<br>    bind(orgPlugin.externalRoutes, {<br>      catalogIndex: catalogPlugin.routes.catalogIndex,<br>    });<br>  },<br>  components: {<br>    SignInPage: props =&gt; (<br>      &lt;SignInPage<br>        {...props}<br>        providers={[<br>          &#39;guest&#39;,<br>          {<br>            id: &#39;microsoft-auth-provider&#39;,<br>            title: &#39;Microsoft&#39;,<br>            message: &#39;Sign in using EntraID&#39;,<br>            apiRef: microsoftAuthApiRef,<br>          },<br>        ]}<br>      /&gt;<br>    ),<br>  },<br>});</pre><p>Com isto feito já é possível ver que o botão de autenticação via Entra ID está disponível na interface.</p><p>🚨 Contudo, a autenticação falhará, pois o Backstage não é capaz de reconhecer o usuário no catálogo. Isso nos leva ao próximo passo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWC-Bw-cOTAIbJtr9Rm-yQ.png" /><figcaption>Erro para autenticar</figcaption></figure><h4>Passo 6: Adicionar usuários ao catálogo do Backstage</h4><p>Para o propósito deste post, vamos <strong>criar um usuário manualmente</strong> no catálogo. Entretanto, você pode automatizar o processo de ingestão de usuários utilizando o Microsoft Graph (confira a documentação <a href="https://backstage.io/docs/integrations/azure/org/">aqui</a>).</p><p>Edite o arquivo examples/org.yaml, adicionando o trecho abaixo ao final do arquivo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJZlAodFth8t6zMjoCscOA.png" /><figcaption>Dados do usuário</figcaption></figure><pre>---<br>apiVersion: backstage.io/v1alpha1<br>kind: User<br>metadata:<br>  name: johndoe<br>  annotations:<br>    graph.microsoft.com/user-id: aaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa<br>spec:<br>  profile:<br>    displayName: John Doe<br>    email: johndoe@mydomain.com<br>  memberOf:<br>    - guests</pre><p>📌 Notas<strong>:</strong></p><ul><li>metadata.name: é o valor de Mail nickname, ou o valor antes de @seudominio.com;</li><li>metadata.annotations.graph.microsoft.com/user-id: é o valor de Object ID;</li><li>displayName: nome do usuário;</li><li>email: endereço de email completo</li></ul><h4>Considerações Finais</h4><p>Se tudo configurado corretamente, você poderá <strong>rodar o Backstage localmente</strong> e se autenticar via Entra ID. 🎉</p><p>🚀 <strong>Próximos Passos:</strong> no próximo post, vamos explorar a <strong>integração do Backstage com o Azure DevOps </strong>e criar e configurar templates para automatizar ainda mais a experiência dos desenvolvedores.</p><p>📩 <strong>Perguntas ou sugestões? Deixe nos comentários!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1895af41ec1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Usando API para Monitorar IPSec da Palo Alto]]></title>
            <link>https://medium.com/@lfmmeier/usando-api-para-monitorar-ipsec-da-palo-alto-ba02edb91c31?source=rss-3b52148ccc9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba02edb91c31</guid>
            <category><![CDATA[monitoramento]]></category>
            <category><![CDATA[túnel]]></category>
            <category><![CDATA[palo-alto]]></category>
            <category><![CDATA[ipsec]]></category>
            <category><![CDATA[vpn]]></category>
            <dc:creator><![CDATA[Luiz Meier]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 11:44:32 GMT</pubDate>
            <atom:updated>2025-01-21T14:06:16.761Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Um guia para monitorar o status dos seus túneis IPSec</em></p><p><em>Read in </em><a href="https://medium.lmeier.net/monitoring-palo-alto-firewalls-using-api-187df8b30aa6"><em>English</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*x-abeT4uj2zf2PMX.jpeg" /><figcaption>Gerado pelo DALL-E</figcaption></figure><p><em>Se você não é um membro Medium, pode conferir este conteúdo </em><a href="https://blog.lmeier.net/posts/usando-api-para-monitorar-ipsec-da-palo-alto/"><em>aqui</em></a><em>.</em></p><p>Quando se trata de monitoramento de rede, <strong>SNMP</strong> é, de longe, um dos protocolos mais utilizados. É simples de ter visibilidade de tráfego e status de interfaces somente coletando dados da base de dados das OIDs relacionadas à conectividade. Entretanto, nem todos os fabricantes disponibilizam o monitoramento de interfaces virtuais (como túneis IPSec) da mesma maneira das interfaces físicas. A Palo Alto é um destes casos. Se você consultar a documentação (disponível <a href="https://knowledgebase.paloaltonetworks.com/KCSArticleDetail?id=kA10g000000ClgECAS">aqui</a>), verá que o status dos túneis IPSec é monitorado somente via traps SNMP, e não coletas.</p><p>Sendo assim, neste post vou endereçar <strong>como monitorar o status de túneis IPSec</strong> utilizando chamadas API ao invés de SNMP, quando o último não é uma opção.</p><p>Para contornar isso, desenvolvi um script em Python que se utiliza da <strong>API </strong>da Palo Alto para capturar o status dos túneis IPSec. Apesar deste script ter sido primariamente para ser integrado com o <strong>Zabbix</strong>, pode ser adaptado para qualquer outra ferramenta de monitoramento. Se você estiver interessado em como o monitoramento dinâmico do Zabbix funciona (LLD), recomendo dar uma olhada nos meus posts anteriores para mais detalhes.</p><h3>Porque Não Podemos Usar SNMP Neste Caso?</h3><p>O SNMP funciona capturando informações de uma árvore de dados hierárquica, que é atualizada continuamente pelo sistema operacional. Ferramentas de monitoramento como o Zabbix ou Prometheus coletam estes dados periodicamente. Por exemplo, você pode listar todas as interfaces de um dispositivo utilizando o simples comando (assumindo que você está usando a comunidade padrão public):</p><pre>snmpwalk -v 3c public 1.2.3.4 ifname</pre><p>Isto retornará uma lista com todas as interfaces, incluindo as <strong>interfaces túnel</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*XKGGDG3oVCcXYKmw9nsaug.png" /><figcaption>Lista padrão de interfaces em um dispositivo Palo Alto</figcaption></figure><p>Apesar do SNMP trazer todas as interfaces listadas em Network &gt; Interface &gt; Tunnel, ele não monitora os túneis IPSec em Network &gt; IPSec Tunnels, e é aqui que está o grande problema:</p><ul><li>Interfaces túnel são virtuais e não refletem o real estado do túnel IPSec. Mesmo que o IPSec venha a ficar <strong>offline, </strong>a interface túnel associada a ele continuará a ser exibida como <strong>operacional</strong>.</li></ul><h4>Demonstrando o problema</h4><p>Para o propósito deste post, criei uma interface IPSec falsa chamada Mediume a conectei à interface tunnel.1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*oErkmKjngiiRk-ECjmDfkA.png" /><figcaption>Lista das interfaces túnel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*-W20OQCbR7wClGpGMj3OaQ.png" /><figcaption>Lista dos túneis IPSec</figcaption></figure><p>Se agora listarmos as interfaces novamente, veremos que a interface IPSec Medium não é listada, diferente da interface tunnel.1 que, sim, é listada normalmente. Por padrão, o protocolo SNMP coloca um número de indexação logo após o nome da interface. Este número é incrementado a cada nova interface criada.</p><pre>snmpwalk -v 2c -c public 1.2.3.4 ifname</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*R7rV6QV1uhJRJ9IM.png" /><figcaption>Lista de interfaces mostrando tunnel.1</figcaption></figure><p>Se usarmos o SNMP para consultar o status operacional da interfacetunnel.1, teremos o retorno incorreto <strong>“up”</strong>, mesmo sabendo que a interface mostra claramente que o túnel está offline (bolinha de status vermelha).</p><pre>snmpwalk -v 2c -c public 1.2.3.4 IF-MIB::ifOperStatus.400000001</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*NC5lPznoVGVKoiCM.png" /><figcaption>Status operacional da interface tunnel.1</figcaption></figure><h4>Resultado:</h4><p>A resposta SNMP permanece trazendo que o estado do túnel é operacional.</p><h3>Como Resolvemos Isso?</h3><p>Como dito acima, desenvolvi um script em Python que consome a <a href="https://docs.paloaltonetworks.com/pan-os/11-1/pan-os-panorama-api">API do firewall</a> para coletar a informação precisa sobre o estado do túnel. Este script suporta duas ações principais:</p><ol><li><strong>Descoberta</strong>: Imprime todos os túneis em formato JSON, ideal para o processo de LLD do Zabbix;</li><li><strong>Status</strong>: Retorna um valor numérico de estado para um túnel específico.</li></ol><p>Você pode encontrar e baixar o script <a href="https://github.com/LuizMeier/Zabbix/blob/master/Palo%20Alto/IPSec_PT-BR.py"><strong>aqui</strong></a>. Abaixo seguem alguns exemplos de como utilizá-lo:</p><p><strong>a) Modo de descoberta</strong></p><p>A ação discovery lista todas as interfaces IPSec em formato JSON:</p><pre>script.py 1.2.3.4 usuario senha discovery</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*NLX_UWnFa5rcL3KoMquqCw.png" /><figcaption>Saída do script</figcaption></figure><p>Esta saída JSON é bastante poderosa para ferramentas como Zabbix para dinamicamente criar itens de monitoramento através do processo LLD. Se tivéssemos mais de uma interface, a saída seria algo assim:</p><pre>{<br>  &quot;data&quot;: [<br>    {&quot;{#TUNNELNAME}&quot;: &quot;Tunnel1&quot;},<br>    {&quot;{#TUNNELNAME}&quot;: &quot;Medium&quot;},<br>    {&quot;{#TUNNELNAME}&quot;: &quot;BackupTunnel&quot;}<br>  ]<br>}</pre><p><strong>b) Modo status</strong></p><p>Para coletar o estado específico de um túnel, use a ação status:</p><pre>script.py 1.2.3.4 username password status &#39;Medium&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*dWQHS0BHeuMAZP-rGU98CA.png" /><figcaption>Estado do túnel</figcaption></figure><p>Os possíveis valores são:</p><ul><li>1 — O túnel <strong>está </strong>operacional;</li><li>2 — O túnel <strong>não está</strong> online.</li></ul><h3>Integrando o Script com o Zabbix</h3><p>Você pode, facilmente, integrar o script à sua ferramenta de monitoramento. Para o Zabbix, eu seguiria o seguinte caminho:</p><ol><li><strong>Integração de Descoberta</strong>: use a ação discovery para criar itens de monitoramento de túneis de forma dinâmica.</li><li><strong>Monitoramento de Estado</strong>: regularmente colete o estado do túnel, utilizando a ação status.</li><li><strong>Disparo de Alertas</strong>: configure alertas, caso seu túnel venha a ficar indisponível.</li></ol><h3>Conclusão</h3><p>Aproveitar a API da Palo Alto te dá a opção de contornar as limitações de coletas SNMP e aumentar a visibilidade dos seus túneis IPSec. Essa estratégia pode ser estendida para outros cenários em que a informação que você precisa só está disponível via API.</p><p>Espero que você ache este post útil para o seu ambiente de monitoramento. Se tiver questões ou sugestões, sinta-se à vontade para compartilhar nos comentários. Grande Abraço!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba02edb91c31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Palo Alto Firewalls using API]]></title>
            <link>https://medium.com/@lfmmeier/monitoring-palo-alto-firewalls-using-api-187df8b30aa6?source=rss-3b52148ccc9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/187df8b30aa6</guid>
            <category><![CDATA[ipsec]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[tunnel]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[palo-alto]]></category>
            <dc:creator><![CDATA[Luiz Meier]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 21:31:32 GMT</pubDate>
            <atom:updated>2025-01-21T14:12:12.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monitoring Palo Alto IPSec using API</h3><p><em>A Guide to Monitor the Status of Your IPSec Tunnels with Python and API integration</em></p><p><em>Também disponível em </em><a href="https://medium.lmeier.net/usando-api-para-monitorar-ipsec-da-palo-alto-ba02edb91c31"><em>Português</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_hQEHuIQD-6gYGVWNEzfg.jpeg" /><figcaption>Generated by DALL-E</figcaption></figure><p><em>If you are not a Medium member, check this </em><a href="https://blog.lmeier.net/posts/monitoring-palo-alto-firewalls-using-api/"><em>here</em></a><em>.</em></p><p>When it comes to networking monitoring, <strong>SNMP </strong>is by far one of the most used protocols. It is easy to have visibility over traffic and interface’s status polling network-related OIDs from SNMP database. However, not all vendors make it available to monitor virtual interfaces (such as IPSec) the same way as they do with physical ones. Palo Alto is one of these. If you check their documentation (linked <a href="https://knowledgebase.paloaltonetworks.com/KCSArticleDetail?id=kA10g000000ClgECAS">here</a>) it will tell you that the IPSec tunnel status is monitored only via SNMP traps and not queries.</p><p>So, in this post I will address how to <strong>monitor IPSec tunnel status </strong>using API instead of SNMP, when the latter is not an option.</p><p>To work around this, I developed a script in Python that leverages the Palo Alto <strong>API </strong>to retrieve IPSec tunnel status. While this script was primarily designed for <strong>Zabbix</strong>, it can easily be adapted for other monitoring tools. If you’re interested in dynamic monitoring approaches like Low-Level-Discovery (LLD), I recommend checking my previous posts for more details.</p><h3>Why Can’t We Use SNMP in This Case?</h3><p>SNMP works by querying a hierarchical tree of information that the device’s OS continuously updates. Monitoring tools like Zabbix or Prometheus collect this data periodically. For example, we can list all interfaces of a device using the following command (assuming you’re using the default publicSNMP community):</p><pre>snmpwalk -v 2c public 1.2.3.4 ifname</pre><p>That would return a list of all interfaces, including <strong>tunnel interfaces</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*XKGGDG3oVCcXYKmw9nsaug.png" /><figcaption>Default interface list on Palo Alto Firewalls</figcaption></figure><p>While SNMP retrieves tunnel interfaces listed in the GUI under Network &gt; Interface &gt; Tunnel, it does not monitor IPSec Tunnels located under Network &gt; IPSec Tunnels, and here lies the critical issue:</p><ul><li><strong>Tunnel interfaces are virtual </strong>and do not reflect the real status of the IPSec tunnel. Even if the IPSec tunnel goes <strong>down</strong>, the associated tunnel interface will still appear as <strong>operational</strong>.</li></ul><h4>Demonstrating the problem</h4><p>For the purpose of this post I created a fake IPSec tunnel called Medium and linked it to the tunnel.1 interface<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*oErkmKjngiiRk-ECjmDfkA.png" /><figcaption>List of tunnel interfaces</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-W20OQCbR7wClGpGMj3OaQ.png" /><figcaption>List of IPSec tunnels</figcaption></figure><p>If we list the interfaces again, you will see that the MediumIPSec interface is not listed, which is not the case of the <strong>listed </strong>tunnel.1 interface. By default, SNMP puts an indexer number after the interface’s name. This number is incremented each time a new interface is created.</p><pre>snmpwalk -v 2c -c public 1.2.3.4 ifname</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*-o6uuAir09GY6mWR9dRe2w.png" /><figcaption>Interface list with tunnel.1</figcaption></figure><p>If we use SNMP to query the operational status of the tunnel.1 interface, it will incorrectly show “<strong>up</strong>”, even though the <strong>GUI </strong>clearly indicates the tunnel is down (via the red status icon).</p><pre>snmpwalk -v 2c -c public 1.2.3.4 IF-MIB::ifOperStatus.400000001</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*H5YcgBJNZgh6ffCNFnz_cA.png" /><figcaption>tunnel.1 operational status</figcaption></figure><h4>Result:</h4><p>The SNMP response still reports the tunnel as operational.</p><h3>How do we solve that?</h3><p>As said above, I developed a Python script that consumes <a href="https://docs.paloaltonetworks.com/pan-os/11-1/pan-os-panorama-api">the firewall’s API</a> to retrieve the precise tunnel status. The script supports two main actions:</p><ol><li><strong>Discovery</strong>: Outputs all tunnels in JSON format, ideal for Zabbix’s Low-Level Discovery (LLD).</li><li><strong>Status</strong>: Returns a numeric status of a specific tunnel.</li></ol><p>You can find and download the script <a href="https://github.com/LuizMeier/Zabbix/blob/master/Palo%20Alto/IPSec_EN.py"><strong>here</strong></a>. Below are examples of how to use it:</p><p><strong>a) Discovery Mode</strong></p><p>The discovery action lists all tunnels in JSON format:</p><pre>script.py 1.2.3.4 username password discovery</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*NLX_UWnFa5rcL3KoMquqCw.png" /><figcaption>Discovery output</figcaption></figure><p>This JSON output is very powerful for tool like Zabbix to create dynamic monitoring items through LLD. If I had more than one interfaces, it would output something like this:</p><pre>{<br>  &quot;data&quot;: [<br>    {&quot;{#TUNNELNAME}&quot;: &quot;Tunnel1&quot;},<br>    {&quot;{#TUNNELNAME}&quot;: &quot;Medium&quot;},<br>    {&quot;{#TUNNELNAME}&quot;: &quot;BackupTunnel&quot;}<br>  ]<br>}</pre><p><strong>b) Status Mode</strong></p><p>To check the status of a specific tunnel, use the status action:</p><pre>script.py 1.2.3.4 username password status &#39;Medium&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*dWQHS0BHeuMAZP-rGU98CA.png" /><figcaption>Tunnel status</figcaption></figure><p>The possible outputs are:</p><ul><li>1 - Tunnel is up</li><li>2 - Tunnel is down</li></ul><h3>Integrating the Script with Zabbix</h3><p>You can easily integrate the script into your monitoring workflow. For Zabbix, here’s a single outline:</p><ol><li><strong>Discovery Integration</strong>: use the discovery action to create dynamic tunnel items using LLD.</li><li><strong>Status Monitoring</strong>: regularly query tunnel status using the status action.</li><li><strong>Trigger Alerts</strong>: set up triggers to alert you if any tunnel goes down.</li></ol><h3>Conclusion</h3><p>By leveraging Palo Alto’s API, you an go around the limitations of SNMP queries and improve the visibility of your IPSec tunnels. This approach can be extended to other scenarios where the information you need available via API only.</p><p>I hope you find this solution helpful for your monitoring setup. If you have questions or suggestions, feel free to share them in the comments. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=187df8b30aa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fortinet vs. Palo Alto: Automatizando Balanceamento de Carga]]></title>
            <link>https://medium.com/@lfmmeier/fortinet-vs-palo-alto-automatizando-balanceamento-de-carga-30c7ee4d1aac?source=rss-3b52148ccc9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/30c7ee4d1aac</guid>
            <category><![CDATA[firewall]]></category>
            <category><![CDATA[ngfw]]></category>
            <category><![CDATA[palo-alto]]></category>
            <category><![CDATA[fortinet]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[Luiz Meier]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 21:11:36 GMT</pubDate>
            <atom:updated>2025-01-21T14:05:21.100Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Como criar uma solução customizada para balanceamento de carga utilizando a API da Palo Alto em conjunto com ferramentas de monitoramento, como o Zabbix.</em></p><p><a href="https://medium.lmeier.net/fortinet-vs-palo-alto-automating-load-balancing-fbcc8db1a09c"><em>Read in english</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yS3HQfJ7m7GCulDi" /><figcaption>Generated by AI</figcaption></figure><p><em>Se você não é um membro Medium, pode conferir este conteúdo </em><a href="https://blog.lmeier.net/posts/fortinet-vs-palo-alto-automatizando-balanceamento-de-carga/"><em>aqui</em></a><em>.</em></p><p>Não há dúvida de que Fortinet e Palo Alto são alguns dos maiores fabricantes no mercado de firewalls de nova geração (NGFW). Enquanto cada fabricante brilha em diferentes áreas, é natural que um engenheiro compare as capacidades de cada um, até encontrar a que melhor se encaixa em suas necessidades, especialmente quando se trata de adotar uma nova solução no seu ambiente.</p><p>Ao me deparar com uma migração de Fortinet para Palo Alto, uma das capacidades a que não me atentei adequadamente foi o balanceamento de carga. Neste post, vou focar em um dos motores de rede que entendo mais úteis da Fortinet, o <strong>Virtual Server </strong>(solução nativa para balanceamento de carga), e falar um pouco como a Palo Alto lida com esse tipo de tarefa. Vou falar sobre uma automação customizada como sugestão para contornar algumas das limitações da Palo Alto, quando se fala em balanceamento/distribuição de tráfego.</p><p><strong>O Balanceamento de Carga Nativo da Fortinet</strong></p><p>Traduzindo literalmente da <a href="https://docs.fortinet.com/document/fortigate/6.2.16/cookbook/713497/virtual-server">documentação </a>do fabricante,</p><blockquote>“O balanceador de carga de servidor contém todas as capacidades de uma solução de balanceamento de carga. Você pode balancear tráfego entre vários servidores de backens, baseado em múltiplas opções de balanceamento: estático (failover), round robin e por peso (baseado na saúde e performance do servidor, incluindo o tempo de ida e volta e número de conexões).”</blockquote><p>O recurso suporta uma variedade de protocolos, como HTTP, HTTPS, IMAPS, POP3S, SMTPS, SSL/TLS e portas genéricas UDP/TCP, além de IP. Adicionalmente, suporta persistência de sessão usando ID de sessão SSL, cookies HTTP injetados ou persistência de host HTTP/HTTPS. O FortiOS também possibilita proteção contra ataques de downgrade de protocolo.</p><p>Essa flexibilidade, somada à habilidade de configurar checagem de saúde (ping, TCP ou requisições HTTP/S), oferece ao engenheiro todas as ferramentas necessárias para assegurar-se de que seus serviços estão disponíbeis e funcionais. A solução da Fortinet é robusta, suportando até 10.000 servidores virtuais nas soluções de grande porte.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*oIp6rFrCr2XOuKx1.png" /><figcaption>Balanceador de carga da Fortinet</figcaption></figure><h3>Palo Alto: Uma Solução Sólida, com uma Desvantagem</h3><p>Quando mudei para Palo Alto, Percebi que a solução <a href="https://docs.paloaltonetworks.com/pan-os/10-1/pan-os-networking-admin/nat/configure-nat/configure-destination-nat-using-dynamic-ip-addresses">oferece um recurso similar de NAT um-para-muitos</a>, incluindo distribuição de tráfego, como round robin. Entretanto, as checagens de saúde da Palo Alto são limitadas quando comparadas às da Fortinet. Especificamente, a Palo Alto não te permite criar checagens de saúde customizadas mais avançadas.</p><p>Por exemplo, em determinados ambientes, enviar um ping para um servidor pode não ser suficiente para determinar se um serviço está funcional. Checagens mais complexas, como verificar uma resposta HTTP específica ou o funcionamento de uma porta customizada, pode ser necessária, e infelizmente a Palo Alto não suporta esse nível de customização.</p><p>Essa limitação me levou a procurar por uma forma de contornar isso para melhorar as checagens de ambiente.</p><h3>Automação Customizada Usando a API da Palo Alto</h3><p>Apesar da falta de checagens avançadas da Palo Alto, a API pode ser aproveitada para criar uma solução customizada. Depois de discutir o assunto com alguns colegas, e pesquisando opções por aí, adaptei (do meu colega <a href="https://github.com/rbonicenha">Bonicenha</a>)um script em Python para poder fazer minhas checagens e automatizar a remoção/adição do servidor em um grupo de endereços que esteja atrás do NAT de destino.</p><p>O script usa a API da Palo Alto para modificar o grupo de endereços, baseado na saúde do servidor, assegurando que nós não funcionais sejam removidos do grupo e que, em contrapartida, os funcionais sejam adicionados.</p><p>Você pode baixar o script <a href="https://github.com/LuizMeier/Zabbix/tree/master/Palo%20Alto">daqui</a>, e se estiver curioso, fique a vontade para explorar outros repositórios e conteúdos que existem lá. Da mesma forma, no repositório do <a href="https://github.com/rbonicenha">Bonicenha</a> você encontrará outros conteúdos sobre Palo Alto.</p><p>Aqui está um pequeno pedaço do script, mostrando as variáveis mandatórias:</p><pre>firewall = sys.argv[1]  # Endereço do firewall<br>action = sys.argv[2]    # Ação (up ou down)<br>group = sys.argv[3]     # Nome do grupo de endereços<br>host = sys.argv[4]      # Endereço do host a ser removido ou adicionado ao grupo<br>username = sys.argv[5]  # Usuário de acesso ao firewall<br>password = sys.argv[6]  # Senha para acesso ao firewall</pre><p>Você pode executar o script pela linha de comando, passando os parâmetros necessários na seguinte ordem:</p><pre>LB.py 1.2.3.4 up AddressGroup Host username password</pre><h3>Automatizando o processo com Zabbix</h3><p>Para automatizar o processo completamente, sugiro integrar o script no Zabbix, uma ferramenta bem popular de monitoramento. Aqui está como fazê-lo:</p><ol><li><strong>Crie um item de monitoramento</strong>, utilizando as métricas que você entende serem as mais relevantes pro seu ambiente (tempo de resposta HTTP, disponibilidade de porta, ping);</li><li><strong>Configure uma trigger</strong>, baseada nas métricas criadas para detectar quando um servidor não estiver mais funcional;</li><li><strong>Configure uma ação</strong> para ser executada quando a trigger disparar. Esta ação pode chamar o script em Python para remover o servidor indisponível do grupo de endereços;</li><li>A<strong>dicione uma ação de recuperação</strong> para retornar o servidor indisponível para produção assim que ele estiver disponível novamente.</li></ol><p>Essa solução provê uma maneira dinâmica e automatizada de gerenciar os servidores atrás do seu NAT, baseada em tempo real nas métricas da sua solução de monitoramento. Haverá um pequeno período de indisponibilidade entre a detecção da falha, a ação do script e o tempo de commit da ferramenta, mas essa é uma escolha ao trabalhar co as possibilidades atuais da Palo Alto.</p><h3>Últimas Conclusões</h3><p>Apesar da solução da Fortinet oferecer uma opção mais completa, a API da Palo Alto oferece um pouco de flexibilidade através da API, possibilitando algumas soluçõpes de contorno, usando um pouco de criatividade. Ao integrar uma ferramenta de monitoramento com um script customizado, você pode replicar algumas das funcionalidades que a solução não oferece nativamente e ter um balanceamento eficaz na sua infraestrutura.</p><p>Por último, tanto a Fortinet quanto a Palo Alto possuem suas vantagens, e a escolha entre elas vai depender das suas necessidades específicas. Se o balanceamento de carga for um pré-requisito, esteja preparado para ter que customizar algumas coisas se decidir ir pra Palo Alto.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30c7ee4d1aac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fortinet vs. Palo Alto: Automating Load Balancing]]></title>
            <link>https://medium.com/@lfmmeier/fortinet-vs-palo-alto-automating-load-balancing-fbcc8db1a09c?source=rss-3b52148ccc9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbcc8db1a09c</guid>
            <category><![CDATA[ngfw]]></category>
            <category><![CDATA[palo-alto]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[firewall]]></category>
            <category><![CDATA[fortinet]]></category>
            <dc:creator><![CDATA[Luiz Meier]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 21:11:34 GMT</pubDate>
            <atom:updated>2025-01-21T14:11:58.760Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to create a custom solution for load balancing in Palo Alto using API and monitoring tools like Zabbix.</em></p><p><a href="https://medium.lmeier.net/fortinet-vs-palo-alto-automatizando-balanceamento-de-carga-30c7ee4d1aac"><em>Também disponível em Português</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CHgA0dQvwE6rQ_PE" /><figcaption>Generated by AI</figcaption></figure><p><em>If you are not a Medium member, check this </em><a href="https://blog.lmeier.net/posts/fortinet-vs-palo-alto-automating-load-balancing/"><em>here</em></a><em>.</em></p><p>There is no doubt that Fortinet and Palo Alto are some of the major players in the next-generation firewall (NGFW) market. While each vendor excels in different areas, it’s natural for engineers to compare features to find the best fit for their needs, especially when introducing a new firewall into their environment.</p><p>When transitioning from Fortinet to Palo Alto, one of the features I immediately missed was load balancing. In this post, I’ll focus on one of Fortinet’s useful network features, <strong>Virtual Server</strong> (its built-in load balancing solution), and discuss how Palo Alto handles similar tasks. I’ll also walk through a custom automation I developed to overcome some of the limitations in Palo Alto’s load balancing capabilities.</p><h3>Fortinet’s Native Load Balancing Features</h3><p>Describing directly from the vendor’s <a href="https://docs.fortinet.com/document/fortigate/6.2.16/cookbook/713497/virtual-server">documentation</a>,</p><blockquote>“The FortiOS server load balancing contains all the features of a server load balancing solution. You can balance traffic across multiple backend servers based on multiple load balancing schedules such as: static (failover), round robin, and weighted (based on the health and performance of the server including round trip time and the number of connections).”</blockquote><p>It supports a variety of protocols such as HTTP, HTTPS, IMAPS, POP3S, SMTPS, SSL/TLS, and generic TCP/UDP and IP. Additionally, session persistence is possible using SSL session IDs, injected HTTP cookies, or HTTP/HTTPS host persistence. FortiOS also provides protection from protocol downgrade attacks.</p><p>This flexibility, coupled with the ability to configure health probes (ping, TCP, or HTTP/S requests), gives engineers the tools to ensure their services are available and functioning. Fortinet’s solution is robust, even allowing up to 10,000 virtual servers on high-end systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oIp6rFrCr2XOuKx1.png" /><figcaption>Fortinet Load Balancing</figcaption></figure><h3>Palo Alto: A Solid Option with One Drawback</h3><p>When I moved to Palo Alto, I found that it <a href="https://docs.paloaltonetworks.com/pan-os/10-1/pan-os-networking-admin/nat/configure-nat/configure-destination-nat-using-dynamic-ip-addresses">offers a similar one-to-many destination NAT feature</a>, including traffic distribution options like round-robin. However, Palo Alto’s health probes are limited compared to Fortinet. Specifically, Palo Alto does not allow you to create custom health probes for advanced checks beyond simple ping tests.</p><p>For example, in some environments, pinging a server may not be enough to determine if a service is healthy. More complex checks, like verifying a specific HTTP response or checking a non-standard port, may be required. Unfortunately, Palo Alto does not offer this level of customization.</p><p>This limitation led me to search for a workaround to improve server health checks in my environment.</p><h3>Custom Automation with Palo Alto’s API</h3><p>Despite Palo Alto’s lack of advanced health probes, its powerful API can be leveraged to create a custom solution. After discussing this with colleagues and referencing some useful community posts, I adapted (from my colleague <a href="https://github.com/rbonicenha">Bonicenha</a>) a Python script to manage health checks and automate server removal/addition in the address group behind the destination NAT.</p><p>The script uses Palo Alto’s API to modify the address group based on server health, ensuring that non-functional servers are removed from the pool and functional servers are added back.</p><p>You can download it from <a href="https://github.com/LuizMeier/Zabbix/tree/master/Palo%20Alto">this </a>repository, and if you are curious, make yourself confortable to explore other scripts and repos there. Likewise, there will be other contents in the <a href="https://github.com/rbonicenha">Bonicenha</a>’s repository to help you with Palo Alto.</p><p>Here’s a snippet of the script, showing the mandatory variables:</p><pre>firewall = sys.argv[1]  # Firewall address<br>action = sys.argv[2]    # Action (up or down)<br>group = sys.argv[3]     # Address group name<br>host = sys.argv[4]      # Host to be removed or added to address group<br>username = sys.argv[5]  # Firewall&#39;s username<br>password = sys.argv[6]  # Firewall&#39;s password</pre><p>You can run the script from the command line, passing the necessary parameters in the following order:</p><pre>LB.py 1.2.3.4 up AddressGroup Host username password</pre><h3>Automating the Process with Zabbix</h3><p>To fully automate the process, I suggest you to integrate the script with Zabbix, a popular monitoring tool. Here’s how you can set it up:</p><ol><li><strong>Create a monitoring item</strong> using the metrics you feel are most relevant for server health (e.g., HTTP response time, port availability).</li><li><strong>Set up a trigger</strong> based on those metrics to detect when a server is no longer healthy.</li><li><strong>Configure an action</strong> to be executed when the trigger is fired. This action should call the Python script to remove the failing server from the address group.</li><li><strong>Add a recovery action</strong> to reinstate the server once it becomes healthy again.</li></ol><p>This solution provides a dynamic, automated way to manage your load-balanced servers based on real-time health metrics. Although there may be a slight delay between detecting an issue and completing the action, this is a tradeoff when working with Palo Alto’s current feature set.</p><h3>Final Thoughts</h3><p>While Fortinet’s native load balancing offers a more complete solution, Palo Alto’s flexibility through its API enables creative workarounds. By integrating a monitoring tool with a custom script, you can replicate some of the missing functionalities and ensure smooth load balancing across your infrastructure.</p><p>Ultimately, both Fortinet and Palo Alto have their strengths, and the choice between them will depend on your specific needs. If load balancing is a key factor, be prepared to implement custom solutions if you opt for Palo Alto.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbcc8db1a09c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>