<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Posts on With the head in the clouds</title>
        <link>https://www.lacabezaenlasnubes.es/en/posts/</link>
        <description>Recent content in Posts on With the head in the clouds</description>
        <generator>Hugo -- gohugo.io</generator>
        <language>en</language>
        <copyright>&lt;a href=&#34;https://creativecommons.org/licenses/by-nc/4.0/&#34; target=&#34;_blank&#34; rel=&#34;noopener&#34;&gt;CC BY-NC 4.0&lt;/a&gt;</copyright>
        <lastBuildDate>Sat, 24 Oct 2026 20:00:00 +0000</lastBuildDate>
        <atom:link href="https://www.lacabezaenlasnubes.es/en/posts/index.xml" rel="self" type="application/rss+xml" />
        
        <item>
            <title>Speed, urgency and reliability. Lessons from the Fujisan</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2026/10/speed-urgency-and-reliability.-lessons-from-the-fujisan/</link>
            <pubDate>Sat, 24 Oct 2026 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2026/10/speed-urgency-and-reliability.-lessons-from-the-fujisan/</guid>
            <description>It is 4:00 p.m. on September 8, 2024; the day is bright and clear. I´m leaving the majestic crater of Mount Fuji behind me, returning to the rim. From its 3,776-meter summit we can gaze out over kilometers upon kilometers of Japan in every direction. We reached the top after a good couple of hours of climbing, stopping by on the stations for some hot tea and even a pack of M&amp;amp;M´s, purchased back at around 2,800 meters.</description>
            <content type="html"><![CDATA[<p><img alt="peak_foto" src="/img/fujisan-crater.jpg"></p>
<p>It is 4:00 p.m. on September 8, 2024; the day is bright and clear. I´m leaving the majestic crater of Mount Fuji behind me, returning to the rim. From its 3,776-meter summit we can gaze out over kilometers upon kilometers of Japan in every direction. We reached the top after a good couple of hours of climbing, stopping by on the stations for some hot tea and even a pack of M&amp;M´s, purchased back at around 2,800 meters. Every mountain is a world in itself, and Fuji is quite different from Teide. They are all majestic, and Mount Fuji is no exception: an imposing vantage point visible, on a truly clear day, even from as far away as Chiba, as we were fortunate enough to discover a few days later. I am happy, absolutely elated; this is my second peak over 3,000 meters. Yet, amidst all the joy, the scenery, and my own repetitive, frequent remarks &ldquo;This isn&rsquo;t like Teide, is it? Though it does look a lot like Chinyero&rdquo; something has been gnawing at me for the last hour or so, though I can’t quite put my finger on what it is yet.</p>
<p>We reached the summit alongside a couple of French-speaking Canadians. We crossed paths with many people, including a group of highly motivated Japanese students who were cheering everyone on during the ascent, they were even wearing <em>hachimaki</em> and everything. And although I can speak a little bit of Japanese, we found it easier to communicate with the Canadians, using both English and French. Our climbing paces were more in sync, we shared the experience of being <em>gaijin</em>, and we had two languages ​​in common. (Note: I don’t speak French, but that’s one of the perks of having a French translator with you!)</p>
<p>And there we were, enjoying the summit, taking photos and the like. I can’t help it but my mind is already on the next milestone: the return journey. From the Fuji Subaru 5th Station, the way we came, following the Yoshida Trail, and the way we’ll be heading back&hellip; when does the last バス (<em>bus</em>) leave? It’s a little past four, and a foreboding shiver runs through me. I pull out my phone and check the photo I took of the bus schedule:</p>
<p><img alt="timetable_foto" src="/img/fujisan-timetable.jpg"></p>
<p>Oh, right. The last one leaves at 18:45. That gives us about two hours to complete the descent, the climb that took us over five hours. &ldquo;Not great, not terrible.&rdquo; I sound a bit worried as I say it. Besides, at the latitude of Mount Fuji, unlike in the Canary Islands, where you still have daylight well past 20:00 in September, here it means darkness. Suddenly, I’m gripped by a sense of urgency. If we don’t make it on time&hellip; well, who knows what that actually entails? Are there タクシー (<em>taxis</em>) at the 5th Station? And if there are, will we even be able to catch one? After all, it wasn’t just a handful of hikers we passed on the way up. We mention this to the Canadians, and after taking one last moment to soak in Japan’s <em>axis mundi</em>, we prepare for the descent. We make a pact with the Canadians: if we don’t make it in time, we’ll share a taxi to Fujiyoshida to split the cost.</p>
<p>And so we began the descent. Have I mentioned that Mount Fuji isn’t like Mount Teide? It consists primarily of dark, unstable volcanic gravel, what we call <em>picón</em>. It’s not the kind of terrain you can descend carelessly, unless you want to fall and end up going down very, very fast.</p>
<h2 id="the-need-for-speed">The Need for Speed</h2>
<p>We needed to move fast. We needed to move fast because there was a clear deadline, and the only way to meet it was to accelerate. This applies to the Fuji climb, but it also applies to most software releases, to any change that Product deems necessary: ​​Dev must rush to implement it, and Ops must rush to deploy it. This isn’t just about being in a hurry for the sake of it; it’s not rushing just to rush. There is a deadline to meet. And usually, that deadline isn’t arbitrary, missing it carries clear consequences. In the case of Mount Fuji, it could mean paying the extra cost for a taxi, or ending up stranded with no idea how to get back to your hotel. In the context of software, it could mean increased costs, reputational damage, or customer churn whether it’s a missed release, a hotfix that isn’t deployed on time, or a configuration change that arrives too late.</p>
<p>So, we had to speed up, move faster. The risk of not doing so was quite clear and significant. And I’m not just talking about missing out on a good soak in the hot, very hot, water of the hotel <em>onsen</em>, or skipping dinner&hellip; which, believe me, was a prospect that weighed more heavily on me than you might imagine. The thing is, as soon as I took my first few steps on that unstable gravel, I realized that rushing at any cost wouldn’t work. One slip, and the best-case scenario would be an embarrassing fall or a twisted ankle. It could be worse, though: acting foolishly at three thousand meters can end in a helicopter evacuation, which is incredibly expensive, and a completely ruined vacation. We’re talking about the difference between a minor incident (missing dinner) and a very high severity incident (breaking a leg and goodbye vacations).</p>
<p>In SRE and DevOps, meeting a deadline also carries risks: a poorly tested change can have an unexpected <em>blast radius</em> and a release that hasn&rsquo;t been thoroughly tested might end up introducing a bug more serious than the one it was intended to fix. If we focus on meeting a deadline at any cost, we may lose sight of something crucial to reliability: the price of meeting that deadline poorly can end up being far higher than the cost of missing it altogether.</p>
<p>So, on the descent from Mount Fuji, the plan was clear. Move as fast as we could, while staying safe, and if that meant missing our deadline rather than ending up on crutches, so be it. We kept up a good pace, a very decent pace in fact, but always one that allowed us to maintain our footing without slipping or skidding on the loose gravel. As the sky darkened, fog began to roll in, lapping at the lower slopes of the mountain. Instead of obsessing over how much ground we had left to cover, we simply focused on placing one foot firmly in front of the other, all while being careful not to wreck our knees from exhaustion, since pushing too hard in the mountains is another sure-fire way to end up with an injury. It was around 18:30 when we reached the Fuji Subaru Line 5th Station trailhead; from there, the path turned into a wide, straight dirt track with no further descent. My knees were aching, they’d really taken a beating, but we had made it!</p>
<p>&hellip; And there was a line of about fifty taxi drivers, with just as many others queuing up, at the trailhead on both sides of the road, waiting very respectfully. They saw us arrive, bowed in greeting, offered a subtle smile, and went right back to waiting as we walked past. I don’t mean to offend them, but I must confess that the image of vultures crossed my mind. So, we arrived, met our deadline, and then had to wait until 18:45, spending about ten minutes sitting in the dusk light, eating an energy bar and smiling. And then I laughed even harder, because if we hadn’t arrived on time, the problem wouldn’t have been finding a taxi, it would have been deciding which one of them to choose.</p>
<h2 id="move-fast-but-stay-safe">Move fast, but stay safe</h2>
<p>This is a principle I apply, and observe in SRE, whenever I can. The sense of urgency, or even the near-catastrophic feeling that arises when a deadline approaches, must not cause us to lose our cool. Moving faster might seem like the right approach, but if you end up with a broken leg, you’ve acted foolishly. Even if you didn’t actually break a leg or burn yourself out, only to realize that missing the deadline slightly while prioritizing safety wouldn’t have been catastrophic, you might still feel like a fool. Or, at least, you should. In mountaineering, just as in Site Reliability Engineering, it’s not only about speed, it’s about a tuple: (speed, safety). Moving at the maximum <em>safe</em> speed is the smartest approach, and the most reliable approach. It’s also smart to have a backup plan in case a deadline isn’t met. In my experience, most &ldquo;deadlines&rdquo; aren’t actually that full of <em>death</em>. As leaders and change managers, we must never be unjustified blockers, but we should be the ones who keep a cool head, making realistic assessments of operational risk and timing. That way, we ensure no one ends up with a broken leg, only to miss the deadline anyway.</p>
]]></content>
        </item>
        
        <item>
            <title>Pipelines that ask for help - Sending PagerDuty alerts from AzureDevops</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2025/06/pipelines-that-ask-for-help-sending-pagerduty-alerts-from-azuredevops/</link>
            <pubDate>Fri, 13 Jun 2025 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2025/06/pipelines-that-ask-for-help-sending-pagerduty-alerts-from-azuredevops/</guid>
            <description>For me, a pipeline is a sequential automation with a set of non-negotiable features. It&amp;rsquo;s not just about deploying new code; it&amp;rsquo;s about doing it in an automated and, above all, unattended manner. But here&amp;rsquo;s the crucial detail: for it to be truly unattended, you must be able to trust it.
Trusting doesn&amp;rsquo;t mean muttering &amp;ldquo;I did the best I could,&amp;rdquo; crossing your fingers, and side-eyeing it every time it runs, hoping it doesn&amp;rsquo;t fail.</description>
            <content type="html"><![CDATA[<p>For me, a <em>pipeline</em> is a sequential automation with a set of non-negotiable features. It&rsquo;s not just about deploying new code; it&rsquo;s about doing it in an automated and, above all, unattended manner. But here&rsquo;s the crucial detail: for it to be truly unattended, you must be able to trust it.</p>
<p>Trusting doesn&rsquo;t mean muttering &ldquo;I did the best I could,&rdquo; crossing your fingers, and side-eyeing it every time it runs, hoping it doesn&rsquo;t fail. For me, trusting means that when something goes wrong —and it will— I&rsquo;ll know instantly and will be able to take corrective action immediately. So, when we talk about automation, a non-negotiable feature is the ability to alert us to any unforeseen failures. This way, we don&rsquo;t have to constantly look over our shoulders.</p>
<p>Lets see how!</p>
<h2 id="wake-me-when-you-need-me">Wake me, when you need me</h2>
<p>In my work, most of our CI/CD automations are on <a href="https://azure.microsoft.com/products/devops/">Azure DevOps</a> and our paging system is <a href="https://www.pagerduty.com/">PagerDuty</a>. So, if I want to avoid constantly monitoring our automations and only get notified when something fails or the execution doesn&rsquo;t complete, the obvious solution is to combine both tools. This way, an error in the ADO pipelines will trigger a PagerDuty alert.</p>
<p>If you&rsquo;ve had the need to send a PagerDuty alert from Azure DevOps and were surprised by the lack of documentation, my implementation example might interest you.</p>
<h2 id="ansible---launch-a-pagerduty-alert">Ansible - Launch a PagerDuty Alert</h2>
<p>Since I work a lot with Ansible, my preference is for the Azure Devops pipeline to run an Ansible job responsible for triggering the page. The first thing I did, of course, was try not to reinvent the wheel and <a href="https://docs.ansible.com/ansible/latest/collections/community/general/pagerduty_alert_module.html">find a PagerDuty alert module</a> in the Ansible Community documentation.</p>
<p><strong>Disclaimer</strong>: What follows is my opinion on this module. If you liked it or found it useful, that&rsquo;s great.</p>
<p>At first, I tried using the module but given its unclear documentation, ambiguous parameter names, and —after looking a bit into its implementation— unnecessarily complex API calls, I opted for a simple solution that would cover my use case: I&rsquo;m going to send a request to the PagerDuty API to generate an alert.</p>
<p>So, I set out to create a playbook that simply triggers a PD when you invoke it. Of course, it&rsquo;s parameterizable.</p>
<pre tabindex="0"><code>---
- hosts: all
  gather_facts: false
  tasks:
    - name: Fire up a PD alert (URI version)
      ansible.builtin.uri:
        url: https://api.pagerduty.com/incidents
        method: POST
        body_format: json
        body:
          incident:
            type: incident
            title: &#34;Failure on Bounce pipeline execution for {{ env_name }}&#34;
            incident_key: ingincident_name
            escalation_policy:
              id: YTHGD
              type: escalation_policy_reference
            service:
              id: YUUTYU
              type: service_reference
        return_content: true  ## Being JSON, it will also be present in a json key in the dictionary of results
        status_code: 201
        headers:
          Authorization: &#34;Token token={{ pd_api_key }}&#34;
          Accept: &#34;application/vnd.pagerduty+json;version=2&#34;
      delegate_to: localhost
      run_once: true
</code></pre><p>We&rsquo;re going to need a <a href="https://support.pagerduty.com/main/docs/api-access-keys">token</a>, because the PagerDuty API won&rsquo;t pay much attention to us without it. I take advantage of Ansible&rsquo;s <code>uri</code> module, and by setting <code>body_format</code> as JSON, I can set the <code>body:</code> as a dictionary with the assurance that the module will convert it correctly. Let&rsquo;s describe the interesting parameters in detail:</p>
<ul>
<li><code>incident_key</code>: it doesn&rsquo;t need to be a unique value, but it should be descriptive.</li>
<li><code>escalation_policy</code>: we can easily find it by navigating to People-&gt;Escalation Policies in the PagerDuty portal, selecting the one we&rsquo;re interested in, and then looking at the URL. The end of the URL will be something like <code>escalation_policies/YTHGD</code>. That final value (<code>YTHGD</code>) is our escalation policy value.</li>
<li><code>service</code>: we obtain it in a similar way. We navigate to Services and extract <code>service-directory/YUUTYU</code> from the URL, keeping the final value.</li>
<li><code>Authorization</code> header: it has a predefined format: <code>&quot;Token token=$tokenvalue&quot;</code> to indicate that we are going to send a token that we will generate beforehand. In the example, it references an Ansible variable defined in another file (encrypted, of course!).</li>
<li><code>delegate_to</code>: we are going to delegate execution of this task to the machine that is running the Ansible playbook, and not to the hosts we have in our inventory, thats why we specify <code>localhost</code></li>
<li><code>run_once</code>: we are setting this to true so this task only runs once, no matter how many hosts we have in our inventory.</li>
</ul>
<p>The task is very straightforward and leverages a solid standard module. The last two parameters are to make sure of one thing and just one: We don´t wnat 40 PagerDuty alerts for a single pipeline that has failed and was set to run on 40 servers.</p>
<p>We now have our Ansible ready to trigger an alert when called, we just need that our pipeline knows when and how to call it.</p>
<h2 id="azure-devops---call-the-alert-job-if-something-is-not-right">Azure DevOps - Call the alert job if something is not right</h2>
<p>ADO pipelines are defined in <code>.yaml</code>. All we need is a condition that in natural language reads &ldquo;If any stage fails, the last stage that triggers an alert must execute&rdquo;. And here is when we find something interesting and funny about Azure DevOps: This final stage must have a dependency with ALL other stages, because ADO only checks in its <code>failed()</code> if between both stages there´s a direct dependency relation. We cannot establish transitive dependencies here. Lets see with the example:</p>
<pre tabindex="0"><code>- stage: Trigger_PD_on_fail
    displayName: &#34;Trigger a PD alert if any previous step in the pipeline has failed&#34;
    dependsOn:
      - Setup_stage
      - Prepare_stage3
      - Stage3
      - Final_stage
    condition: failed()
    jobs:
      - job: Trigger_PD_on_error
        displayName: &#34;Error detected, triggering PD alert&#34;
        pool:
          vmImage: ubuntu-22.04
        steps:
          - checkout: none
          - template: myplaybooks/ansible-fire-pd.yml
</code></pre><p>The stages defined in <code>dependsOn</code> are mere <em>placeholders</em>. With this, we can be sure the stage will only execute when any of the others it depends on (remember, must be all of them) does not execute correctly. Let´s see a few example runs:</p>
<h2 id="example">Example</h2>
<p>In this first one, all stages the alert depends on have ran correctly, nothing is triggered.</p>
<p><img alt="no pd launched" src="/img/ado_pd1.png"></p>
<p>And, in the opossite, when one fails -or is manually cancelled- our alert triggers ready to pound our <em>pager</em>.</p>
<p><img alt="no pd launched" src="/img/ado_pd2.png"></p>
<h2 id="conclusion">Conclusion</h2>
<p>I was surprised to not find many examples of triggering a PagerDuty alert from Azure DevOps, as they are two widely used tools in SRE and DevOps.</p>
<p>Being able to trust our automations so they are truly unattended should be one of our main goals. To me, a good philosophy is to strive for reliability but be confident that we´ll get an alert when they aren´t. This way, we can be more than kinda confident. We can <strong>trust</strong>.</p>
]]></content>
        </item>
        
        <item>
            <title>My first year as Tech Lead. Lessons learned and cheatsheet</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2024/10/my-first-year-as-tech-lead.-lessons-learned-and-cheatsheet/</link>
            <pubDate>Thu, 10 Oct 2024 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2024/10/my-first-year-as-tech-lead.-lessons-learned-and-cheatsheet/</guid>
            <description>I&amp;rsquo;ve been working as Tech Lead for an SRE team since September 2023. While I don’t think I have enough experience yet to teach anybody, I´ve learned a lot. An incredible amount, both on a technical level and in leadership. Here, soft skills are just as important as hard skills. I remember that when I got the offer, the first thing I did was look up as much information as I could.</description>
            <content type="html"><![CDATA[<p>I&rsquo;ve been working as Tech Lead for an SRE team since September 2023. While I don’t think I have enough experience yet to teach anybody, I´ve learned a lot. An incredible amount, both on a technical level and in leadership. Here, soft skills are just as important as hard skills. I remember that when I got the offer, the first thing I did was look up as much information as I could. What does it mean to be a Tech Lead? What does it mean to lead such a highly technical team? I found a lot and read a lot. Then, over the course of this first year, I learned even more. Little by little, just like with the technical side of my job, I started condensing quick notes, writing down keys that would trigger the stored content in my dicts. Without realizing it I ended up assembling a cheatsheet. And since this blog is all about sharing and giving back—to the Web and the world—byte by byte, I want to share my experience and that cheatsheet. Along with another reflection on leading a team.</p>
<h2 id="a-thought-on-my-journe-from-junior-to-tech-lead">A thought on my journe from Junior to Tech Lead</h2>
<p>I love reading, and I always say that I’m a frustrated historian. Around my early twenties I read The Art of War, and there was a quote that immediately stuck with me, forever: “He must be just, methodical, and reserved.” It really resonated with me, and in some way or another I’ve tried to apply it in what I do. How does a quote from over 2,500 years ago apply to an industry that’s not even 80 years old yet? Well, being methodical is incredibly useful in all things IT.</p>
<p>Being methodical means being well organized, designing a system, validating it, and applying it to then stick to it. Isn&rsquo;t that essentially what we do? A <em>rockstar</em> might be great, but if they&rsquo;re not consistent or organized, they’re not <em>as good as they could be</em>. And we all have stories of that <em>rockstar</em> who one day broke Production. In a moment of overload, emergency, or uncertainty, being methodical gives us the ability to respond, something that confusion and the unknown often strip away from us. A clear runbook that assumes zero prior knowledge when an alert is triggered, a framework for Incident Management during the critical early stages of an incident, a takeoff checklist to ensure we don’t miss anything when starting our shift… These are all examples of a methodical approach to something as chaotic as the work of Reliability Engineering. That’s why, in my experience, striving to be methodical has helped me handle both the technical and soft aspects of leadership. Going back to Sun Tzu’s quote and its parallel with IT: a methodical person adapts and improvises, but does so based on a system. Exactly as we should. As for the parts about being <em>just</em> and <em>reserved</em>, I’ll save them for a future post :p.</p>
<h2 id="my-reminder-cheatsheet-mode">My reminder, cheatsheet mode</h2>
<ul>
<li>The work of prioritizing, scheduling, and dispatching tasks/tickets has a huge impact on the team. And not doing it has twice the negative impact: bottlenecks, misalignment between the team&rsquo;s work and the client&rsquo;s priorities. And overload, whether it’s <a href="https://sre.google/workbook/overload/">real or perceived overload</a>.</li>
<li>Prioritize, then delegate and let the team do what they do best: their work. If you&rsquo;re micromanaging without needing to, there&rsquo;s a problem. If you have to micromanage because you can&rsquo;t delegate reliably, there&rsquo;s a problem.</li>
<li>As SREs, we can&rsquo;t be reluctant to change. We like it and we manage it. Finding balance between change and acceptable risk to stability is the key. A solid change management process is essential.</li>
<li>If you are not ON-CALL its fine to prioritize deep work and take more than 10 minutes to answer an email or message.</li>
<li>Finding bottlenecks in the team&rsquo;s workflow —first, find the KPIs to detect them— has a much greater impact than just resolving one or two stuck tickets.</li>
<li>A Tech Lead combines leadership and technical work. It allows you to lead from the front. It’s a unique opportunity to coach and support the growth of everyone. Win-win.</li>
<li>Always make time to work on the technical side. Don’t stop coding, don’t stop automating. Don’t stop applying new solutions. Never stop optimizing and solving problems.</li>
<li>But sometimes there isn’t time for the technical side, and that’s okay. You should only worry if it’s chronical (like a week without any time for it).</li>
<li>You are the bridge between the team and the client (whether internal or external). Sometimes it means being equidistant.</li>
<li>Pointing that something &ldquo;isn&rsquo;t right&rdquo; and just mentioning it doesn&rsquo;t help. Raising a complaint doesn&rsquo;t help. What works is detecting something that we believe can be improved, providing evidence and metrics for it; and presenting a solution in the same report.</li>
<li>EXTRA: This is a reminder much just for myself, but it might also work others who share my geeky-though-not-as-geeky-as-in-the-90s hobby, video games. “Leading is not an <a href="https://en.wikipedia.org/wiki/Real-time_strategy">RTS</a> with a minimap, nice interface, top-down vision and instant reaction times. Leading is an [FPS])https://en.wikipedia.org/wiki/First-person_shooter) where you need a clear vision using a limited field of view; then you explain and point out the objective. You must have confidence that it will be accomplished when the next moment requires you to look elsewhere, towards the next challenge.”</li>
</ul>
<h2 id="lets-talk-metrics">Let´s talk metrics</h2>
<p>SRE is a position that is very focused and based on metrics, it should be. Metrics are the foundation of observability. For me this doesn’t change when we’re trying to observe our teammates and our workload. But measuring the workload of SREs, in my experience, has a fundamental problem: we handle very diverse requirements, making it difficult to initially estimate the time or effort needed. There are routine decommissions that end up becoming true odysseys, and there are updates that lead to cascading requirements and need forking an unsupported library to update it…</p>
<p>As a result, I&rsquo;m afraid that the metrics I currently work with aren&rsquo;t as precise as I would like them to be. I’ll mention a few, very briefly to perhaps expand on this in a future post dedicated solely to metrics. My team and I work in Jira, but I will try to define them in a <em>vendor-agnostic</em> way.</p>
<ul>
<li><strong>Number of tickets assigned to the team (total) and to each member (value and % of the total):</strong> Observing how this number varies over time and among team members gives us a very basic idea of how balanced the workload is. It’s a key starting point. Moreover, a higher number of tickets leads to more task rotation and context switching. That’s where we start to lose a lot due to the context switching that causes residual attention.</li>
<li><strong>List of tickets ordered by priority or volume (%) of tickets at each priority level:</strong> This depends on how good we are at organizing and prioritizing tasks, as well as how good those assigning tasks are at giving them a real and honest priority. When everything is urgent, nothing is. Fortunately, in our case, I can prioritize based on customer feedback. The more high-priority tickets there are, the greater the risk of missing a deadline or causing an impact. Increasing the priority of something means lowering the priority of another, since both people and time are finite resources. If we&rsquo;ve seen that we can handle X high-priority tickets, the acceptance of another must be postponed, or one of the existing tickets has to be deprioritized.</li>
<li><strong>Mean Time To Resolution (MTTR):</strong> the time from when a request is formally accepted until it is resolved. In our case, due to the need to balance the technical aspect with scheduling during specific maintenance windows (and other factors like budget approvals and costs), it’s not as straightforward to measure or as informative. Additionally, the varying levels of complexity make it difficult to determine when something is taking longer than necessary. However, it can generally provide an idea of the team’s &ldquo;agility&rdquo; within the context of the organization.</li>
<li><strong>Average Age of tickets:</strong> I’m not a fan of averages for any statistics because they can be significantly skewed by outliers. Generally, the higher this average is, the more likely it is that we have many tickets taking longer than ideal or that we have a few that are dragging on for a very long time. Both situations need to be addressed. It can also provide a very generalized idea of whether the team is overwhelmed: if the average age of tickets is consistently increasing, it&rsquo;s very likely because we&rsquo;re getting requests constantly and there’s never enough time to work on the backlog. We become increasingly reactive and less proactive.</li>
<li><strong>Completed tickets, monthly:</strong> I hesitate to mention this because I don’t want to turn anyone into a ticket-closing machine. Because we are not machines and we are here to solve problems and manage change, not to close tickets. However, it does provide a very general and imprecise idea of the work pace. If we do good dispatching and the team has a balanced workload, the output should be similar. If not, we need to see if it’s because someone has much more complex and time-consuming tasks or if they’re going through a less productive period.</li>
<li><strong>Assigned tickets vs. completed tickets, monthly:</strong> Again, and having in mind the idea that we’re not ticket-completing machines, this provides a very basic idea of &ldquo;performance.&rdquo; In a well-balanced team, it should tend to be consistent. If at any point the trend becomes unbalanced (with many more assigned tickets than resolved), we might be overloading the team. Conversely, if we see that there are significantly fewer assigned and resolved tickets, we could have someone who is <em>idle</em>.</li>
</ul>
<h3 id="continuous-improvement">Continuous improvement</h3>
<p>I know that the above metrics are somewhat general and imprecise, and on their own they don’t convey much. However, combined, they can provide a general idea that allows us to know if we need to take action. Additionally, they are there to be refined over time because I believe in the principle of &ldquo;Done now is better than perfect later,&rdquo; which is nothing but iterative and continuous improvement. I have all these metrics on a dashboard that I’ve named &ldquo;Workload HUD&rdquo; with the sole intention of having a quick overview of how my team and I are managing our workload. I don’t like to guess or assume things; I prefer to measure them.</p>
]]></content>
        </item>
        
        <item>
            <title>Moving an Azure VM, with Azure Resource Mover or the easy way?</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2024/06/moving-an-azure-vm-with-azure-resource-mover-or-the-easy-way/</link>
            <pubDate>Wed, 26 Jun 2024 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2024/06/moving-an-azure-vm-with-azure-resource-mover-or-the-easy-way/</guid>
            <description>In Azure, once a VM is created it cannot be moved to another region. So in order to &amp;ldquo;move&amp;rdquo; a VM the real operation is to clone it and recreate it in the desired region, then delete the original. This is moving, exactly the same way as that teleport joke from SMBC. Although these steps can be done manually from Azure itself, they recommend using Azure Resource Mover, which as its name indicates is a wizard to help move Azure resources.</description>
            <content type="html"><![CDATA[<p>In Azure, once a VM is created it cannot be moved to another region. So in order to &ldquo;move&rdquo; a VM the real operation is to clone it and recreate it in the desired region, then delete the original. This is moving, exactly the same way as <a href="https://www.smbc-comics.com/comic/transporter-2">that teleport joke from SMBC</a>. Although these steps can be done manually from Azure itself, they recommend using <a href="https://azure.microsoft.com/products/resource-mover/">Azure Resource Mover</a>, which as its name indicates is a wizard to help move Azure resources. Move, not duplicate-and-delete-the-original, that&rsquo;s what the description says. It also says &ldquo;move your resources without problems&rdquo; That´s a point for their marketing team.</p>
<p>Although the process using AZCLI was pretty clear to me -and in fact it was recommended to me over ARM by some colleagues- last time I wanted to try ARM because it is the recommended option and had a promise of &ldquo;ease-of-use&rdquo; it offered. So I went for it. After all, the scenario was as basic as you can expect. Mind you, this is not a detailed guide to using Azure Resource Mover, it is an analysis of my experience with the tool, of the alternative way I ended up using and of my conclusions.</p>
<h2 id="the-scenario">The scenario</h2>
<p>Two VMs in one region (East US, for example) in a Resource Group with six other VMs in another region (Central US). You need to move the two in East US to Central. Both are domain joined and have only the OS disk. Nothing too fancy.</p>
<h2 id="using-azure-resource-mover">Using Azure Resource Mover</h2>
<p>The first thing that struck me is that Resource Mover has some <a href="https://learn.microsoft.com/en-us/azure/resource-mover/tutorial-move-region-virtual-machines#prerequisites">prerequisites</a> that seemed a bit overkill to me. You need to have owner privileges on the subscription. It seems it creates a System-Assigned Managed Identity at the subscription level. Once I validated the prerequisites, I decided to test first with only one of the two VMs so as not to complicate things.</p>
<p>The first step with Azure Resource Mover is to &ldquo;validate dependencies&rdquo;. That is, see how many resources have dependencies with the VM we want to move (moving being -remember- cloning and then deleting the original). It has an interface that detects dependencies as errors and reports them and allows us to resolve them and re-evaluate without canceling the operation. Some of the curious dependencies I found:</p>
<ul>
<li>I had to select only the VM, if I also selected its NIC, the Resource Mover recommended moving the rest of the associated resources to the new region, including the subnet. Because they became depencies on the NIC.</li>
<li>You cannot move from one region to the same Resource Group, since what it does is a copy, it will not allow two VMs with the same name in the same RG. As a workaround I decided to create a new Resource Group and a new VNET in the Central US region, and do a global peering between both VNETs. Moving the VMs to the original Resource Group could be done in a second step.</li>
<li>Since the disk was encrypted with keys managed by Azure, I had to resolve the dependency of having access to the Key Vault where the keys existed. I had to give access to the source Key Vaults to the VM subscription, and even then, it failed to work and I ended up <em>manually</em> copying the backups of the key and the secret to another destination Key Vault.</li>
</ul>
<p>Once dependencies are resolved, or bypassed, the change is ready to be &ldquo;committed&rdquo;, which means that it is validated but has not yet been made. Once it is made, we will see the copy of the VM appear in the destination, with the correct region. In my case, since it clones it and does not turn off the original (I did not turn it off either, to be fair) it could not join the new one to the domain because the original computer still existed. So another manual step was going to be to delete the computer object from the AD and then manually join this new VM to the domain.</p>
<p>After several manual steps, some of which I had never had to do using the &ldquo;manual&rdquo; way of moving VMs, I found myself with a cloned VM not domain-joined, and the original one still existing since I had not completed the last step, which is to delete the original resources. This is a step that must be taken in Azure Resource Mover and confirmed. The illusion that something is being &ldquo;moved&rdquo; is now gone, if it still existed in any way.</p>
<p>I decided not to complete the operation with Resource Mover, instead to retrace my steps and use the &ldquo;non-automated&rdquo; method which surprisingly has fewer manual steps.</p>
<h2 id="using-azcli">Using AZCLI</h2>
<p>I like SOPs (Standard Operating Procedures). I make a constant effort to convert any operation that is repeated and still done by hand into an SOP with automation and in this way I kill two birds with one stone: I reduce the <em>toil</em> and also the operation stops being something at the discretion of each operator/engineer to become a consensus of the organization that must be complied with and applied. We no longer check how the operator/engineer plans to do it, but if his operation is according with our SOP.</p>
<p>I&rsquo;m telling this because I was able to rely on automations I created as part of an SOP to decommission Azure VMs. In that process VM disks are converted to .VHD images and sent to a blob in a Storage Account. This will be relevant later, I promise.</p>
<p>Using AZCLI to move a VM is&hellip; much more immediate. It&rsquo;s still the same process, remember that you can&rsquo;t move VMs in Azure. They are &ldquo;teleported&rdquo; in the sense of the comic above: Cloned to the destination and the original is destroyed. This is exactly what we did with AZCLI. To clone a VM the easiest way, or one of the easiest, is to clone it from a snapshot of its system hard drive. However, I encountered problems changing the snapshot´s snapshot. In the docs I find references to move an <em>incremental</em> snapshot but not a complete one. You have to use another trick: Copy the snapshot as a .VHD and send it to a Storage Account blob in the region you want to move it to. Do you see how the backup automation I mentioned before helps now?</p>
<p>So it all went:</p>
<ol>
<li>Create snapshots of the OS disks of the two VMs.</li>
<li>Copy those snapshots as .VHDs to a blob in a Storage Account in the Central US region.</li>
<li>Using an AZCLI automation, without dependencies or any other issues.</li>
<li>Clone the VM using the .VHD as a base, in the destination region.</li>
<li>Here it helps a lot to deallocate the original VM, just in case there are hostname collision issues.</li>
<li>Delete the original VMs.</li>
</ol>
<p>It is true that once cloned, the Computer object of the original has to be deleted and the new one joined to the Domain, but it is a step that I could not avoid with Azure Resource Mover either. And its relatively easy to automate with a Powershell that we can then run in the VM using the Invoke-Command extension of the Azure Agent of the VM, for example. Although I logged in and did it locally.</p>
<p>Once the new VMs were tested and functionally validated, the original VMs were deleted. And that was it, they were <em>teleported</em> from East US to Central US. With some manual steps, yes, but most of them easily automated when this operation becomes a SOP. I didn&rsquo;t have to resolve any dependencies, by the way. Nor did I have to manually copy encryption keys to another Key Vault&hellip;</p>
<h2 id="conclusion-azure-resource-mover-did-not-make-it-easier-for-me-to-move-vms">Conclusion: Azure Resource Mover did not make it easier for me to move VMs</h2>
<p>Since I haven&rsquo;t investigated the tool in depth and with other use cases I&rsquo;m not going to question its usefulness for other resource movement operations, but after my experience I think that Azure Resource Mover doesn&rsquo;t make the operation to move VMs between regions easy. In fact, I think it makes it more complicated. We have to resolve countless &ldquo;dependencies&rdquo; and we have a high risk of side effects (moving an entire VNET when moving a VM??) to obtain a final result that is the same as if we cloned the VM based on a .VHD or snapshot.</p>
<p>In the tests -and these where Production VMs- we did not find the slightest functional difference between those created using the manual method and the original ones. So, in this specific case, I think it is easier to take advantage of some automations with AZCLI and create our own authentic &ldquo;VM mover&rdquo; than to use Azure Resource Mover.</p>
]]></content>
        </item>
        
        <item>
            <title>Corporate´s, client´s... managing multiple identities on a single computer</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2024/04/corporates-clients...-managing-multiple-identities-on-a-single-computer/</link>
            <pubDate>Sun, 28 Apr 2024 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2024/04/corporates-clients...-managing-multiple-identities-on-a-single-computer/</guid>
            <description>At work I manage several digital identities every day: The corporate one, with email and the company´s internal tools; the client´s, with another email, management system and internal tools; and even the &amp;ldquo;personal&amp;rdquo; one, I really don´t access anything &amp;ldquo;personal&amp;rdquo; on my work but I use this category for Spotify (gotta stay in the top 1% of worldwide Genesis listeners) and the RSS feed where I read news and keep track of everything happening in the industry.</description>
            <content type="html"><![CDATA[<p>At work I manage several digital identities every day: The corporate one, with email and the company´s internal tools; the client´s, with another email, management system and internal tools; and even the &ldquo;personal&rdquo; one, I really don´t access anything &ldquo;personal&rdquo; on my work but I use this category for Spotify (gotta stay in the top 1% of worldwide Genesis listeners) and the RSS feed where I read news and keep track of everything happening in the industry. So, even if there´s a single person in front of the desk, I manage quite a few accounts.</p>
<p>While I mention web identities, in this post I won&rsquo;t exclusively talk about them. They serve as an introduction to a specific use case in which we have to manage multiple digital identities in a single user of the operating system. I&rsquo;ll detail my specific situation and how I&rsquo;ve solved it. Everyone&rsquo;s situation is different but I hope it can give you clues to adapt them to yours if needed. Instead of switching, sharing identities or logging in and out, I&rsquo;ve tried to find a way to work in a compartmentalized manner where the change of identities is as seamless as possible.</p>
<h2 id="web-identities-browser-containers">Web identities: Browser containers</h2>
<p>No, I&rsquo;m not talking about computing containers, despite this being an SRE blog. I&rsquo;m talking about compartmentalizing the session information that the browser stores as if they were different profiles. So, by separating them I can have a &ldquo;Client&rdquo; container where I have the client&rsquo;s sessions (without saved credentials, I don´t like letting the browser remember credentials), and another &ldquo;Company&rdquo; container where I have tabs with sessions on my company&rsquo;s corporate websites. This is especially useful for me because both the client and the company use Office 365 as an office suite/email and also both use Confluence/Jira. I also have a third container for my personal web sessions. Actually, only for music and news, as I said. Well, also for when it&rsquo;s time to schedule some training or certification.</p>
<p>I use Firefox and take advantage of the <a href="https://addons.mozilla.org/firefox/addon/multi-account-containers/">Multi-Account Containers</a> plugin, which allows me to preconfigure containers for each &ldquo;profile&rdquo; and even offers the option &ldquo;Always open this site in this container&rdquo;. I know there are similar options available for Chrome as well.</p>
<p>This way, I can have different sessions in the same browser and switch between them seamlessly, depending on the active tab. I can have multiple Outlook web sessions open, two Confluence instances, and access pages with one identity or another as needed. It&rsquo;s much more convenient for me than having to switch between browsers.</p>
<p>There are other creative solutions for this: some colleagues have their personal and work computers connected to a KVM switch and switch between them as needed, while others use a separate browser for each &ldquo;profile.&rdquo; I don&rsquo;t consider the first option because I lose the ability to <code>copy</code> &amp; <code>paste</code> between tabs with different identities, and that&rsquo;s no way of living. As for the second option, I don&rsquo;t do it because having more than one browser in use, instead of just one that you really prefer, feels odd to me. Perhaps it&rsquo;s due to my bias as a &ldquo;systems&rdquo; person and that little voice in my internal monologue: &ldquo;Two programs running for the same task at the same time, what&hellip; they give away memory for free now?&rdquo;</p>
<h2 id="digital-identities-git-repositories">Digital identities: GIT repositories</h2>
<p>I work with GIT repositories in both the client and my company (where we have our in-house tool and other repositories for internal workshop practices). In all cases I authenticate using a digital certificate via SSH instead of a username/password. Again, I don&rsquo;t want to be choosing identities but rather be able to switch in the terminal from one repository to another and not have to worry about anything when I do a <code>pull</code> or <code>push</code>. The most comfortable solution has been leveraging the config file for SSH <code>~/.ssh/config</code> and add entries based on host to define the identity file (certificate) to use.</p>
<pre tabindex="0"><code> Host ssh.dev.azure.com
 HostkeyAlgorithms +ssh-rsa
 PubKeyAcceptedKeyTypes=ssh-rsa
 IdentityFile ~/.ssh/myCorporateKey
 IdentitiesOnly yes 

 Host *
 HostkeyAlgorithms +ssh-rsa
 PubkeyAcceptedAlgorithms +ssh-rsa
 IdentityFile ~/.ssh/myOtherKey
 IdentitiesOnly yes 
</code></pre><p>In the above example, I define one identity to use with the Azure DevOps repositories and another for the rest. Its just a matter of defining as many host entries as needed. For now I´m lucky enough to not have overlap of identities with all the GIT service sites I have to work with. In the end, by defining once in the file the identities to use, per host, I don´t have to worry about anything when moving from one repo to the next.</p>
<p>By the way, if we&rsquo;re talking about managing different SSH certificates to connect to machines, it&rsquo;s straightforward. At the time of connection we can choose the identity (here we use the private key, the public key should already be on the target server) with <code>ssh -i ~/.ssh/corporateIdentity x.x.x.x</code></p>
<h2 id="what-about-credentials-password-manager">What about credentials? Password manager</h2>
<p>Since I don´t like browsers remembering passwords nor using the same password for everything (for obvious reasons) I rely on my own password manager. It&rsquo;s something obvious, I know, yet I&rsquo;m still amazed by the number of professionals who don&rsquo;t use one. In that encrypted database I store all client and company credentials. I also duplicate the personal ones I use at work for ease of access. The encrypted database is backed up. At work I use <a href="https://macpassapp.org/">macPass</a> which is an open-source application compatible with KeePass.</p>
<h2 id="conclusions">Conclusions</h2>
<p>There&rsquo;s no great technical feat in leveraging these small solutions, but they are <em>Quality of Life</em> improvements that save me quite a few minutes each day and clear my mind of these considerations, allowing me to focus on what really matters: solving problems and getting work done.</p>
]]></content>
        </item>
        
        <item>
            <title>Mi first experience using LLMs as study aid</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2024/03/mi-first-experience-using-llms-as-study-aid/</link>
            <pubDate>Tue, 26 Mar 2024 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2024/03/mi-first-experience-using-llms-as-study-aid/</guid>
            <description>As I child I was called preguntón (too inquisitive) and I had the ability to end anyone´s patience. My chained &amp;ldquo;why&amp;quot;s could seem endless. I´d say that hasn´t changed much but I´ve managed to control it. I know when I have to stop asking others and myself to not sink into an infinite loop. It happens when I work, too. &amp;ldquo;Why is Ansible throwing a MaxConcurrentOperationsPerUser error? Why is that MaxConcurrentOperationsPerUser behaving like a sequential counter?</description>
            <content type="html"><![CDATA[<p>As I child I was called <em>preguntón</em> (too inquisitive) and I had the ability to end anyone´s patience. My chained &ldquo;why&quot;s could seem endless. I´d say that hasn´t changed much but I´ve managed to control it. I know when I have to stop asking others and myself to not sink into an infinite loop. It happens when I work, too. &ldquo;Why is Ansible throwing a MaxConcurrentOperationsPerUser error? Why is that MaxConcurrentOperationsPerUser behaving like a sequential counter? How is that counter defined in Windows?&rdquo; though in this case I´m asking myself and have to find my own answers.</p>
<h2 id="using-llms-as-study-assistants-my-experience">Using LLMs as study assistants, my experience</h2>
<p>As a technology enthusiast, SRE and Tech lead I´m exposed to the current frenzy with generative AI in the form of the well-known LLMs. I don´t want to come accross as a guru trying to tell anybody how much of it its actually ground breaking and how much its <em>hype</em>. Certainly I´m not going to delve into the philosophical side of what is consciousness and <a href="https://en.wikipedia.org/wiki/Chinese_room">the Chinese Room experiment</a>. I´m just going to share my experience in a field that I don´t see discussed as much from the IT perspective.</p>
<p>Yes, of course GPT 3.5 has helped me with the basics of scripts in bash and pwsh. And I´ve changed REGEX or JSON validators for prompts where I ask it to do them for me so I achieve the desired end result. I´ve also asked it about things to see if I can reduce the time I spend googling or to just have to google a confirmation. But another use that I´m getting out of it is in my studying.</p>
<p><strong>DISCLAIMER:</strong> Mi experience for this post is based entirely on GPT 3.5 as a representative LLM.</p>
<h2 id="leveraging-a-tool">Leveraging a tool</h2>
<p>Filled with curiosity I decided to try using LLMs as a study aid, to save me time and use it better. I want to see what this tool can do. I don´t want to be afraid of it, I want to see how it can make things easier for me. Mind you, notes and official documentation are still my primary source. I still verify and expand on more specific knowledge by going to search engines. I´ve used GPT-3.5 for three vluable things: starting from more fuzzy concepts and delving deeper, with as much backtracking as necessary (that dreaded chain of &ldquo;whys&rdquo; from children), asking for simple and custom exercises for practice, and using it as a conversational tool like a <a href="https://en.wikipedia.org/wiki/Rubber_duck_debugging">3.5 version Rubber Duck</a> that answers back to further solidify knowledge.</p>
<h3 id="from-fuzzy-to-concrete-with-as-many-whys-as-needed">From fuzzy to concrete, with as many &ldquo;whys&rdquo; as needed</h3>
<p>I said it, I think the &ldquo;inquisitive&rdquo; part of me comes from a tendency of wanting to dig into the most elemental aspect every time I gaing new knowledge. I learned many years ago that the limit of &ldquo;why?&rdquo; at the end of each explanation someone gave me was between three and four before they lost patience. GPT-3.5 has not lost its patience with me yet. Have you ever been studying something and realized you want more theoretical basis? Welcome to my life, too often. With GPT-3.5 I can ask questions and, at the very least, points me in a direction to search further.</p>
<p>It also works, as I said, to delve into the specifics of a topic. For example you can start asking about overriding in Python and end with examples of operator overloading with overriding their magic functions, through a dialogue in natural language rather than a string of searches or a click-fest on Stack Overflow links.</p>
<h3 id="custom-practice-exercises">Custom practice exercises</h3>
<p>I haven´t tried it with complex exercises because I don´t fully trust it and because for those I want humans that &ldquo;go for the kill&rdquo;. But when I want to solodify a concept after studying it, there´s nothing better than requesting a few customized exercises. &ldquo;GPT-3.5, give me 10 exercises with lambda functions. Okay, make them a bit more complicated, mix them with the use of <code>map()</code>or <code>filter()</code>. I´m stuck on this one, help me solve it&rdquo;.</p>
<p><img alt="LLM exercises" src="/img/LLM-learning5.JPG"></p>
<h3 id="rubberduck">Rubberduck</h3>
<p>It resembles the first point, but I want to make a disctintion because the idea is to engage in a dialogue to improve understanding of a concept or to solve a problem without directly asking for the solution. Something like: &ldquo;I´m going to paste a code snippet, I don´t want you to tell me how it works yet. I´ll explain it step by step, and you´ll ask me questions to help me improve my explanation&rdquo;</p>
<p><img alt="LLM rubber duck 1" src="/img/LLM-learning3.JPG"></p>
<p><img alt="LLM rubber duck 2" src="/img/LLM-learning4.JPG"></p>
<p>Here it behaves like a good rubber duck, which also provides corrections. We can se that I´m not such a good teacher, and it has encouraged me to be more careful with the terms I use. It´s right, in list comprehensions there are no &ldquo;function calls&rdquo;, there are operations, which may include function calls. Also, it quickly returns to its role of &ldquo;I am the one who gives the answers&rdquo;, if it was a human, it would even look arrogant.</p>
<h2 id="the-risks">The risks</h2>
<p>All that sounds great, but besides the advantages we need to talk about what GPT-3.5 doesn´t do that well. I´ve come across some risk that can detract from the value of learning with the aid of LLMs. I´ve divided them in a couple of categories:</p>
<h3 id="the-llm-is-plain-wrong">The LLM is plain wrong</h3>
<p>Not all answers are correct or real, or the ones it would produce if you ask again or tune the <em>prompt</em>. That´s why I think its ideal to use it to solidify and deepen concepts studied in other sources. It can also make mistakes when correcting your answers, so its best to ask for exercises that can be checked in another way (this is quite simple when studying programming languages, fortunately)</p>
<p><img alt="LLM hallucination1" src="/img/LLM-learning1.JPG"></p>
<p>Most of the time, with a prompt requesting a reevaluation of the answer, it will correct itself. But I wouldn´t fully trust it!</p>
<h3 id="the-llm-propagates-biases-from-the-content-its-been-trained-on">The LLM propagates biases from the content it´s been trained on</h3>
<p>Why would GPT-3.5 use examples of less-than-ideal practices in its examples? My answer to that is that its based on the content the LLM has been trained on. That is, human-generated content, and I´m afraid much of that content does may not follow best practices.</p>
<p><img alt="LLM bias" src="/img/LLM-learning2.JPG"></p>
<p>Here we can see GPT-3.5 uses <code>from module import class</code> in the example, which is totally valid but not recommended since it´s imported into the current namespace and can lead to confusion or even collisions (what if we had defined our own <code>reduce</code>?) It works, but what is clear is that its not the best example to give tosomeone who is getting acquainted with the language.</p>
<p>In the recent <a href="https://www.tecnologicasantacruz.com/">Tecnologica Santa Cruz</a>, <a href="https://www.linkedin.com/in/mariano-sigman/">Mariano Sigman</a> stated as the sole tesis of his talk that AI is eminently human creation, and I agree. Unintentionally, due to the training material we provide them, LLMs show a very human side with our same cognitive biases and errors.</p>
<h3 id="excessive-dependency">Excessive dependency</h3>
<p>In this I´m going to sound old-school, but the biggest risk for me is relying too much on a specific technology. It can help us complete tasksfaster, or at least get them started faster. That´s good. But we have to continue appreciating our own ability to think, to get <em>bored of studying</em> and to endure feeling stuck until we understand something or find the solution to a problem. That time is valuable. If it serves no other purpose, it at least trains us into patience and tolerance for frustration. And that´s valuable for any job, but I dare to think it´s even more so for IT. This risk borders on the philosophical, I know. But its something that seems to be happening as technology changes our habits and even our abilities. There are <a href="https://www.nature.com/articles/s41598-023-36256-4">plenty of clues</a> that we are <a href="https://elearningindustry.com/a-deep-dive-into-the-shrinking-attention-span">losing attention span</a> due to technology.</p>
<h2 id="conclusions">Conclusions</h2>
<p>The main point is that this post is not intended to be a comparison or in-depth investigation and is based solely on my experience with a fairly limited (yet representative) subset of text-based LLMs. The second point is that this is moving fast. Still, I´ll try to comment on some things that I believe can be generalized. If you want to learn from scratch or reinforce knowledge, it works, but in both cases you´ll have to verify everything. For me, ideally it´ll be used to solidify concepts that are already studied elsewhere more&hellip; reliable. Its also great to generate primers as well as exercises that help solidify concepts.</p>
<p>And lastly, I´ll leave here a <em>nerdy</em> movie quote that sums up what I think abouy being able to ask &ldquo;whys&rdquo; to a machine in natural language <em>ad nauseaum</em> without anyone or anything losing patience:</p>
<blockquote>
<p>Watching John with the machine, it was suddenly so clear. The terminator would never stop. It would never leave him, and it would never hurt him, never shout at him, or get drunk and hit him, or say it was too busy to spend time with him. It would always be there. And it would die to protect him. Of all the would-be fathers who came and went over the years, this thing, this machine, was the only one who measured up. In an insane world, it was the sanest choice &ndash;Sarah Connor (Terminator 2)</p>
</blockquote>
]]></content>
        </item>
        
        <item>
            <title>Python for SRE. Slots, should you bother?</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2024/02/python-for-sre.-slots-should-you-bother/</link>
            <pubDate>Mon, 26 Feb 2024 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2024/02/python-for-sre.-slots-should-you-bother/</guid>
            <description>I&amp;rsquo;m not a programmer, but my job involves programming. Mainly for our Azure in-house tool and also to automate repetitive tasks (away with toil!). The resulting software has a fairly small number of users: the rest of my team or other teams in the Operations and Engineering department. Sometimes the only user is myself. Nevertheless, given the usual complexity of the software I handle - a couple of hundred lines if we exclude the in-house tool - it doesn&amp;rsquo;t seem profitable to worry about efficiency as much as worrying about it working and getting the job done.</description>
            <content type="html"><![CDATA[<p>I&rsquo;m not a programmer, but my job involves programming. Mainly for our Azure <em>in-house</em> tool and also to automate repetitive tasks (away with <em>toil</em>!). The resulting software has a fairly small number of users: the rest of my team or other teams in the Operations and Engineering department. Sometimes the only user is myself. Nevertheless, given the usual complexity of the software I handle - a couple of hundred lines if we exclude the <em>in-house</em> tool - it doesn&rsquo;t seem profitable to worry about efficiency as much as worrying about it working and getting the job done. However, as I&rsquo;ve already hinted, I like what I do to be efficient or at least not <em>so</em> inefficient. I believe that if a piece of software can take 10ms and 500 bytes, it has no excuse to take 100ms and 1000 bytes. Even if we have spare time and memory.</p>
<p>So I&rsquo;ve been wondering about the impact of <code>__slots__</code> in Python. Would it be significant, would it be worth it? The theory, online discussions, and the <a href="https://docs.python.org/3/reference/datamodel.html#slots">official documentation</a> clearly say yes. But I wanted to see it for myself and try it out to answer the question that gives this post its tittle: &ldquo;Is it worth worrying about it?&rdquo;. Here is the resulting test, which has served as an excuse for me to get started in Python memory profiling.</p>
<h2 id="slots-the-theory">Slots, the theory</h2>
<p><code>__slots__</code> allows to explicitly declare the attributes of a class in Python. It makes it kinda similar to C-like languages, where if we don&rsquo;t declare a variable beforehand, it will complain with some kind of &ldquo;UndefinedVariable&rdquo; error. However, usually this is entirely legal in Python:</p>
<pre tabindex="0"><code>class Example:
    def __init__(self, number):
        self.number = number

    def do_stuff(self):
      if (self.number % 2 == 0):
        return (self.number)
      else:
        self.new_num = 1 + self.number
        return (self.new_num)
</code></pre><p>Above example works perfectly in Python. The variable <code>new_num</code> is not declared as an instance attribute (those that go in the constructor) but directly in the <code>else</code>. There is no problem. And there isn&rsquo;t because Python objects have the <code>__dict__</code> dictionary to dynamically map their attributes. This gives flexibility when writing code, at the cost of overhead in memory and access time.</p>
<p>Using <code>__slots__</code> in a class allows us to deny the creation of that <code>__dict__</code>, forcing us to declare all the attributes that each object of the class will have. By the way, this also means that we won&rsquo;t have objects of the same class with different attributes depending on what happens at runtime.</p>
<pre tabindex="0"><code>class Example:
    __slots__ = (&#39;number&#39;)
    def __init__(self, number):
        self.number = number

    def do_stuff(self):
      if (self.number % 2 == 0):
        return (self.number)
      else:
        self.new_num = 1 + self.number
        return (self.new_num)
</code></pre><p>This will no longer work in Python. <code>new_num</code> is not declared in <code>__slots__</code>, so the object cannot have an attribute other than <code>number</code>. We will encounter an error:</p>
<pre tabindex="0"><code>AttributeError: &#39;Example&#39; object has no attribute &#39;new_num&#39;.
</code></pre><p>To fix it, you just declare the variable in <code>__slots__</code> isn´t it C-like?</p>
<pre tabindex="0"><code>class Example:
    __slots__ = (&#39;number&#39;, &#39;new_num&#39;)
    def __init__(self, number):
        self.number = number

    def do_stuff(self):
      if (self.number % 2 == 0):
        return (self.number)
      else:
        self.new_num = 1 + self.number
        return (self.new_num)
</code></pre><p>BTW, we could also simply make <code>new_num</code> a local variable of the method and not an instance attribute (we declare it without <code>self.</code>) and it would work because <code>__slots__</code> &ldquo;restricts&rdquo; the attributes of an instance. I just wanted to mention it, although this example doesn&rsquo;t deal with that.</p>
<p>What&rsquo;s the purpose of this behavior change brought by the use of <code>__slots__</code>? It&rsquo;s not about restricting anything, as clarified long ago by the BDFL Guido van Rossum:</p>
<blockquote>
<p>Some people mistakenly assume that the intended purpose of <strong>slots</strong> is to increase code safety (by restricting the attribute names). In reality, my ultimate goal was performance.</p>
</blockquote>
<p>It&rsquo;s a matter of <em>performance</em>. Accessing attributes declared in <code>__dict__</code> is slower, and moreover, <code>__dict__</code> itself has a larger memory footprint. I don&rsquo;t want to delve too much into this to keep the post concise. In the above linked explanation by Guido he goes into more detail and with firsthand knowledge.</p>
<h2 id="the-test">The test</h2>
<p>The way I&rsquo;ve set out to compare performance is intuitive:</p>
<ol>
<li>An example class. Two versions, one using <code>__slots__</code> and one without it.</li>
<li>Measure the memory usage of objects from both versions.</li>
<li>Compare the usage of each to answer: Is there a gain? In what proportion?</li>
</ol>
<p>For the test I designed a basic class that multiplies a range of numbers from 0 to max by a multiplier, and also stores the name of the &ldquo;caller&rdquo; because I wanted the class to store a string. I know, I&rsquo;m not too creative with examples. The second one is the same class but leveraging <code>__slots__</code> to see the differences.</p>
<pre tabindex="0"><code>class MyTestClass:
    def __init__(self, mult, rang, caller):
        self.multiplier = mult
        self.list = []
        self.caller = caller
        for number in range(0, rang):
            print(f&#34;Adding {number} x {self.multiplier}&#34;)
            self.list.append(number*self.multiplier)

class MySTestClass:
    __slots__ = (&#39;multiplier&#39;, &#39;list&#39;, &#39;caller&#39;)
    def __init__(self, mult, rang, caller):
        self.multiplier = mult
        self.list = []
        self.caller = caller
        for number in range(0, rang):
            print(f&#34;Adding {number} x {self.multiplier}&#34;)
            self.list.append(number*self.multiplier)
</code></pre><p>The first important question is, how do we measure the memory usage of an object in Python? We can&rsquo;t simply use <code>sys.getsizeof()</code> since <a href="https://docs.python.org/3/library/sys.html#sys.getsizeof">it will return the size of the object but not the objects it refers to</a>. That is, since my object contains references to other objects, it won&rsquo;t return reliable results. The demonstration of this is trivial: create a class that contains a list, instantiate two objects of the class and add 10 elements to one and 100 to the other, then <code>getsizeof()</code> will return the same value for both of them.</p>
<pre tabindex="0"><code>import sys

class testClass:
    def __init__(self, ran):        
        self.ran = ran
        self.lst = []
        for element in range(0, self.ran):
            self.lst.append(element)

small = testClass(10)
big = testClass(400)

print(f&#34;Size of small is {sys.getsizeof(small)}&#34;)
print(f&#34;Size of big is {sys.getsizeof(big)}&#34;)
</code></pre><p>Output shows us this limitation of <code>getsizeof()</code></p>
<pre tabindex="0"><code>Size of small is 48
Size of big is 48
</code></pre><p>The documentation itself references a recursive <code>sizeof</code>, but I turned to an easy to use third-party memory profiler called <a href="https://pypi.org/project/Pympler/">Pympler</a> that serves my purpose. The level of memory profiling I want to achieve is quite basic, so I didn&rsquo;t have time to &ldquo;reinvent the wheel,&rdquo; fun as it sounded.</p>
<p>So here&rsquo;s the example usage with Pympler.</p>
<pre tabindex="0"><code>import pympler.asizeof as pasizeof

class MyTestClass:
    def __init__(self, mult, rang, caller):
        self.multiplier = mult
        self.list = []
        self.caller = caller
        for number in range(0, rang):
            print(f&#34;Adding {number} x {self.multiplier}&#34;)
            self.list.append(number*self.multiplier)

class MySTestClass:
    __slots__ = (&#39;multiplier&#39;, &#39;list&#39;, &#39;caller&#39;)
    def __init__(self, mult, rang, caller):
        self.multiplier = mult
        self.list = []
        self.caller = caller
        for number in range(0, rang):
            print(f&#34;Adding {number} x {self.multiplier}&#34;)
            self.list.append(number*self.multiplier)
</code></pre><p>Once everything is ready for testing, it&rsquo;s time to try out cases. And this is where the influence of <code>__slots__</code> can shine. The value of <code>rang</code> is the only thing that will vary, as it represents the amount of dynamic memory I want the object to consume. To prepare the output, I&rsquo;ve decided to refer to objects using <code>__slots__</code> as &ldquo;sobjects&rdquo;. It&rsquo;s not a convention, it&rsquo;s just a quick way to differentiate them when printing their memory footprint.</p>
<p>Test 1: One small and one large:</p>
<pre tabindex="0"><code>test_subject = MyTestClass(2.5, 5, &#34;John&#34;)
test_subject2 = MyTestClass(2.5, 1000, &#34;Kelly&#34;)

stest_subject = MySTestClass(2.5, 5, &#34;John&#34;)
stest_subject2 = MySTestClass(2.5, 1000, &#34;Kelly&#34;)

print(f&#34;First object size is {pasizeof.asizeof(test_subject)}B&#34;)
print(f&#34;Second object size is {pasizeof.asizeof(test_subject2)}B&#34;)

print(f&#34;First sobject size is {pasizeof.asizeof(stest_subject)}B&#34;)
print(f&#34;Second sobject size is {pasizeof.asizeof(stest_subject2)}B&#34;)

print(f&#34;First object takes {pasizeof.asizeof(test_subject) / pasizeof.asizeof(stest_subject)} times the memory of First sobject&#34;)
print(f&#34;Second object takes {pasizeof.asizeof(test_subject2) / pasizeof.asizeof(stest_subject2)} times the memory of Second sobject&#34;)
</code></pre><p>The results (verbose output from <code>print(f&quot;Adding {number} x {self.multiplier}&quot;)</code> is clipped):</p>
<pre tabindex="0"><code>[...]
Adding 998 x 2.5
Adding 999 x 2.5
First object size is 648B
Second object size is 33264B
First sobject size is 376B
Second sobject size is 32992B
First object takes 1.7234042553191489 times the memory of First sobject
Second object takes 1.0082444228903977 times the memory of Second sobject
</code></pre><p>In the first case memory gains are significant. The memory usage of the class object that doesn&rsquo;t use <code>__slots__</code> is over 1.723 times that of the one that does use it. In the second case, the difference is much smaller: 1.008, okay, not as impressive, although we&rsquo;re shaving off 272 bytes which is never bad. The gains from using <code>__slots__</code> lose impact as the size of the list grows. The use of slots will have more impact if we instantiate many objects with a smaller memory footprint compared to just a big one containing collections.</p>
<p>Let&rsquo;s see the output if we change the <code>rang</code> when instantiating the objects from <code>5</code> and <code>1000</code> to <code>100</code> and <code>10000</code>:</p>
<pre tabindex="0"><code>[...]
Adding 9998 x 2.5
Adding 9999 x 2.5
First object size is 3728B
Second object size is 325584B
First sobject size is 3456B
Second sobject size is 325312B
First object takes 1.0787037037037037 times the memory of First sobject
Second object takes 1.0008361204013378 times the memory of Second sobject
</code></pre><p>No surprises there. There´s still some gains but less significant. So&hellip;</p>
<h2 id="then-is-it-worth-worrying-about">Then, is it worth worrying about?</h2>
<p>For me, the answer is: Yes, BUT.</p>
<p>We&rsquo;ve seen that memory savings can be important, just as the official documentation promises. Gaining efficiency in memory and access speed in such a simple way is not something to overlook. However, I believe it&rsquo;s something that should be approached differently depending on how we&rsquo;re working:</p>
<ol>
<li>If we have time for an orderly design phase (which is not often the case for us SREs, due to time and workload constraints), we can start leveraging <code>__slots__</code> from the beginning.</li>
<li>If it&rsquo;s part of a more &ldquo;adhoc&rdquo; development process, I would wait until the script or software is at least a bit mature. In other words, while we&rsquo;re testing and creating attributes, it&rsquo;s not worth going crazy adding <code>__slots__</code> as it slows us down. But once we&rsquo;re clear on what we need, why not?</li>
</ol>
<p>In both cases, we&rsquo;ll minimize access time and shed off a few (potentially quite a few) bytes. That&rsquo;s always a good thing.</p>
]]></content>
        </item>
        
        <item>
            <title>Doc-as-code. Loading into memory a Markdown document in Python</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2024/01/doc-as-code.-loading-into-memory-a-markdown-document-in-python/</link>
            <pubDate>Sat, 27 Jan 2024 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2024/01/doc-as-code.-loading-into-memory-a-markdown-document-in-python/</guid>
            <description>I believe that in the field of computer science, there are two main types of professionals, without discrediting either of them. There are those who first tinker, and then there are those of us who eagerly dive into the documentation (and later tinker, &amp;hellip;a lot). I love reading, so I&amp;rsquo;m one of those who eagerly turns to the docs. I value good documentation both to delve into a new concept and to refer back to it later.</description>
            <content type="html"><![CDATA[<p>I believe that in the field of computer science, there are two main types of professionals, without discrediting either of them. There are those who first tinker, and then there are those of us who eagerly dive into the documentation (and later tinker, &hellip;a lot). I love reading, so I&rsquo;m one of those who eagerly turns to the docs. I value good documentation both to delve into a new concept and to refer back to it later. I don&rsquo;t trust my memory beyond what&rsquo;s absolutely necessary because I&rsquo;m aware of its fallibility. I&rsquo;ve had enough <em>page fails</em> when going to the kitchen and forgetting why I went there in the first place. That&rsquo;s why Damian Conway&rsquo;s quote resonates so well with me:</p>
<blockquote>
<p>&ldquo;Documentation is a love letter that you write to your future self&rdquo;</p>
</blockquote>
<p>Also, obviously, I love programming. I believe that I would treat everything as code if I could, so why not documentation? This idea is not mine; it&rsquo;s called <strong>Documentation as Code</strong> (or doc-as-code) and has quite a few advocates on the web. As soon as I got the opportunity, I prepared a Proof of Concept for doc-as-code, and now that I work as a Tech Lead, I&rsquo;m going to ramp up the level of <em>evangelism</em> in my team. For me doc-as-code is a comfortable and natural way, as well as much more auditable, to prepare documentation. It&rsquo;s not just talk. This blog is written as doc-as-code, and the vast majority of the documentation I produce in my work (except for quick notes and meeting notes) is also generated using that doc-as-code PoC. I generate documents in <a href="https://www.markdownguide.org/">Markdown</a>, and then automation takes care of publishing them where needed.</p>
<h2 id="test-your-documentation">Test your documentation</h2>
<p>One of the great advantages of treating documentation as code is that it can be tested. All code can and should be tested. What tests should technical documentation pass? The question is open-ended and in my case, it&rsquo;s in the process of iterative answering. In the initial version we have decided to audit its content against a series of <em>compliance</em> standards. Not just a linter (there are already good linters for markdown), but something to ensure that the document has the format we want and the sections we require and find beneficial. For example, after the first heading, there should be a note stating that it&rsquo;s a self-generated document, discouraging direct edits (changes will disappear in the next run of the CD pipeline). Since I couldn&rsquo;t find anything to test documentation as code, I simply started to build it. This project, which I named <strong>Dactester</strong>, is still in development and brought about a series of quite interesting needs. One of the most important ones was: if I want to automate testing a Markdown document using Python, how do I represent it in memory?</p>
<h2 id="representing-the-document-the-naive-solution-10">Representing the Document: The Naive Solution 1.0</h2>
<p>Markdown is a plain text file with its own syntax that allows interpreters to render it. But at the data level it&rsquo;s just a plain text file. A plain text file is a collection of lines. So, my first implementation is a list of plain text lines. The code follows an object-oriented programming (OOP) approach and includes the necessary methods to provide a minimal functional interface that <strong>dactester</strong> requires.</p>
<h3 id="the-code">The code</h3>
<pre tabindex="0"><code>&#34;&#34;&#34; Represent a markdown document file &#34;&#34;&#34;
__author__      = &#34;Abian G. Rodriguez&#34;
__version__     = &#34;0.1&#34;
__status__      = &#34;PoC&#34;

# This is a class representing a .md document and providing methods to handle it: read it, parse it, etc

class MdDoc:
    &#34;&#34;&#34;
    Class abstraction of a markdown document file.
    &#34;&#34;&#34;

    def __init__(self):
        self.doclines = []

    def load_from_file(self, filepath):
        try:
            with open(filepath,&#39;r&#39;) as sourcefile:
                for line in sourcefile:
                    self.doclines.append(line)
        except FileNotFoundError as error:
            self.doclines = []

    def get_doc_lines(self):
        if len(self.doclines) &gt; 0:
            return self.doclines
        else:
            return -1

    def get_line_number(self, linestring):
        &#34;&#34;&#34;
        Get the line number of a given line.
        If two or more lines are equal, will get only the first one

        Parameters:
            linestring (str): The exact string representing a line to match

        Returns:
            linenumber (int): The number of the line found, or -1 if not found or document is empty
        &#34;&#34;&#34;
        if len(self.doclines) &gt; 0:
            if linestring in self.doclines:
                return(self.doclines.index(linestring)+1)
            else:
                return -1
        else:
            return -1
</code></pre><p>It works, and that&rsquo;s enough for a first approach but not for me. I&rsquo;d like to know if it&rsquo;s efficient. I&rsquo;ve always admired those who squeezed the hardware to the maximum instead of just jumping to the next task regardless of the resources their code consumed. I grew up admiring the people who could squeeze polygons and effects on the early 32-bit consoles. People capable of <a href="https://www.youtube.com/watch?v=LUZ436FXB4U">running Quake on the Sega Saturn</a>.</p>
<h3 id="performance">Performance</h3>
<p>To determine if it&rsquo;s efficient, in this initial approach I&rsquo;m interested in seeing the execution times based on the size of the markdown document, which is the only variable input. In the execution of the entire <strong>dactester</strong> process, the quantity and type of tests on the documents also matter, but by now I&rsquo;ll focus solely on the document and its implementation. I&rsquo;m concerned about the three main operations performed by the MdDoc class, which will be the three tests I&rsquo;ll conduct:</p>
<ol>
<li>Read and load a document into memory.</li>
<li>Loop through the list, performing an operation (typically a string comparison).</li>
<li>Search for a specific line and return its line number.</li>
</ol>
<p>To measure performance I&rsquo;m going to use <a href="https://docs.python.org/3/library/timeit.html">timeit</a> from Python&rsquo;s standard libraries. It provides the execution time in <strong>seconds</strong> for the snippet or code function passed as a parameter. By the way, I&rsquo;m just getting started with performance testing, so if my methods aren&rsquo;t entirely accurate or contain errors, feel free to provide any suggestions for improvement or comments. Remember you can <a href="/en/contactme/">contact me</a>.</p>
<h3 id="results">Results</h3>
<p>I&rsquo;ve conducted each of the basic tests with three different document sizes. A small markdown with 50 lines, a medium one with 500, and a large one with 5000. So, each document has ten times more lines than the previous. <strong>timeit</strong> returns the total time taken for the code execution <code>number</code> times, where <code>number</code> is an integer parameter. In my case, each result will be the total time for 10,000 executions since the code is simple and relatively small, and I want a relatively high number to make any minimal differences based on the document size visible. And now, here are the test results.</p>
<pre tabindex="0"><code>@@@@ Document load tests
Load test for small doc took: 1.9765488000120968 seconds
=======================================
Load test for medium doc took: 2.843191900057718 seconds
=======================================
Load test for big doc took: 10.372771300142631 seconds
=======================================
@@@@ END of Document load tests

@@@@ Load Document and loop through content tests
Load &amp; Loop test for small doc took: 2.015927999978885 seconds
=======================================
Load &amp; Loop test for medium doc took: 2.0034616000484675 seconds
=======================================
Load &amp; Loop test for big doc took: 2.1118023002054542 seconds
=======================================
@@@@ END of Load Document and loop through content tests

@@@@ Load Document, find line and return line number tests
Load &amp; Loop test for SMALL doc (line near start) took: 1.9678535000421107 seconds
=======================================
Load &amp; Loop test for SMALL doc (line near the middle) took: 1.9765974001493305 seconds
=======================================
Load &amp; Loop test for SMALL doc (line near EoF) took: 1.9668072001077235 seconds
=======================================
Load &amp; Loop test for MEDIUM doc (line near start) took: 1.9576516000088304 seconds
=======================================
Load &amp; Loop test for MEDIUM doc (line near the middle) took: 1.9541629999876022 seconds
=======================================
Load &amp; Loop test for MEDIUM doc (line near EoF) took: 2.0762366999406368 seconds
=======================================
Load &amp; Loop test for BIG doc (line near start) took: 1.9916893998160958 seconds
=======================================
Load &amp; Loop test for BIG doc (line near the middle) took: 2.003709400072694 seconds
=======================================
Load &amp; Loop test for BIG doc (line near EoF) took: 1.978114299941808 seconds
=======================================
@@@@ END of Load Document, find line and return line number tests
</code></pre><p>The operation where there is the most significant difference is loading the document into memory. The large document takes around ten times longer than the small one. This makes sense because I perform the loading using <code>.append()</code>, which, despite having a constant time complexity of O(1), is called <em>n</em> times based on the <em>n</em> lines in the document. Consequently, the time complexity for loading into memory with MdDoc is closer to O(n).</p>
<p>For the document loading and traversal (loop) operations the times are quite similar, although curiously, the medium document consistently takes less or the same time as the small one. This has occurred consistently in all test runs and raises a new question that I&rsquo;ll have to delve into at another time. The MdDoc comparison is done with <code>value in string</code>, which for <strong>strings</strong> becomes a call to <code>str.__contains__()</code>. According to its implementation in CPython, it uses the <a href="https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm">Boyer-Moore-Horspool algorithm</a> and is sublinear in the best cases O(n/m), O(n) on average, and O(nm) in the worst cases. Based on the test results, it seems to approach something sublinear.</p>
<p>The operation to return the line number of a line in the document has a duration that approaches constant time. In theory, based on the <a href="https://stackoverflow.com/questions/5913671/complexity-of-list-indexx-in-python">information I&rsquo;ve found</a>, <code>list.index()</code> has a linear time complexity of O(n). The fact that in the tests the behavior approaches O(1) may be because the document size is not large enough for the difference to be so visible.</p>
<p>So, the three main operations are on average O(n), not highly efficient but not terribly inefficient either. The fact that in my tests, where the <em>medium</em> document approaches the size of those we work with on my team, the operation times behave almost constant reassures me. For now, it will suffice.</p>
<p>However, I&rsquo;m not settling. Among the project notes there is now a measurable reason to improve the efficiency of the <code>MdDoc</code> class.</p>
<h2 id="dactester-action">Dactester action</h2>
<p>As I mentioned, I couldn&rsquo;t find anything to automate the testing of doc-as-code, so I had to create it myself. I decided to publish the same GitHub Action that I use in the CI/CD pipeline for documentation on our team. It has the original name of <a href="https://github.com/AbianG/dactester-action">dactester-action</a>. In case someone might find it interesting after reading this post. <em>Sharing is caring</em>.</p>
<h2 id="kudos">Kudos</h2>
<ul>
<li><a href="https://docs-as-co.de/">Doc-as-code</a></li>
<li><a href="https://www.writethedocs.org/guide/docs-as-code/">Doc-as-code in writethedocs.org</a></li>
<li><a href="https://github.com/AbianG/dactester-action">dactester-action</a> en mi Github</li>
<li><a href="https://stackoverflow.com/questions/35220418/runtime-of-pythons-if-substring-in-string">Runtime of substring in string in Stack Overflow</a></li>
</ul>
]]></content>
        </item>
        
        <item>
            <title>Recap, the blog´s first year</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2023/12/recap-the-blogs-first-year/</link>
            <pubDate>Sat, 30 Dec 2023 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2023/12/recap-the-blogs-first-year/</guid>
            <description>2023 is ending and its common to have moments of introspection about the year. For me this implies quite a few things: a retrospective of my professional life, one about my personal goals, another analyzing the level of compliance with the habits that I have wanted to set and even a letter that I write to myself from year to year (if we are talking about accountability, we owe such a level to few people other than ourselves).</description>
            <content type="html"><![CDATA[<p>2023 is ending and its common to have moments of introspection about the year. For me this implies quite a few things: a retrospective of my professional life, one about my personal goals, another analyzing the level of compliance with the habits that I have wanted to set and even a letter that I write to myself from year to year (if we are talking about accountability, we owe such a level to few people other than ourselves). Far from being a tedious process, I confess that I like it. It is an opportunity to stop, think and check if the path I´m walking goes towards where I want to go. Come to think of it, there is a clear parallelism with my habit of regularly checking the route on a map on my hiking trips. All this makes me realize two things: clearly Im kind of a geek and of course I am a very <em>data driven</em> person, at this point I don&rsquo;t know if it is product of <em>déformation professionnelle</em> or a <em>builtin setup</em>.</p>
<p>This year I have to add a new audit to the list.</p>
<h2 id="recap-about-the-blog">Recap about the blog</h2>
<p>As an idea, the blog was born a couple of years ago. But it was in my previous recap (2022) where I set the goal of starting it formally, along with a metric to reach. The thing about being a <em>data driven geek</em> is that it prevents my recaps from being based on subjective opinions (I think it wasn´t that bad, I think I fell short of&hellip;) and instead rely on objective data and be more honest. So now its time to see, among other things, what this first year of blogging was like. First lest review the set objective and its metric:</p>
<blockquote>
<p>Publish the blog, have 12 posts in the first year</p>
</blockquote>
<p>First part, way accomplished. Second part, there´s 9 out of the set 12 posts. 75%. <em>Not great, not terrible</em>. Besides the number of posts, in which I did fell short, there have been some usability improvements and ―almost as important― the addition to the backlog of a few more that will come out in 2024. On the other hand, if I track the only metric I can monitor natively in the Azure static webapp that hosts the blog (requests to the server, not too reliable) I see a small upward trend.</p>
<p>I also take a few lessons learned, the thing about writing a blog is that is as continuous a learning process as the rest of my work. Its not only important to have good information to share, but to share it in a comfortable or, better said, <em>usable</em> way.</p>
<p>Even having missed the goal by 25%, I´m reaching the end of 2023 and feel satisfied because it has been a great year of professional growth: I´ve finally challenged myself to publish the blog and share a little of my professional day to day with the world, well, more like the part of the world that reaches the blog and wants to read it. It has been a year in which I have opened myself to scrutiny and the opinions/criticism of my peers. A year where there has been an even greater growth with <a href="https://www.linkedin.com/feed/update/urn:li:activity:7125903527255638016/">my advancement from SRE to TechLead</a> that will also be reflected in the blog itself.</p>
<p>So okay, I missed the mark of the 12 post in the first year. But I can say that I´ve dared with this project and giving back a bit of all the knowledge and experiences that the Net has given me. And since I´m a geek, I can´t help but have this quote come to mind: <em>&ldquo;And where does this newborn go from here? The Net is vast and infinite&rdquo;</em></p>
]]></content>
        </item>
        
        <item>
            <title>Of Azure NSGs and VNET peerings.</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2023/10/of-azure-nsgs-and-vnet-peerings./</link>
            <pubDate>Sat, 07 Oct 2023 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2023/10/of-azure-nsgs-and-vnet-peerings./</guid>
            <description>Networking in the Cloud is becoming more and more streamlined. But that doesn´t mean its not free from vendor-specific peculiarities. In this case, trying to leverage Azure´s Network Security Groups (Azure´s ACLs) under a particular setup showed a behavior that allowed me to learn a thing of two about Azure´s networking.
Intended setup: NSGs to block access from the Internet The intended setup was straighforward and one we had in other parts of our infrastructure: Limit public access (from the Internet) to only certain IPs for our services.</description>
            <content type="html"><![CDATA[<p>Networking in the Cloud is becoming more and more streamlined. But that doesn´t mean its not free from vendor-specific peculiarities. In this case, trying to leverage Azure´s Network Security Groups (Azure´s ACLs) under a particular setup showed a behavior that allowed me to learn a thing of two about Azure´s networking.</p>
<h2 id="intended-setup-nsgs-to-block-access-from-the-internet">Intended setup: NSGs to block access from the Internet</h2>
<p>The intended setup was straighforward and one we had in other parts of our infrastructure: Limit public access (from the Internet) to only certain IPs for our services. For that, we leveraged NSGs against the VNET´s subnets where the servers resided. Its a tried and tested method, so NSGs where setup and exception IPs where added. But this time it didn´t work: services where still accesible from the Internet to anyone. Why was that? What was different in this setup? Quite a few things, actually.</p>
<h2 id="the-initial-setup-more-components-to-take-into-account">The initial setup: More components to take into account</h2>
<p>The servers where spread in a VNET (let´s call it Example VNET) with four subnets but I´ll reduce them to two for the sake of this example: ServersA_subnet and ServersB_subnet. And then the Azure Application Gateways that controlled access where on another subnet (Gateways_subnet). That makes it 3 subnets where we could apply the NSG to prevent unauthorized direct access to either of the servers´ subnets and the AppGWs that where ready to handle most of the traffic.</p>
<p>The NSG setup was simple enough. Just inbound rules to add, since outbound connectivity was not to be limited:</p>
<ol>
<li>Allow inbound traffic comming from certain public IPs for HTTPS traffic</li>
<li>Allow inbound traffic comming from VNET (this is a default Azure NSG rule to allow intra-VNET communication)</li>
<li>Deny all other inbound traffic</li>
</ol>
<p>My IP was clearly not one of the public IPs allowed, yet I could hit the servers. And others could, too. What was wrong in the setup, then? Was the NSG not being applied correctly? Unlikely, but after reviewing and validating that the NSG setup was correct I set out to investigate what this environment had that the others didn´t. Time to trace the network flow!</p>
<p>The inbound flow from browser request until it reached the servers was as follows:</p>
<ol>
<li>First a <strong>CNAME</strong> like <code>customer-service.ourdomain.com</code> in our third party DNS service, mapped to an A record (also in the same third party DNS vendor).</li>
<li><strong>A RECORD</strong> mapped to the Public IP of one of our Azure Firewalls.</li>
<li>Dynamic NAT (DNAT) rule on the Firewall that translated the Public IP to the correct Application´s Gateway Private IP.</li>
<li>The AppGW sent the request to one of the servers in the correct backend pool.</li>
</ol>
<p>The setup was different, mainly because it had a Firewall that was also doing NAT. This NSG method was done on other envs which didn´t leverage Azure Firewall. Also, the CNAME was <em>proxied</em>, meaning that once it reached our third party DNS provider it would enter their network and come to our servers as if from one of their Public IPs. See whats happening already?</p>
<h2 id="what-was-really-happening-that-was-no-public-traffic-anymore">What was really happening: that was no public traffic anymore</h2>
<p>Issue with our approach was first and foremost it was our Firewall performing DNAT translation: Our third party vendor´s Public IPs where allowed through and since it was proxied, any request for that CNAME <code>customer-service.ourdomain.com</code> was coming from those approved public IPs from our third-party DNS. All good there, that should happen. But at that step, the original requester´s IP was already meaningless. But more interesting things where happening that show a few things about Azure´s VNETs inner workings.</p>
<p>When performing the translation for the DNAT rule, Azure Firewall translates origin IPs to private IPs in the range of the Firewall´s own subnet. <a href="https://techcommunity.microsoft.com/t5/azure-network-security-blog/azure-firewall-nat-behaviors/ba-p/3825834">Per this techcommunity doc</a>:</p>
<blockquote>
<p>“When a new flow matches against a DNAT rule on the Azure Firewall, both the source and destination IP addresses will be translated to new values. When the destination is a private IP address in the virtual network, the source IP address will translate to one of the IP addresses in the AzureFirewallSubnet of the virtual network, while the destination IP address will translate to what has been configured in the DNAT rule as the Translated address.”</p>
</blockquote>
<p>So technically, after executing the DNAT rule, any request coming from the outside (The Internet) for that CNAME was now part of the Firewall´s subnet. Still, that didn´t mean the request should reach the servers. Actually it should be the opposite, right? On the NSG Rule 1 was to allow a series of Public IPs that no longer meant anything (all request at this point would have a Private IP in the range of the FW´s subnet) and Rule 2 of the NSG said to allow everything coming from the <strong>same VNET</strong>, and the Firewall was in a whole different VNET. If anything, our original setup should have been denying all requests, even the ones comming from the allowed IPs (which at this point in the request´s flow were irrelevant). But instead it was allowing everything. Why? Well&hellip;both the Firewall´s VNET and our Example VNET where <a href="https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview">peered</a>.</p>
<p>According to <a href="https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-manage-peering?tabs=peering-portal#create-a-peering:~:text=The%20VirtualNetwork%20service%20tag%20for%20network,network%20when%20this%20setting%20is%20Enabled">official Microsoft docs</a> if the peering is marked like &ldquo;Allow vnet-1 to access vnet-2&rdquo; (and it is by default) the <code>VirtualNetwork</code> service tag -used by NSGs- includes both the VNET and peered VNETs. Meaning that, for the NSG, the Firewall´s VNET and the local VNET where it was applied where indistinguishable.</p>
<p>So, logically, the NSG was doing its job. My outside requests where first proxied through our third-party DNS and getting their IPs, which where allowed on our Firewall but where no longer my original Public IP. Then the Firewall executed a DNAT rule to translate said request´s destination IP to a private IP in the correct range for the correct resource (an Application Gateway).</p>
<p>In the process, it also translated the origin IP (again) to be in the range of the Private IPs of its own subnet in the Firewall´s VNET. Now, being part of a VNET peered with Example VNET, my original request looked exactly like any other request coming from inside Example VNET. Per rule 2, the NSG allowed it through. And that was it, mystery solved.</p>
<h2 id="the-solution">The solution</h2>
<p>We couldn´t simply disallow intra-VNET traffic, our servers needed to talk to each other, as well as access other resources. A more complex setup like this wasn´t simply going to work with NSGs. And unproxying the CNAME so request didn´t get our vendor´s Public IPs was out of the question (because it provided many other advantages). Our best bet was trying to solve it as close to the edge as possible, leveraging another kind of ACLs in our third party´s DNS vendor.</p>
<h2 id="kudos">Kudos</h2>
<ul>
<li><a href="https://learn.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview">Network security groups overview</a></li>
<li><a href="https://blog.aelterman.com/2021/01/08/defaulting-azure-virtual-network-peering-from-allowing-to-denying-traffic/">SvenAelterman´s blog entry about VNET peering and the Service Tag</a></li>
</ul>
]]></content>
        </item>
        
        <item>
            <title>File pull and push from Azure Blobs in Azure functions with Powershell.</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2023/08/file-pull-and-push-from-azure-blobs-in-azure-functions-with-powershell./</link>
            <pubDate>Sat, 19 Aug 2023 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2023/08/file-pull-and-push-from-azure-blobs-in-azure-functions-with-powershell./</guid>
            <description>I&amp;rsquo;ve completed a PoC to adapt a local script and turn it into a function that runs based on an HTTP request. It was a great opportunity to work with serverless architecture using Azure Functions. As I adapted it from a Powershell script made by one of my colleagues, the language option was preset (I would have gone with Python otherwise, knowing myself) The main feature of the function is that it interacts with rules of an Azure Firewall policy to backup or modify (add or delete) some specific rules.</description>
            <content type="html"><![CDATA[<p>I&rsquo;ve completed a PoC to adapt a local script and turn it into a function that runs based on an HTTP request. It was a great opportunity to work with serverless architecture using Azure Functions. As I adapted it from a Powershell script made by one of my colleagues, the language option was preset (I would have gone with Python otherwise, knowing myself) The main feature of the function is that it interacts with rules of an Azure Firewall policy to backup or modify (add or delete) some specific rules. Originally the script downloaded a backup locally as a .JSON file and consumed another .JSON of the rules to be modified.</p>
<p>My goal was to make it serverless and reside completely in the customer&rsquo;s infra Azure, so the most interesting part was moving the functionality of writing and reading the files to an Azure Blob. Maybe I didn&rsquo;t search well enough (and I searched, I searched a lot&hellip;) but I found that the Azure Functions documentation for Blob input or output binding with Powershell was limited and the examples were few and very simple. Of course, you can always use the AzCLI module <code>Az.Storage</code>, leverage directly the Connection String and interact with the Blob like from anywhere else, but where&rsquo;s the fun in that? Why not use the bindings? I ran into several issues, so I&rsquo;m going to put the relevant code here along with some comments, hopefully it will help someone.</p>
<h2 id="bindings">Bindings:</h2>
<p>The first thing is to declare in the <code>function.json</code> the bindings that we want. In this case my function has:</p>
<ul>
<li>An HTTP trigger.</li>
<li>An HTTP output binding.</li>
<li>An output binding to a blob.</li>
<li>An input binding from a blob (the same, but it doesn&rsquo;t have to).</li>
</ul>
<h3 id="wheres-my-connection-string">¿Where´s my connection String?</h3>
<p>There can be as many inputs and outputs as we want, but only one trigger. Most relevant here is the <code>connection</code> parameter in the blob bindings. This parameter will refer to a secret in the function app, in a common namespace to all the functions that we have under that app. Very similar to the secrets of code repositories like Github. This way, we can have credentials saved for your use without exposing them. As we can see, the file name can also be parameterized in the bindings (<code>backupFile</code> and <code>sourceFile</code> in this case)</p>
<pre tabindex="0"><code> {
  &#34;bindings&#34;: [
    {
      &#34;authLevel&#34;: &#34;function&#34;,
      &#34;type&#34;: &#34;httpTrigger&#34;,
      &#34;direction&#34;: &#34;in&#34;,
      &#34;name&#34;: &#34;Request&#34;,
      &#34;methods&#34;: [
        &#34;get&#34;,
        &#34;post&#34;
      ]
    },
    {
      &#34;type&#34;: &#34;http&#34;,
      &#34;direction&#34;: &#34;out&#34;,
      &#34;name&#34;: &#34;Response&#34;
    },
    {
      &#34;name&#34;: &#34;outputBlob&#34;,
      &#34;type&#34;: &#34;blob&#34;,
      &#34;path&#34;: &#34;poc/{backupFile}&#34;,      # Path is directly the blob/file we want
      &#34;connection&#34;: &#34;blobCs&#34;,          # This is the name of the secret containing the ConnectionString
      &#34;direction&#34;: &#34;out&#34;
    },
    {
      &#34;name&#34;: &#34;inputBlob&#34;,
      &#34;type&#34;: &#34;blob&#34;,
      &#34;path&#34;: &#34;poc/{sourceFile}&#34;,
      &#34;connection&#34;: &#34;blobCs&#34;,
      &#34;dataType&#34;: &#34;binary&#34;,           # Explicit typecast
      &#34;direction&#34;: &#34;in&#34;
    }
  ]
}
</code></pre><h2 id="the-function">The function</h2>
<p>The function is here simplified, and the relevant part is the one that reads or writes to the blob bindings.</p>
<p>At the beginning, we declare the modules and parameters to use, in this case they are read from the <code>body</code> of the HTTP request.</p>
<pre tabindex="0"><code>using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $inputBlob, $TriggerMetadata)

Import-Module Az.Accounts

# Interact with query parameters or the body of the request.
$sourceFile = $Request.Body.sourceFile
$backupFile = $Request.Body.backupFile
</code></pre><h3 id="output-blob-writing-multiple-files-to-an-output">Output Blob: Writing multiple files to an output</h3>
<p>By design the output binding is directly considered a blob (a file). The solution to be able to write more than one is to generate a temporary folder, save the files there and zip it later to push it to the output. I took advantage of the fact that in Powershell everything is an object and managed each rule <em>object</em>, exported it to an .XML file in a temporary folder. The folder is then compressed. Temporary folders are created and deleted on each run (if they exist) since the function can persist the filesystem between runs.</p>
<pre tabindex="0"><code>Write-Host &#34;Rules discovery completed&#34;
# Create temp folder to store all rules and then zip it
if (Test-Path -Path .\caughtRules) {
  Remove-Item -Path .\caughtRules -Recurse -Force | Out-Null
}
New-Item -ItemType Directory -Path .\caughtRules
# Have the rule collection, now lets catch the rules we targeted
foreach ($rule in $targetedRules) {
  $ruleName = $rule.Name
  $caughtRule = $existingrulecollection.GetRuleByName($ruleName)
  $caughtRule | Export-Clixml .\caughtRules\$ruleName.xml
}        
# Zip temp folder with the objects in xml
if (Test-Path -Path .\caughtRules.zip) {
  Remove-Item -Path .\caughtRules.zip -Force | Out-Null
}        
Compress-Archive -Path .\caughtRules\* -DestinationPath .\caughtRules.zip | Out-Null
# Copy zipped file to output blob
$zipPath = &#34;.\caughtRules.zip&#34;
$content = [System.IO.File]::ReadAllBytes($zipPath)
Push-OutputBinding -Name outputBlob -Value $content -Clobber
</code></pre><h3 id="reading-the-file">Reading the file</h3>
<p>Also by design the input binding is directly considered a single file and it will also be provided as a <code>string</code>, something quite problematic if what we have there is a .zip. The first life-saving step, which can be seen in the <code>function.json</code>, is to <em>typecast</em> the input to a ByteArray (declared there as <code>binary</code>).</p>
<p>Once the typecast was done, I just had to treat the input blob as a byteArray from which to read my .zip file. Of course I also had to create temporary folders to store the unzipped rules in the same way as I did with the output&hellip;</p>
<pre tabindex="0"><code>if (Test-Path -Path .\unzippedRules) {
  Remove-Item -Path .\unzippedRules -Recurse -Force | Out-Null
}
# Pulling inutBlob string into a MemoryStream
$asByteArray = $inputBlob
$zipPath = &#34;.\sourceRules.zip&#34;
# Writing ByteArray into .zip file
[System.IO.File]::WriteAllBytes($zipPath, $asByteArray)
# Expand .zip and load unzipped rules
Expand-Archive -Path .\sourceRules.zip -DestinationPath .\unzippedRules -Force | Out-Null
$objXmls = gci .\unzippedRules
$ruleArray = @()
  foreach ($xmlobj in $objXmls){
    $importedObject = Import-Clixml $xmlobj
    $ruleArray += $importedObject
}
</code></pre><h3 id="keypoints">Keypoints</h3>
<p>Actually, even when including so many threatening-sounding words, reading and writing from Azure Functions in Powershell to an Azure Storage Account using input and output blobs is not that complicated. But the lack of simple examples that can be extrapolated to each particular case can make us spend more hours than we want to get it done. Let&rsquo;s remember the most important thing:</p>
<ol>
<li>Correctly define our bindings (including the connection Strings if they are necessary to connect to another resource)</li>
<li>Typecast the input if we want to treat it as something other than <code>string</code></li>
<li>Read and write correctly. The input/output blob already represents the file.</li>
</ol>
<h2 id="kudos">Kudos</h2>
<ul>
<li>Blob storage bindings overview <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob?tabs=in-process%2Cextensionv5%2Cextensionv3&pivots=programming-language-powershell">in official docs</a></li>
<li>Blob input binding for Powershell <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob-input?tabs=python-v2%2Cin-process&pivots=programming-language-powershell">in official docs</a></li>
<li>Blob output binding for Powershell <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob-output?tabs=python-v2%2Cin-process&pivots=programming-language-powershell">in official docs</a></li>
</ul>
]]></content>
        </item>
        
        <item>
            <title>The blog is now multilanguage.</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2023/07/the-blog-is-now-multilanguage./</link>
            <pubDate>Sat, 22 Jul 2023 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2023/07/the-blog-is-now-multilanguage./</guid>
            <description>This month´s post is not technical, even though I could talk about how to configure multilang static webs made with Hugo I think the how-to I followed does it best. This post is just to announce that the blog is now multilanguage: spanish and english. I worked on this feature in the spare time I could find during June and part of July.
PSA: There may be small differences between posts in both languages.</description>
            <content type="html"><![CDATA[<p>This month´s post is not technical, even though I could talk about how to configure multilang static webs made with Hugo I think the <a href="https://phrase.com/blog/posts/i18n-tutorial-how-to-go-multilingual-with-hugo/">how-to I followed</a> does it best. This post is just to announce that the blog is now multilanguage: spanish and english. I worked on this feature in the spare time I could find during June and part of July.</p>
<h2 id="psa-there-may-be-small-differences-between-posts-in-both-languages">PSA: There may be small differences between posts in both languages.</h2>
<p>I didn´t use automatic translators to translate the posts to english, just relied on them occasionally. I´ve reviewed everything manually and changed a few details to make them sound more like what I intend to say on each language. I´m talking mostly about idioms, the technical part is identical between both languages. The main reason for this is that I work with both languages on a daily basis (in fact, some of the original posts of the blog where actually in english, taken from my work notes that are a mishmash of 99% english) and I´d rather sacrifice homogenity in order to not lose my own <em>voice</em> on either of the two languages.</p>
]]></content>
        </item>
        
        <item>
            <title>The operational error that revealed a coding error.</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2023/05/the-operational-error-that-revealed-a-coding-error./</link>
            <pubDate>Sat, 20 May 2023 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2023/05/the-operational-error-that-revealed-a-coding-error./</guid>
            <description>I think we have a tendency to think in incident´s root causes as isolated factors (either the code is wrong, or somebody executed something wrong, or the configuration was wrong&amp;hellip;) Even knowing the theory, if we have read dozens of articles about how usually its a combination of factors (errors), our automatic tendency is to look for a single culprit, even the concept itself root cause assumes a monolythic source from where the rest of consequences propagate until they create the problem we where trying to solve.</description>
            <content type="html"><![CDATA[<p>I think we have a tendency to think in incident´s root causes as isolated factors (either the code is wrong, or somebody executed something wrong, or the configuration was wrong&hellip;) Even knowing the theory, if we have read dozens of articles about how usually its a combination of factors (errors), our automatic tendency is to look for a single culprit, even the concept itself <em>root cause</em> assumes a monolythic source from where the rest of consequences propagate until they create the problem we where trying to solve.</p>
<p>This next issue is proof that this is not always like that, and we should not use that mental shortcut without a little critical thinking: We had an operational error that, by itself, wouldn´t have caused the issue and I discovered a coding error in a module from the Ansible collection <code>community.windows</code> that, by itself, wouldn´t have caused an incident. What happened when they both concurred?</p>
<blockquote>
<p>The source for this post is a bunch of notes that I always like to take when facing interesting troubleshoots. Moreover, it has been my first contribution to an open source project as big as Ansible.</p>
</blockquote>
<h2 id="the-error-we-are-probably-doing-something-wrong">The error: we are probably doing something wrong.</h2>
<p>The error occurred in our main deployment pipeline, during the release of a new version. As always, the FQDNs, hostnames and the output in general have been edited to protect the respective clients.</p>
<pre tabindex="0"><code>failed: [host-2.domain.com] (item=CUSTOMER_WEBSITE) =&gt; 
{     
    &#34;ansible_loop_var&#34;: &#34;item&#34;,     
    &#34;application_pool&#34;: &#34;CUSTOMER-1&#34;,     
    &#34;changed&#34;: false,    
    &#34;physical_path&#34;: &#34;G:\\WEBAPP\\22.2.0.0\\CUSTOMER-1&#34; } 
    MSG: Cannot find path &#39;G:\\WEBAPP\\22.1.0.0\\CUSTOMER-1&#39; because it does not exist.
</code></pre><p>The <code>physical_path</code> doesn´t exist? We already have a suspect, displaying another mental shortcut the first thing we thought was &ldquo;If it has always worked, and now it doesn&rsquo;t, we must have changed something that causes the error. We have broken that path&rdquo; (and this is a mental shortcut, Certainly, just because it worked in the past does not guarantee that it will work in the present.) It was a good start.</p>
<p>The path for <code>22.2</code>existed, but the <code>22.1</code> didn´t. Okay, operational error, during that moment in the deployment process, the previous path, since it´s the previous´version path, always exists in case its needed for a rollback. During the deployment we solved the problem by just restoring the missing path, and continued.</p>
<p>During execution I made a note to look into this later: What did the previous´ version path matter if what we were doing was mapping to the newest version path, which did exist? Had we really made an operational error? Or was the code imposing unnecessarily restrictive conditions? The problem went from being a suspect of operational error to something more interesting. The first thing I needed to know whas where that error came from. Ansible its Python, but in Windows hosts Ansible is Powershell and that error string looked very <em>pwsh-ish</em>. In another mental shortcut, I came up with an evidence-sparse theory based on instinct and what the limited data available inspired me. This, which can be called &ldquo;speculation&rdquo;, it Esto, que puede llamarse &ldquo;especular&rdquo;, its called <strong>heuristics</strong> in knowledge engineering.</p>
<h2 id="the-theory">The theory.</h2>
<p>The error “Cannot find path $path” didn´t came from Ansible, nor from the pwsh module. It came from PowerShell itself. But first I had to understood a little bit better what had happened. To not stretch this post too much, I will put the facts as a list:</p>
<ul>
<li>The path that was trying to be mapped (Version 22.2) existed at runtime.</li>
<li>The path of the previous version (22.1) had been deleted earlier than expected, there was an operational error here.
<ul>
<li>This was possible because in another step of our automation we stop the IIS and delete all <code>n</code> older versions except <code>n</code> (ie we delete <code>n-1</code>versions to make sure there are no more version folders older than the one immediately before and that do not have value to make a rollback)</li>
</ul>
</li>
<li>The IIS APP Pool still had the path of the previous version mapped (<code>G:\\WEBAPP\\22.1.0.0\\CUSTOMER-1</code>), since it was never updated.</li>
</ul>
<p>After these facts it was pretty clear what we had done wrong from our side (deleting the latest version prematurely), but not why we got the &ldquo;Cannot find path <code>'G:\\WEBAPP\\22.1.0.0\\CUSTOMER-1' because it does not exist.</code>&rdquo; error when in the module we where trying to map the <code>'G:\\WEBAPP\\22.2.0.0\\CUSTOMER-1'</code>, which did exist.</p>
<p>In my opinion, the greatest advantage of Open Source, and what has allowed it to become the de facto standard for many parts of our industry, is that you can take a look at the code to get a better idea of what is going on.</p>
<h2 id="the-bug-in-the-code-an-implicit-validation">The bug in the code: An implicit validation.</h2>
<p>When taking a look at the <a href="https://github.com/ansible-collections/community.windows/blob/main/plugins/modules/win_iis_webapplication.ps1">source</a> of <code>win_iis_webapplication</code> I came across a very interesting line of code, previous to making a check between the current Physical Path of the webapp and the one received as a parameter (<code>$folder.FullName</code>), to validate if it has to be modified or not and meet the idempotency condition (do nothing if the desired state and the current state are the same).</p>
<pre tabindex="0"><code>$app_folder = Get-Item -LiteralPath $application.PhysicalPath
            $folder = Get-Item -LiteralPath $physical_path
            if ($folder.FullName -ne $app_folder.FullName) {
                Set-ItemProperty -LiteralPath &#34;IIS:\Sites\$($site)\$($name)&#34; -name physicalPath -value $physical_path -WhatIf:$check_mode
                $result.changed = $true
            }
</code></pre><p>There was the error. On the conditional, the module compares between the current path and the given path (<code>if ($folder.FullName -ne $app_folder.FullName)</code>), however, to get the current path it did something a bit strange: <code>$app_folder = Get-Item -LiteralPath $application.PhysicalPath</code>. If you perform a <code>Get-Item</code> for something that does not exist, you get the very descriptive error message <code>Cannot find path 'X' because it does not exist.</code> An IIS App Pool can have in its PhysicalPath any path, even one that does not exist if we´ve managed to delete it while it was stopped. Of course if will fail as soon as you start it again, but it is allowed, you can have a path that does not exist in the filesystem.</p>
<p>It was clear what had happened, when trying to do that <code>Get-Item</code> with the previous PhysicalPath which we have deleted (operational error) PowerShell threw an unrecoverable error (you are asking it to perform a <code>Get</code> of something that doesn´t exist, after all). Mystery solved, yay!</p>
<p>But, should the Ansible module perform a check on the old path, and not just the new one received? If we honor the idea that in Ansible you are defining the final state in which we want to leave our hosts, it doesn´t make much sense to validate the previous state. What if I am actually running my playbook to fix something that is currently wrong? What if somebody or something misconfigures my App Pools? The logical thing to do would be to run the playbook to fix it, and its not very helpful to have Ansible fail because my current configuration (not the one I want to get) is not correct. Moreover, in this particular case it didn´t even look like an explicit check, but an implicit check derived from the way the code was trying to get the existing PhysicalPath.</p>
<h2 id="the-fix-an-improvement-to-not-be-unnecessarily-restrictive">The fix: An improvement to not be unnecessarily restrictive.</h2>
<p>The module shouldn´t care if the current PhysicalPath is valid, or if it exists. It can be <code>ILoveYou</code>, if should only care if the given one is valid and not the same that the current one. That is its call to action. With this approach, applying a fix is quite simple: Remove the implicit validation. And that is exactly what I did in <a href="https://github.com/ansible-collections/community.windows/pull/385">this PR</a></p>
<pre tabindex="0"><code>$app_folder = Get-Item -LiteralPath $application.PhysicalPath
            if ($folder.FullName -ne $application.PhysicalPath) {
                Set-ItemProperty -LiteralPath &#34;IIS:\Sites\$($site)\$($name)&#34; -name physicalPath -value $physical_path -WhatIf:$check_mode
                $result.changed = $true
            }
</code></pre><h2 id="kudos">Kudos</h2>
<p><a href="https://docs.ansible.com/ansible/latest/collections/community/windows/win_iis_webapplication_module.html">Official docs for the win_iis_webapplication module</a></p>
]]></content>
        </item>
        
        <item>
            <title>The string that pretended to be an ansible variable.</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2023/04/the-string-that-pretended-to-be-an-ansible-variable./</link>
            <pubDate>Sun, 23 Apr 2023 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2023/04/the-string-that-pretended-to-be-an-ansible-variable./</guid>
            <description>Its not unusual in Ansible to import a playbook inside another playbook. This allows for modularization and reutilization of the source code. Its also not unusual to pass variables to that new playbook, so it can use them. This was the initial setup I had to debug not long ago: A flag variable, marking if a folder exists or not, this information necesary to bifurcate a whole series of operations in the next playbook.</description>
            <content type="html"><![CDATA[<p>Its not unusual in Ansible to import a playbook inside another playbook. This allows for modularization and reutilization of the source code. Its also not unusual to pass variables to that new playbook, so it can use them. This was the initial setup I had to debug not long ago: A flag variable, marking if a folder exists or not, this information necesary to bifurcate a whole series of operations in the next playbook.</p>
<h2 id="the-theory-passing-a-variable-to-another-playbook-to-reference-it">The theory: Passing a variable to another playbook to reference it</h2>
<p>The imported playbook didn´t make a correct use of the variable and broke the whole process. At a glance, no issues. Funny thing was that it didn´t threw the <code>undefined variable</code> error, it went on without issues, behaving like if the variable was always <code>true</code>.</p>
<p>This is the -adapted- code in question. I´m sure many will spot the problem inmediately:</p>
<pre tabindex="0"><code>---
- hosts: group_a
  tasks:
    - name: Register folder status
      ansible.windows.win_stat:
        path: &#34;{{ predeploy_dir }}&#34;
      register: predeploy

- import_playbook: install-artifacts.yml
  vars:
    predeploy_done: predeploy.stat.exists
</code></pre><h2 id="when-in-doubt-debug-print-debug-print-and-debug-print">When in doubt, debug print, debug print and debug print.</h2>
<p>As I said, at a first glance I didn´t catch any errors (<em>my rookie mistake</em>). So I asked myself a question that I, at least, find very useful when facing any source code: &ldquo;Is it really doing what I think its doing?&rdquo;. The way that question materialized here is by debugging the variable values. In Ansible we have <code>ansible.builtin.debug</code> for that. So lets get to it. On the importet playbook I added:</p>
<pre tabindex="0"><code>- name: Debug variable
  ansible.builtin.debug:
    var: predeploy_done
</code></pre><p>Did a test run and the debug printed the variable´s value.</p>
<pre tabindex="0"><code>ok: [node-a] =&gt; {
    &#34;predeploy_done&#34;: &#34;predeploy.stat.exists&#34;
}
</code></pre><p>That did not look like a boolean at all. The value contained in <code>predeploy.stat.exists</code> was not being assigned to the variable, the string <code>&quot;predeploy.stat.exists&quot;</code> was. Of course, downstream in the imported playbook this was evaluated in the condition, as the boolean <code>true</code>, because Ansible is based on Python, and in Python any non-empty string is <code>true</code>.</p>
<p>The error I didn´t manage to see in the first place was that bad variable assignment. But now everything made sense, and in my experience that is the essential step to fixing anything.</p>
<h2 id="the-fix-and-being-a-bit-more-practical">The fix, and being a bit more practical.</h2>
<p>I´ve already catched the problem: The variable was not being assigned correctly. Fixing that was as easy as <code>predeploy_done: '{{ predeploy.stat.exists }}'</code>. However, I decided to made the value available to the remaining playbooks during the execution (contrary to what I tend to do, this time I didn´t stop to think what would be more efficient. I needed a quick fix and as practical as possible). Setting the value for a variable in the localhost for the whole execution is something Ansible allows us to do with <code>set_fact</code>. In the new code there´s no need to worry about importing <code>predeploy_done</code> on the importing playbook (once set with <code>set_fact</code> its available from that moment onwards for all the playbooks in that host, for the remaining execution time)</p>
<pre tabindex="0"><code>---
- hosts: group_a
  tasks:
    - name: Register folder status
      ansible.windows.win_stat:
        path: &#34;{{ predeploy_dir }}&#34;
      register: predeploy

    - name: Set global variable predeploy_done
      ansible.builtin.set_fact:
        predeploy_done: &#34;{{ predeploy.stat.exists }}

- import_playbook: install-artifacts.yml
</code></pre><h2 id="kudos">Kudos</h2>
<p><a href="https://docs.ansible.com/ansible/latest/collections/ansible/builtin/set_fact_module.html">set_fact in the official ansible docs</a></p>
]]></content>
        </item>
        
        <item>
            <title>Python parallelism-The runner that was too nice.</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2023/03/python-parallelism-the-runner-that-was-too-nice./</link>
            <pubDate>Mon, 20 Mar 2023 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2023/03/python-parallelism-the-runner-that-was-too-nice./</guid>
            <description>Azure offers the possibility to send commands and scripts (using Powershell if they are Windows hosts) to your VMs using the Run Command. This is something we can take advantage of to reduce toil and comfortably manage large numbers of servers. One of the projects in which I participate is the development of an in-house Python tool that, among other things, allows parallelizing this function by sending the same command or script to several VMs.</description>
            <content type="html"><![CDATA[<p>Azure offers the possibility to send commands and scripts (using Powershell if they are Windows hosts) to your VMs using the <a href="https://learn.microsoft.com/en-us/azure/virtual-machines/windows/run-command">Run Command</a>. This is something we can take advantage of to reduce <em>toil</em> and comfortably manage large numbers of servers. One of the projects in which I participate is the development of an <em>in-house</em> Python tool that, among other things, allows parallelizing this function by sending the same command or script to several VMs.</p>
<p>During development I have been in charge of this part of the tool since its initial version. But I wasn&rsquo;t happy with it, the first version was too nice: It waited for all instances of the scripts launched in parallel to finish without giving any context or intermediate result, even if one crashed or was incredibly slow. It was time to debug.</p>
<p>Let&rsquo;s take a look at how the program is organized (the code has been truncated and any referenced modules should be assumed to be correctly imported)</p>
<h2 id="the-polite-runner">The polite Runner</h2>
<pre tabindex="0"><code>class Runner:    
    &#34;&#34;&#34;     
    Class to manage the launch of scripts in parallel.     
    ASCYNCHRONOUS.     
    &#34;&#34;&#34;     
    def __init__(targetvmlist):       
        [...]
    def runScripts(self):         
        &#34;&#34;&#34;
        Run the script against all the VMs specified during object instantiation.
        &#34;&#34;&#34;         
        with ThreadPoolExecutor(max_workers=30) as executor:
            futures = []
            for vm in self.targetvmlist:                 
            #Instantiate a PowerShellScript object per VM to launch in. Sumbit all to the executor                 
            pwshS = PowerShellScript(vm)                 
            futures.append(executor.submit(pwshS.run))             
            execution_outputs=[]             
            #When execution is complete, return output             
            for future in as_completed(futures):                 
                execution_outputs.append(future.result())
            return(execution_outputs)
</code></pre><h2 id="powershellscript">PowershellScript</h2>
<pre tabindex="0"><code>class PowerShellScript:
    &#34;&#34;&#34;
    Represents a powershell script object
    &#34;&#34;&#34;     
    def __init__([...]):
        [...]     
    
    def run(self):         
        &#34;&#34;&#34;         
        Runs a powershell script in a certain VM.         
        &#34;&#34;&#34;         
        # Commands are prepared and readied here         
        [...]         
        ran_script = subprocess.run(command_with_parameters, capture_output=True)         
        #Simplified, I actually prepare an output dict         
        [...]
        return ran_script.stdout
</code></pre><ul>
<li>The PowershellScript class uses <code>subprocess.run</code> to launch the AzCLI command. It is the method that is parallelized.</li>
<li>The Runner class uses ThreadPoolExecutor as a context manager to parallelize execution, based on <a href="https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor-example">ThreadPoolExecutor example in the official docs</a>. The script objects to send (its <code>.run</code> method) are queued by the ThreadPoolExecutor and represented as Futures. A Future is, in parallel execution, an abstract concept that represents the function that has been sent to execute.</li>
<li>According to the ThreadPoolExecutor documentation, each queued function will use its own <em>thread</em>. So for <em>n</em> Powershell scripts we will have <em>n</em> threads.</li>
<li>Futures complete execution as fast as possible and return their result to the ThreadPoolExecutor using <code>as_completed</code>. This async approach makes sense and allows that, if the first function in the queue takes longer, others can finish anyway and exit to return output.</li>
<li>The first version is incredibly naive, with no error handling or timeouts of any kind. A slow script can hang the entire program even if all other threads complete perfectly. And this happened often.</li>
</ul>
<p>So my first step, after reading more about <a href="https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures">concurrent.futures</a>, was to add a timeout to <code> as_completed</code>, which throws a <em>TimeoutError exception</em> if a thread stays running longer than the specified number of seconds.</p>
<h2 id="less-polite-runner">Less polite Runner</h2>
<pre tabindex="0"><code>class Runner:     
    &#34;&#34;&#34;     
    Class to manage the launch of scripts in parallel.     
    ASCYNCHRONOUS.     
    &#34;&#34;&#34;     
    def __init__(targetvmlist):       
        [...]         
    
    def runScripts(self):         
        &#34;&#34;&#34;         
        Run the script against all the VMs specified during object instantiation.         
        &#34;&#34;&#34;         
        with ThreadPoolExecutor(max_workers=30) as executor:
            futures = []             
            for vm in self.targetvmlist:                 
            #Instantiate a PowerShellScript object per VM to launch in. Sumbit all to the executor                 
            pwshS = PowerShellScript(vm)                 
            futures.append(executor.submit(pwshS.run))             
            execution_outputs=[]             
            #When execution is complete, return output             
            try:                 
                for future in as_completed(futures, timeout=240):                     
                    execution_outputs.append(future.result())             
            except TimeoutError as error:                 
                execution_outputs.append(f&#34;TIMEOUT ERROR&#34;)             
            finally:
                  return(execution_outputs)
</code></pre><p>This is a good start, right? Yes and no. Runner was still extremely nice: if a thread was running for more than 240 seconds, it would throw the exception but not terminate execution until all threads had finished. It was not returning control to the function calling Runner. A quick look through the docs made me think that I could use <code>future.cancel()</code> to kill the thread. But you can only kill threads that are queued but haven&rsquo;t started running yet, and if one of my threads was throwing TimeoutError then they surely were running.</p>
<p>Killing a thread that has started executing is tricky, in my limited experience. That&rsquo;s when it occurred to me that doing things well and simply is usually best. At that moment I have:</p>
<ul>
<li>An instance of the Runner class that uses the ThreadPoolExecutor to execute in parallel functions it receives, in this case representing executions of a remote Powershell script using subprocess.</li>
<li>That, essentially, means that I have <em>x</em> threads with subprocess prepared to execute with a ThreadPoolExecutor.</li>
<li>When one of those threads encounters a problem and stays running, the entire program hangs waiting for it. My Runner leaves no one behind.</li>
<li>This is because the ThreadPoolExecutor, and thus my Runner, is still too nice. Even throwing TimeoutError and catching that exception, the thread continues to run. When the rest have finished, the program continues to wait for the thread that timed out and hasn&rsquo;t finished executing yet. This is by ThreadPoolExecutor´s design.</li>
</ul>
<p>At this point I could choose to catch the timeout, continue and not wait for all the results, but the thread would still run and the ThreadPoolExecutor would still wait. I didn&rsquo;t like the idea too much.</p>
<p>I also considered trying to force ThreadPoolExecutor to stop and kill any threads that haven&rsquo;t terminated yet, but this too seemed drastic and counter-intuitive to me. Surely there was a simpler, more correct solution. What was blocked or could run slower than expected? It was not some abstract process over which he had no control. It was an instance of my PowerShellScript class, which inside used <code>subprocess</code>. The easiest way to approach this was not to force ThreadPoolExecutor to care and control what that object that executed the script using <code>subprocess</code> did, it was to force those objects to behave appropriately. I had to add a timeout to <code>subprocess</code> so it wouldn&rsquo;t force the rest of the program to wait indefinitely.</p>
<h2 id="less-narcissitic-powershellscript">Less narcissitic PowershellScript</h2>
<pre tabindex="0"><code>class PowerShellScript:     
    &#34;&#34;&#34;
    Represents a powershell script object
    &#34;&#34;&#34;     
        def __init__([...]):
            [...]     
        def run(self):         
            &#34;&#34;&#34;         
            Runs a powershell script in a certain VM.         
            &#34;&#34;&#34;         
            # Commands are prepared and readied here         
            [...]         
            ran_script = subprocess.run(command_with_parameters, capture_output=True, timeout=220)         
            #Simplified, I actually prepare an output dict         
            [...]
            return ran_script.stdout
</code></pre><p>Now, if a script takes too long, it&rsquo;s a problem that is handled in the class that represents it, and the timeout occurs there. I thought I was having a problem with parallel execution, but I think I was having a coupling problem. Forcing a class to handle a timeout and execution that should never have been its problem.</p>
<p>Like I said, I&rsquo;m learning parallelism in Python and other intermediate concepts (I&rsquo;m reluctant to call anything I&rsquo;m learning yet &ldquo;advanced&rdquo;), but along the way I keep realizing that the basics are never sufficiently understood.</p>
]]></content>
        </item>
        
        <item>
            <title>Configuring Ansible on Windows hosts from macOS. The pain</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2023/02/configuring-ansible-on-windows-hosts-from-macos.-the-pain/</link>
            <pubDate>Thu, 16 Feb 2023 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2023/02/configuring-ansible-on-windows-hosts-from-macos.-the-pain/</guid>
            <description>Ansible is handy, at least for me it has opened up a universe of easier ways to managing the configuration of the huge numbers of servers that are handled in Cloud environments. (That it is based on Python also helps a lot). Getting it to work to communicate with Windows hosts from a macOS host isn´t that straightforward, at least for me it wasn´t. macOS, en general, always makes me pay with a little effort and pain for any action that on another OS I consider trivial.</description>
            <content type="html"><![CDATA[<p>Ansible is handy, at least for me it has opened up a universe of easier ways to managing the configuration of the huge numbers of servers that are handled in Cloud environments. (That it is based on Python also helps a lot). Getting it to work to communicate with Windows hosts from a macOS host isn´t that straightforward, at least for me it wasn´t. macOS, en general, always makes me pay with a little effort and pain for any action that on another OS I consider trivial. This post is based on some work notes I made when I started having to configure Windows hosts for a series of tests.</p>
<h2 id="configuring-windows-hosts-to-run-ansible-from-macos-the-pain">Configuring Windows hosts to run Ansible from macOS: The Pain.</h2>
<p>To run Ansible and be able to communicate with Windows hosts the most common way is to use WINRM for Python. While trivial on Linux, this can be a bit trickier to achieve on macOS due to the confusing executable paths. Even if you configure everything correctly you may run into the error: <code>winrm or requests is not installed: No module named 'winrm'</code></p>
<p><img alt="no winrm found" src="/img/exe-ansible-on-win-0.png"></p>
<p>It says that winrm is not installed. Well, lets run <code>python3 -m pip install pywinrm</code> to fix it, right? No! Because you&rsquo;ve been diligent and it&rsquo;s supposed to be ALREADY installed.</p>
<p>Stop, breathe. The error must make sense. It&rsquo;s installed, but is it installed for the version of Python that Ansible actually uses? To test this, we can run <code>head -n1 $(which ansible)</code></p>
<p><img alt="ansible´s python" src="/img/exe-ansible-on-win-1.png"></p>
<p>Wait a moment, that&rsquo;s not the same python that pywinrm is installed for, or is it?</p>
<p><img alt="system´s python" src="/img/exe-ansible-on-win-2.png"></p>
<p>Maybe its a bit confusing, but we have already realized the error, as always on this field even if sometimes we find it hard to believe, the error makes sense and we only had to investigate a little to understand what was happening. No, the machine was not plotting against us. Now all that remains is to install the module with <code>pip</code> for the correct Python installation.</p>
<p><img alt="installing for the right exec" src="/img/exe-ansible-on-win-3.png"></p>
<p>And finally we will have <code>winrm</code> working for ansible on macOS.</p>
<p><img alt="winrm finally working" src="/img/exe-ansible-on-win-4.png"></p>
<p><strong>Kudos</strong> as always to Stack Overflow, where I found <a href="https://serverfault.com/questions/1063343/ansible-error-when-trying-to-ping-windows-10-host-no-winrm-module">the answer</a>.</p>
]]></content>
        </item>
        
        <item>
            <title>Azure Static Web App metrics are missing-in-action</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2023/01/azure-static-web-app-metrics-are-missing-in-action/</link>
            <pubDate>Thu, 26 Jan 2023 20:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2023/01/azure-static-web-app-metrics-are-missing-in-action/</guid>
            <description>The error No metrics for Azure Static Web App, graphs show &amp;ldquo;Resource not found&amp;rdquo;
Like in almost every Azure resource, the overview pane of an Azure Static Web App shows a pair of metrics to have a quick idea of its status. However, it may happen that these charts appear without data and with the cryptic meessage: &amp;ldquo;Resource not found&amp;rdquo;. First question that may come to your mind is: what resource?</description>
            <content type="html"><![CDATA[<h2 id="the-error">The error</h2>
<blockquote>
<p>No metrics for Azure Static Web App, graphs show &ldquo;Resource not found&rdquo;</p>
</blockquote>
<p>Like in almost every Azure resource, the overview pane of an Azure Static Web App shows a pair of metrics to have a quick idea of its status. However, it may happen that these charts appear without data and with the cryptic meessage: &ldquo;Resource not found&rdquo;. First question that may come to your mind is: what resource? Because the static web app is right there.</p>
<p><img alt="WHAT resource?" src="/img/no-metrics-azure-static-web-0.png"></p>
<p>Well, what its not found are the metrics themselves, which are supplied by the resource provider <code>Microsoft.Insights</code>. This is because for the static web app´s subscription <code>Microsoft.Insights</code> is not registered as a provider. Metrics for static web apps aren´t exactly the most detailed (not that there´s much to show for an static web app). But, in case like me you have been trying to search Microsoft´s official descriptions, let me tell you <a href="https://learn.microsoft.com/es-es/azure/azure-monitor/essentials/metrics-supported#microsoftwebstaticsites">they don´t expand much into them</a>. <em>What you see is what you get</em>.</p>
<h2 id="the-fix">The fix</h2>
<p>Starting to get access to the metrics its as easy as manually registering <code>Microsoft.Insights</code>. It all can be done from the Azure portal:</p>
<ol>
<li>Select our static web app aplication´s subscription.</li>
<li>Go to <code>Resource providers</code>in the subscription´s left pane. There you can check all the resource providers and which ones are registered.</li>
<li>If <code>Microsoft.Insights</code> appears as unregistered, you just have to select it and click <code>Register</code>. Once its completed you should have access to all the metrics.</li>
</ol>
<p><img alt="The fix" src="/img/no-metrics-azure-static-web-1.jpg"></p>
<h2 id="kudos">Kudos</h2>
<ul>
<li><a href="https://learn.microsoft.com/en-us/answers/questions/324368/why-i-am-seeing-resource-not-found-for-all-the-sta">https://learn.microsoft.com/en-us/answers/questions/324368/why-i-am-seeing-resource-not-found-for-all-the-sta</a></li>
<li><a href="https://github.com/MicrosoftDocs/azure-docs/blob/main/includes/log-analytics-troubleshoot-azure-diagnostics.md">https://github.com/MicrosoftDocs/azure-docs/blob/main/includes/log-analytics-troubleshoot-azure-diagnostics.md</a></li>
<li><a href="https://learn.microsoft.com/es-es/azure/azure-monitor/essentials/metrics-supported#microsoftwebstaticsites">https://learn.microsoft.com/es-es/azure/azure-monitor/essentials/metrics-supported#microsoftwebstaticsites</a></li>
<li><a href="https://learn.microsoft.com/en-us/cli/azure/provider?view=azure-cli-latest">https://learn.microsoft.com/en-us/cli/azure/provider?view=azure-cli-latest</a></li>
</ul>
]]></content>
        </item>
        
        <item>
            <title>Did you break Ansible in macOS? Me too!</title>
            <link>https://www.lacabezaenlasnubes.es/en/posts/2023/01/did-you-break-ansible-in-macos-me-too/</link>
            <pubDate>Fri, 20 Jan 2023 21:00:00 +0000</pubDate>
            
            <guid>https://www.lacabezaenlasnubes.es/en/posts/2023/01/did-you-break-ansible-in-macos-me-too/</guid>
            <description>The error If when launching Ansible from macOS you´ve faced the (pretty sinister) error Error: A worker was found in a dead state, its not only you. I also broke Ansible in macOS.
](/img/broke-ansible-macos-0.png)
This error is related to the way the OS handles the Python´s forks. Per this Stack Overflow reference.
The fix The quickest workaround is to tell macOS to stop its shenanigans with an environment variable: export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES</description>
            <content type="html"><![CDATA[<h2 id="the-error">The error</h2>
<p>If when launching Ansible from macOS you´ve faced the (pretty sinister) error <strong>Error: A worker was found in a dead state</strong>, its not only you. I also broke Ansible in macOS.</p>
<p><img alt="Crepiest error" src="/img/broke-ansible-macos-0.png">](/img/broke-ansible-macos-0.png)</p>
<p>This error is related to the way the OS handles the Python´s forks. Per this <a href="https://github.com/ansible/ansible/issues/76322">Stack Overflow reference</a>.</p>
<h2 id="the-fix">The fix</h2>
<p>The quickest workaround is to tell macOS to stop its shenanigans with an environment variable: <code>export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES</code></p>
]]></content>
        </item>
        
    </channel>
</rss>
