<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lucas J. Ross on Medium]]></title>
        <description><![CDATA[Stories by Lucas J. Ross on Medium]]></description>
        <link>https://medium.com/@lucjross?source=rss-9525d53f20d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*fSa5CNuKBgC3G48ngxB4tQ.jpeg</url>
            <title>Stories by Lucas J. Ross on Medium</title>
            <link>https://medium.com/@lucjross?source=rss-9525d53f20d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:38:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucjross/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Smoke, Mirrors, and Extinguishers]]></title>
            <link>https://lucjross.medium.com/smoke-mirrors-and-extinguishers-33f87399376c?source=rss-9525d53f20d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/33f87399376c</guid>
            <category><![CDATA[organizational-culture]]></category>
            <category><![CDATA[personality-disorders]]></category>
            <dc:creator><![CDATA[Lucas J. Ross]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 01:44:22 GMT</pubDate>
            <atom:updated>2025-01-10T02:32:53.731Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Perspective on Narcissism in Professional Spaces</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8PI7Xd29FXhhsmn4evQPQ.jpeg" /><figcaption>Source: Instagram</figcaption></figure><p>Have you ever met a narcissist? You will have if you work in corporate environments for long enough. What is a narcissist? Let’s get to strict definitions later. I’ll start with some profiles of some odd characters, one fictional and one real. After all, anyone who isn’t a trained professional in psychology is likely to have some confusing experience with a narcissist before coming to understand anything about them.</p><h4>G.O.B.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*GlJ6aDdd3x4ecbnK9X2slw.gif" /></figure><p>This article is about narcissism in the workplace, and there’s nothing funny about that, at all. One exception is when the classic show <em>Arrested Development</em> put the character George Oscar Bluth II into a sharp suit and let nepotism run wild. In the episode shown in this GIF, Gob flaunts his business suit with increasingly inflated claims of its value as justification for abusive treatment of Bluth Company staff.</p><p>Throughout the series, Gob Bluth exhibits pretty much standard narcissistic traits. He’s grandiose and finds a way to bring attention to himself in any situation. Gob’s primary profession is “Illusionist” (as opposed to the lesser “Magician”). He exhibits extreme insecurity, masked by bravado: Gob is desperate for his father’s approval, overcompensates for failures with grandiose claims, and takes any slight to his reputation extremely personally. He frequently demonstrates entitlement and exploits others, including his brother Michael (for money and favors) and women (for attention to his crying fits). He lacks empathy and self-awareness, never accepts blame, drives a Segway everywhere as a status symbol…</p><p>We also see behaviors of Gob that aren’t exactly narcissistic traits in themselves but can be attributed to them. For example, Gob often embarks impulsively on risky careers other than magician, such as religious speaker-ventriloquist, hot cop, and surrogate father. One-off ventures include a banana-stand arson scheme, selling the family boat to drug dealers, and something with bees (?). All of these were quickly abandoned upon encountering challenges. Not to be outdone by fiction, real-life narcissists are known for risky financial behavior, which can be attributed to their belief that they are exceptional. They have “magical” thoughts about money and fantasize about success. They’re overconfident and vulnerable to flattery from scammers. They tend to engage in schemes like MLMs and crypto speculation, and they’ll quickly abandon a scheme upon failure. They tap family and friends to fund these schemes, causing financial chaos and ruin.</p><h4>T.P.</h4><p>I almost certainly experienced the phenomenon of narcissistic personality (I’m not a psychology expert, but <a href="https://en.wikipedia.org/wiki/Narcissistic_personality_disorder">I connected the dots</a>) a few years ago as an early hire at a startup company. I originally posted the following story to a forum dedicated to the topic of narcissistic abuse.</p><blockquote>I actually helped hire the guy when the team was still really small. I rooted for him after his spectacular interview performance. He was a great showman and I got the impression he was highly competent. I thought I had a pretty good sense of a person’s level of self esteem and I was convinced. However I did detect a bit of arrogance, and I gathered that he had the expectation of being viewed as very intelligent.</blockquote><blockquote>We even texted back and forth about the role, and boy was he a talker. He was awfully friendly for someone I had just met, you know?</blockquote><blockquote>Within his first few days he came up with some very pretty technical designs. I mean, they looked perfect. They were intended to replace stuff we had come up with thus far and I figured since he was so competent that he was doing us a favor. He emphasized that we all should contribute to the design, that we should all have a say in what we build… but the design was polished like something out of a textbook, so how could we feel comfortable messing with it at all?</blockquote><blockquote>A few weeks in, he contributed some work and I reviewed it. I found some errors and remarked on them. Boy, that did not go over well. He stopped opening up his work for review after that. Oopsie!</blockquote><blockquote>I started working on a big project of my own design for a while. It was going well and was totally transparent to the organization. I demoed it a few times and it was well received. After a few weeks he decided he needed to build the exact same thing I was building, but differently. That was when I started to suspect he was trying to pull the rug out from under me.</blockquote><blockquote>Of course since he was in a higher position and upper leadership was convinced of his brilliance, his work became preferred for the requirement. To his credit, what he built was cool and worked, but it was very sloppy and no one could understand it. I was upset about having to abandon a month of work, but he seemed oblivious to this… even unempathetic.</blockquote><blockquote>Now, as you might expect from his reaction to my earlier review of his work, he started making our boss (a decent guy) angry with the lack of transparency. He seemed to expect special freedom to not report on progress nor make his work accessible for collaboration.</blockquote><blockquote>As with his initial designs, he told the team we were welcome to contribute to what he was doing. Oh joy! Well I tried for a while but he restricted my contributions to very minor things like “cleaning up” things. Work you might expect a “junior” of my profession to do. So after a while I just started to avoid him, working on other things such as the actual product requirements.</blockquote><blockquote>At some point I learned that he had been ostracized at his last company. Having seen all his annoying behavior I was glad to hear that at least his last company could put him in his place.</blockquote><blockquote>I haven’t mentioned one of the worst things yet. He wanted me to think he was my friend throughout all this. He complimented my shirts whenever they had brand logos on them. Also he could never, ever admit being wrong about anything. When I would start telling him something he would always interrupt and act like he already knew what I was going to say.</blockquote><blockquote>[…]</blockquote><p>I will say that this writing doesn’t adequately capture my emotional suffering or the damage to the culture of that fledgling organization that I had worked to cultivate. Another tidbit: the guy drove a huge, glittery-white Mercedes-Benz SUV — what kind of software developer owns a car like that?</p><p>Fast-forward: I left the company soon enough and after that, others started bowing out. T.P. got himself a promotion to VP (meaningless under the circumstances); he subsequently moved himself out of the common open-office area and into a private office (all the others in the suite remained unoccupied); within another few months the business went under.</p><h3>Narcissism Explained</h3><p>It’s about time I make it clear that I am not a psychology/counseling professional and all my information is based on personal research and casual experience. If you believe you’re suffering from abuse of any kind, please seek help from people who are qualified to help.</p><p>This topic is a dark rabbit hole and can challenge some basic assumptions about human nature. Why do I feel compelled to write about it? I have struggled with numerous narcissistic people at work and would like others to benefit from my experience. I’ve also found that existing literature on narcissists in the workplace tends to be a little too superficial or lacking in practical guidance. Dangerous personalities are pervasive enough in workplaces and our culture at large that we all benefit from some awareness.</p><h4>What Is [a Narcissist / Narcissism / NPD]?</h4><p>These words get thrown around a lot these days. A few definitions:</p><ul><li><em>Narcissism</em> is a personality pattern characterized by a grandiose self-image, need for admiration, and lack of empathy. It involves a deep focus on oneself and one’s own needs at the expense of others’ feelings and perspectives. In itself this pattern doesn’t qualify as a disorder; in some environments such as corporations with competitive cultures, these traits might serve an individual well and lead to personal gain (though they probably won’t benefit anyone else).</li><li>A <a href="https://my.clevelandclinic.org/health/diseases/9636-personality-disorders-overview"><em>personality disorder</em></a> is a “long-lasting, disruptive pattern of thinking, behavior, mood, and relating to others.” Cases of personality disorder usually arise from childhood trauma and are difficult to treat. PDs are distinct from emotional (mood) disorders like anxiety. They’re also in a different category from cognitive disorders like autism and ADHD.</li><li><em>Narcissistic Personality Disorder</em> is also known as pathological narcissism. For diagnosis, the <a href="https://www.ncbi.nlm.nih.gov/books/NBK556001/">DSM-V</a> requires a subject to demonstrate 5 of 9 narcissistic traits. People with NPD suffer from poor mental health and unstable relationships. They’re also notorious for being resistant to mental health care, so they often go undiagnosed.</li><li>“<em>Narcissist</em>” is an imprecise term that describes someone with narcissism (not necessarily diagnosed with NPD).</li></ul><p>Note that “narcissism” in this article generally refers to an unhealthy or pathological form of it. A degree of <a href="https://www.psychologytoday.com/us/blog/contemporary-psychoanalysis-in-action/201609/what-is-healthy-narcissism">healthy narcissism</a> allows a person to experience joy and confidently take up space in the world (without being an asshole).</p><p>Narcissism is one of the “dark triad” personality profiles. As shown in this Venn diagram, narcissism shares certain “toxic” traits with the other profiles in the triad, Machiavellianism and psychopathy. Sometimes, sadism is included in a “<a href="https://www.linkedin.com/pulse/dark-tetrad-4-toxic-leaders-you-meet-organisations-quentin-jones/">dark tetrad</a>” of personalities, but it seems redundant, at least to an observer, as the behavior of all dark triad types can be quite sadistic (satisfying by way of hurting others).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*WNNb9ZmzOEqT9rfs.png" /><figcaption>Source: <a href="https://raybwilliams.medium.com/signs-that-your-co-worker-could-have-a-dark-triad-personality-disorder-6da74ddcbd16">https://raybwilliams.medium.com/signs-that-your-co-worker-could-have-a-dark-triad-personality-disorder-6da74ddcbd16</a></figcaption></figure><h4>Analogues</h4><p>The metaphor of “emotional vampire” can help to understand narcissism. Vampires are initially charming. They lack a reflection — they’re blind to their true selves. Victims must “invite in” (be vulnerable to) a narcissist for them to be able to do harm. When they do, the narcissist will sink their fangs in and drain them of their emotional energy.</p><p>Examples of narcissistic characters in film include Charles Foster Kane in <em>Citizen Kane</em> (1941), Joan Crawford in <em>Mommie Dearest</em> (1981), and <a href="https://www.psychologytoday.com/us/blog/doesnt-get-any-better/201909/tangled-escape-the-5-story-tower-narcissistic-abuse">Rapunzel’s stepmother in <em>Tangled</em> (2010)</a>. There are many <a href="https://www.clyverose.com/post/narcissism-in-fiction">examples in literature</a> as well. In video games, there’s <a href="https://www.thegamer.com/red-dead-redemption-2s-dutch-van-der-linde-is-a-textbook-narcissist/">Dutch van der Linde in <em>Red Dead Redemption 2</em></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*bE92wjBuDjxKuaQppqrflQ.jpeg" /><figcaption>Faye Dunaway raging over wire hangers</figcaption></figure><h4>What causes narcissism?</h4><p>Narcissistic traits are thought to originate in early childhood as a response to neglectful, abusive, or pampering treatment by parents. In the YouTube series “<a href="https://www.youtube.com/watch?v=h-a98NJWmoI">Surviving Narcissism</a>,” Dr. Les Carter explains:</p><blockquote>The troubling circumstances that a narcissist can’t really come to terms with prompts them to become <em>bad. …</em></blockquote><blockquote>I recall a man who would say, “I grew up with a father who was harsh and mean and had a really nasty temper and also had an older brother who would do the same thing…” And this man struggled as a result with dating and work settings and developing friends. Looking at these troubles and difficulties he had, he decided to himself, “I’m never going to be vulnerable with anyone again! I don’t really like people, and when someone differs from me, I’m just going to make them miserable.” …</blockquote><blockquote>Often when narcissists struggle with their difficulties and they go more and more in the direction of being bad, you’ll find that they become morally defective, they become harmful in the way that they engage with people… and then, they transfer their disturbed feelings toward you, and <strong>the disturbed becomes the disturb-<em>ing</em> person</strong>.</blockquote><h4>NPD as “Arrested Development”</h4><p>The field of psychoanalysis (Freudian psychology) defines pathological narcissism in a way that at least seems useful for illustration. As a disclaimer, psychoanalysis isn’t generally supported by empirical research, but is based upon clinical observations and <em>spicy </em>methodologies like dream analysis. Psychoanalysis occupies a kind of middle ground between general psychology and cultural/philosophical theories about human nature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c_yn7hPog2Sz17zW.jpg" /><figcaption>Source: <a href="https://psychodynamicpsychology.com/melanie-klein-paranoid-schizoid-depressive-position/">https://psychodynamicpsychology.com/melanie-klein-paranoid-schizoid-depressive-position/</a></figcaption></figure><p>This diagram illustrates the <a href="https://en.wikipedia.org/wiki/Object_relations_theory">object-relational</a> concept of good/bad splitting, which characterizes the relations of the <em>psyche</em> occupying the “paranoid-schizoid position” (at less than 3 months of age, normally) to external <em>objects</em>, such as the infant’s mother. The relation of the self to “good” objects is love and to “bad” objects is hate. “Good” represents the savior, “bad” the persecutor. In both relations the psyche <em>projects </em>part of itself onto an object as a way of defensively identifying it, and it <em>introjects </em>or internalizes that identity to form a model of the self.</p><p>The psychoanalytic theory is that adult narcissists are stuck in this position, often as a result of childhood neglect. With a scarcity of “good” object relations they may intensify good/bad splitting as a way to preserve the good while excessively projecting “bad” onto others. They never learn to <em>integrate</em> good and bad into complex objects, so they’re incapable of seeing others as whole individuals. Instead, they project either the “savior” or “persecutor” character onto a given person, often flipping from one to the other based on momentary perceptions of behavior.</p><p>A few notes: I love that this theory compares the emotional maturity of narcissists to that of literal babies. Also, it provides a theoretical constraint for the “5 of 9 traits” diagnostic criteria, by which a pathological narcissist otherwise <em>could</em> have affective empathy while also being absorbed in grandiose delusions (not likely).</p><h4>Narcissistic emotions</h4><p>It isn’t too hard to infer from the object relations theory what psychology has verified about <a href="https://www.psychologytoday.com/us/blog/finding-new-home/202010/one-emotion-the-heart-narcissism">narcissistic emotional states</a>. Their core emotions are anger, rage, and contempt: to a narcissist, anyone who disagrees with them, criticizes them, asserts boundaries, or otherwise challenges the narcissist’s false reality, is a “bad object” deserving punishment. They also experience seething envy when others have achieved or obtained something better than what they have. They fear the collapse of their image of superiority and perfection.</p><h4>NPD subtypes</h4><p>While various categorization strategies have been applied to NPD, <a href="https://psychiatryonline.org/doi/10.1176/appi.ajp.2008.07030376">three subtypes</a> are commonly recognized: fragile (vulnerable), grandiose/malignant, and high-functioning/exhibitionistic.</p><blockquote>Fragile narcissists suffer the most; they have the poorest global adaptive functioning and the highest comorbidity with major depressive disorder and generalized anxiety disorder. Grandiose/malignant narcissists have the most problems with substance abuse and the most externalizing behavior (e.g., spouse abuse). High-functioning/exhibitionistic narcissists have relatively good adaptive functioning and less psychiatric comorbidity.</blockquote><h4>Another dimension: overt vs. covert</h4><p>The official diagnostic manual doesn’t distinguish between overt and covert narcissism, but the difference is useful in clinical and research contexts. In some articles (<a href="https://www.sciencedirect.com/science/article/abs/pii/S0191886915003384">1</a>, <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC8426529/">2</a>), <em>overt</em> is used to describe grandiose and exhibitionistic narcissism, and <em>covert</em> is equated to the vulnerable/sensitive type. In Freudian psychology these types are associated respectively with extraversion and introversion.</p><h4>The narcissistic relationship pattern</h4><p>I previously described a cycle of behavior that malignant narcissists tend to get stuck in with businesses and careers, but their peak destructive behavior surfaces in their most intimate relationships, and a common series of events tends to play out in each of them. This is usually illustrated as a four-phase pattern:</p><ol><li><strong>Love bombing/idealization phase<br></strong>Initially, the narcissist will foster a rapid, intense attachment through flattery, mirroring of interests/values, grand promises, and constant attention. This can involve marathon-length conversations resembling a crafty sales pitch.</li><li><strong>Devaluation phase<br></strong>The narcissist will start testing their partner’s tolerance and creating dependency. They’ll commit increasingly hurtful violations of boundaries, collect data on the partner’s vulnerabilities, subtly demean them, and isolate them from support systems. Eventually the narcissist will have diminished their partner’s power and self-esteem enough to withdraw affection entirely, replacing it with gaslighting, harsh criticism, and silent treatment. They’ll force their partner to work for their approval and intensify their triangulation with other parties to further isolate and damage the reputation of their victim.</li><li><strong>Discard phase<br></strong>Eventually the abused partner has sunk so deep into depression, anxiety, confusion, and low self-esteem, that the narcissist can no longer get their “supply” of emotional energy from them. In other words, the vampire has exsanguinated them and regained some strength. The narcissist will be pretty satisfied with themselves at this point. Being unconcerned with moral constraints around fidelity, the narcissist may engage another partner with love-bombing in a concurrent cycle.</li><li><strong>Hoover phase</strong><br>In this phase (named after the popular vacuum cleaner brand), the narcissist’s emotional strength has waned rapidly from a deficit of narcissistic supply. They’ll try to thwart a frustrated partner’s escape from the cycle in the most nauseating ways imaginable: begging, manufacturing crises, guilt-tripping, and continuing to manipulate third parties into applying pressure on the abuser’s behalf. After that, the narcissist may flip back to the beginning of their playbook and apply another round of love bombing, restarting the cycle.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wfXVnUZRvfOeJzSv" /><figcaption>Source: <a href="https://www.instagram.com/p/C2RBiV4syZu/?utm_source=ig_web_copy_link&amp;igsh=MzRlODBiNWFlZA==">https://www.instagram.com/p/C2RBiV4syZu</a></figcaption></figure><p>This begs the question of what happens when narcissistic supplies dry up and their love-bombing fails. The narcissist will become desperate and likely will double down on hoovering and idealizing of new and former targets, as their stubbornness and lack of introspection inhibits them from pursuing different and potentially healthier strategies.</p><h4>Narcissistic targeting</h4><p>Some individuals are more susceptible to being targeted for abuse by narcissists than others, although anyone can be a victim. Targets of narcissists have a combination of what narcissists lack (inner strengths) and some vulnerability that the narcissist can exploit.</p><ul><li>“People pleasers” avoid conflict, seek approval, keep the peace, and put others first. Even in relationships with healthy people, these folks will give more than they take.</li><li>High achievers are another type that narcissists like to sink their fangs into. Narcissists are fundamentally lazy and will drag highly talented and productive people down in order to maintain the illusion of their own superiority. They’ll accomplish this through bullying, humiliation, and any other toxic behavior that their organization allows.</li><li>People with <a href="https://www.psychologytoday.com/us/conditions/borderline-personality-disorder">borderline personality disorder</a> tend to form <a href="https://www.psychologytoday.com/us/basics/trauma-bonding">trauma bonds</a> that are hard to break and can keep them stuck in a narcissist’s abuse cycle.</li><li>Children of narcissists end up being trained to tolerate and subconsciously seek out narcissistic treatment. They may develop a set of traits known as <a href="https://www.newportinstitute.com/resources/mental-health/echoism/">echoism</a>, which is kind of the opposite of narcissism and includes people pleasing, distrust, and conflict avoidance.</li><li>A less commonly recognized target for narcissists is autistic people. They tend to have an underdeveloped ability to process social information, so they recognize narcissistic social behaviors less readily and have more trouble setting boundaries. Their behaviors also look like a little like echoism in that they tend to “mask” their true personality traits to gain acceptance. See: <a href="https://kristenhovet.medium.com/do-autistic-people-attract-narcissists-more-often-than-non-autistic-people-4200d795e8c4"><em>Do Autistic People Attract Narcissists More Often Than Non-Autistic People?</em></a></li><li>In romantic/domestic relationships where one partner is narcissistic, women are usually the victim. About <a href="https://emedicine.medscape.com/article/1519417-overview#a5?form=fpf">75% of people diagnosed with NPD are men</a>. This gender imbalance is due in part to <a href="https://evolvebyskd.substack.com/p/the-connection-between-narcissism">patriarchal expectations and power structures</a>.</li></ul><p>A common thread of susceptibility to narcissistic abuse is <em>openness</em>. Considering that <a href="https://hbr.org/2018/11/a-new-way-to-become-more-open-minded">openness is an essential trait in healthy relationships and organizations</a>, it’s clear that dark-triad behaviors such as manipulation and lying have no place in those contexts.</p><h4>Ugly truths</h4><p>A difficult thing to grasp about narcissists is that they actually believe their own lies. More than that, they typically <em>don’t know</em> that they’re lying because they’re actually <a href="https://www.healthyplace.com/personality-disorders/malignant-self-love/narcissists-confabulated-life">confabulating</a> — creating their own reality and coercing others into participating in it.</p><p><a href="https://thriveworks.com/help-with/relationships/can-a-narcissist-change">Narcissists almost never change</a> because the disorder is hard-wired from infancy and is self-perpetuating. Growth requires hard work and persistence, but even if (hypothetically) a narcissist were to realize they’re toxic and are causing harm, their narcissistic pathology justifies it in their mind. They feel no remorse.</p><p>It appears that, because of their calculating nature and low impulsivity, <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC5191918/">people with NPD attempt suicide at significantly lower rates</a>, but their attempts tend to be carefully planned and lethal. They’re particularly prone to suicide <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC3057651/">following life events that challenge their self-esteem, such as being fired from work</a>.</p><h3>Narcissists at Work</h3><p>Now that I’ve painted that picture of narcissism in broad strokes, I’ll go ahead and focus on the main subject: narcissists in the workplace.</p><h4>What are the signs someone might be narcissistic?</h4><p>With coworkers, some telltale behaviors are:</p><ul><li>Lots of name-dropping of influential connections or companies in the industry</li><li>Repetitive/excessive sharing of supposed achievements</li><li><a href="https://journals.sagepub.com/doi/full/10.1177/1745691619873350">Obsession with status and titles</a></li><li>“<a href="https://humanmagnetsyndrome.com/hmsblog/induced-conversation-is-narcissists-most-potent-weapon/">Induced conversations</a>”, or coercing you into 1:1 conversation with unclear purpose</li><li>Stonewalling: ignoring your messages, acting like you don’t exist</li><li>Backstabbing of colleagues</li><li>Fishing for personal information (cataloguing your vulnerabilities)</li><li>Monopolizing conversations, often bringing it back to themselves</li><li>Dismissing others’ concerns/ideas</li><li>Changing decisions that weren’t “their idea”</li><li>Major differences between their public &amp; private personas (typically, they’re more critical in private)</li><li>Violating standards/rules for “efficiency” while holding others to impossible standards</li><li>Creating dependency on their supposed expertise — this may come with offers of “mentorship”</li><li><a href="https://articlegateway.com/index.php/AJM/article/view/2627">Amorality</a></li><li>Contempt for principled/democratic decision-making</li><li><a href="https://www.psychologytoday.com/us/blog/love-in-the-age-narcissism/202102/lying-die-why-narcissists-may-lie-about-their-health">Exaggerating health issues</a> to garner sympathy</li></ul><p>When you’ve interacted with one of these people, you may feel frustrated and violated; it might be like the feeling of walking into your home and finding it’s been burglarized.</p><p>Narcissistic <em>managers</em> may exhibit any of the above, but given the power granted to them in their role, they can engage in additional controlling and sabotaging behaviors such as:</p><ul><li>Taking credit for team successes, blaming their team for failures</li><li>Micromanaging but also being unavailable when needed</li><li>Showing favoritism to create competition</li><li>Making veiled threats about job security</li><li>Expecting constant availability</li><li>Loyalty testing</li><li>Gatekeeping opportunities</li><li>Communicating in formal channels and involving higher-ups to establish dominance</li></ul><p>When you’ve interacted with a narcissistic manager, you’ll probably feel devalued and alienated. It probably goes without saying that <a href="https://www.nature.com/articles/s41598-024-60202-7#Sec17">your boss is more likely to be a grandiose narcissist</a> than your coworkers are.</p><h4>How do narcissists get away with this?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*yqhByOpsAmDvOjga.gif" /><figcaption>The Wicked Witch of the West commanding her air force</figcaption></figure><p>In a discussion about narcissism in group (organizational) settings, it’s important to address the concept of the <a href="https://www.psychologytoday.com/us/blog/women-autism-spectrum-disorder/202010/are-you-narcissist-s-flying-monkey"><em>flying monkey</em></a><em>. </em>The term comes from <em>The Wizard of Oz</em>, in which the Wicked Witch of the West commands flying monkeys to capture the protagonist Dorothy and her friends.</p><p>Narcissists often recruit others to serve their agendas, and some of those recruits are at least partially aware of those agendas but choose to go along with it anyway. Why would they subject themselves to this humiliating treatment? Leading the question a bit, Dr. Les Carter presents it in another way: <a href="https://youtu.be/JCnQslcq7pQ?si=Kk6vg4VUNYI3ZGO5"><em>Are Flying Monkeys Also Narcissists Or Just Cowards?</em></a></p><blockquote>They’ve been groomed with promises. … Typically that flying monkey is a weak-willed, non-assertive kind of person. … Often, the flying monkey is quite gullible. … They tend to be very impressed by the narcissist and vicariously, they can take delight in the ways the narcissist wields power. … To that flying monkey, the narcissist represents power, and that’s more appealing to the flying monkey than honesty or decency or healthy principles. And then we ask the question, are they themselves narcissists or are they just cowards? How about if we were to say: both?</blockquote><p>There are other reasons narcissistic behavior might be tolerated and even rewarded by a company’s leadership. Narcissism is a natural driver of achievements because it leads to recognition that reinforces their sense of superiority. A narcissist also might fool leaders with charm and grandiose promises (forms of “love bombing”).</p><h4>What are signs that narcissistic abuse is occurring?</h4><p>An employee may show various signs of suffering from narcissistic treatment:</p><ul><li>Loss of enthusiasm</li><li>Loss of interest in career path</li><li>Isolation or decreased social engagement</li><li>Working late or early hours to avoid conflict</li><li>Hesitance to take credit for work or speak in meetings</li><li>Questioning their own competence or sanity</li></ul><h4>How do I avoid being a victim of a narcissistic coworker/boss?</h4><p>You should first consider how disruptive someone’s narcissistic tendencies are to your success and well-being and how aggressively they’re targeting you. If they aren’t in close proximity (organizationally) and you’re out of their crosshairs, try to keep it that way. Refrain from calling them out on their errors (granted that they can be quite frequent and glaring) to avoid becoming a target of revenge. Be vigilant for signs of colleagues being impacted, but otherwise, you’ll probably be okay. Their behavior is primarily your employer’s problem.</p><p>If you believe you’re being targeted (because you’re a high performer or neurodivergent or simply in the same room as them too often), please don’t skip the section below on what <em>not</em> to do, and also <em>do</em> start to adopt some behaviors that will be crucial in protecting yourself:</p><ul><li>Document all your interactions with the suspected narcissist, keeping track of the date each one occurred. It doesn’t matter how innocuous the interaction may seem as you might realize later on that they were manipulating you. <em>Every </em>conversation they induce with you should be considered potentially harmful. Take screenshots of conversations that take place in your chat app. You may be compelled to report abuse to HR at some point, and that report would need to be thoroughly factual with timelines and focused on the impact to you and the business.</li><li>Establish boundaries, but this doesn’t mean proclaiming your boundaries to them. They will take offense and adjust their strategy to tear those boundaries down with brutal efficiency. Boundaries means minimizing 1:1 conversations, sticking to written channels, and requiring written confirmation of their directives. Decline all personal/social invitations.</li><li>Maintain your support systems. Connect with trusted colleagues as well as your external network. Seek mental health care. Do whatever you need to do to maintain psychological wellness and perspective.</li><li>Manage your emotions. Narcissistic behavior will often trigger anger, frustration, and confusion, but <a href="https://www.charliehealth.com/post/what-is-reactive-abuse">your expression of those feelings is what the narcissist is looking for</a>. They know that in professional settings, those expressions are seen as weakness and instability, and narcissists seek to humiliate you. Accept that your feelings are valid, but always consider the consequences of reacting publicly.</li></ul><p>Circling back to “dark triad” personality traits, <a href="https://www.linkedin.com/posts/johnpcutler_challenges-navigating-the-dark-triad-if-activity-7251752915499982848-iPxW">one writer on LinkedIn suggests</a> being careful not to mistake one type of toxic personality for another:</p><blockquote>If you treat someone high in Machiavellianism as if they are high in psychopathy, you risk misinterpreting their savvy/strategic, long-term manipulation as impulsive actions, leaving you unprepared for their calculated tactics. They are playing 3d/4d chess.</blockquote><blockquote>….high in psychopathy as if they are high in narcissism, you risk enabling not-great behavior while trying to appeal to their sense of self-worth (which may not exist).</blockquote><blockquote>….high in narcissism as if they are high in Machiavellianism, you risk attributing their actions to a grand strategy (4d chess) when they might just be driven by the need for admiration. You’ll overestimate their strategy skills.</blockquote><blockquote>….high in narcissism as if they are high in psychopathy, you risk responding aggressively or defensively. You think they lack conscience, while they might be seeking admiration and validation. A less confrontational approach [may be] more effective.</blockquote><h4>What should I NOT do around a narcissist?</h4><p>Don’t fall into <a href="https://www.linkedin.com/pulse/narcissists-trap-sneaky-essence-emotional-hasaan-mansoor-gmbpss-xpruf/">their traps</a>, which are often set within induced conversations. One of those is the <strong>information trap</strong>. They might ask for “confidential” feedback about others, make “just between us” remarks, or bait you into criticizing others. You can defeat this by minimizing conversations and keeping them focused on tasks and solutions.</p><p>They might set <strong>loyalty traps</strong> by testing your reaction to their toxic behavior, forcing a choice between them and others, or assigning work that is non-impactful and isolating. They might request inappropriate favors, which can be anything from doing their work for them to illegal and immoral acts. Your defenses against this are documenting their demands and maintaining relationships with trusted colleagues. Also, be especially careful not to fall into the trap of appeasing them in a way that violates your standards or those of your organization. Loyalty to a narcissist is a one-way street.</p><p>Their <strong>career traps</strong> include promises of mentorship that create dependency, engaging you in very niche activities to limit your mobility, and taking credit for your transferable achievements. In my career I’ve often seen this take form as rejection and unfounded criticism of good contributions.</p><p>It’s important to stay humble and realize that you almost certainly will not beat a narcissist at their game. Mastery of that game —the abuse cycle that reinforces their grandiose false self — keeps them functioning and gives them purpose.</p><h4>A dim outlook</h4><p>Even if you follow all this advice, a narcissist on a campaign to destroy you might succeed, leaving you wrecked while they relish in false validation of their superiority. Consequences or justice for a narcissist’s actions usually will never manifest.</p><p>Taking action to stop a narcissist’s behavior can be more stressful than it’s worth. Maybe you don’t have much support from your organization, possibly as a result of the narcissist’s efforts at isolating you and damaging your reputation. In that case, any report to HR might not be seen as credible, and if the narcissist finds out, they might take further calculated, vindictive action to eliminate you. In this situation you probably have only one remaining option: leave. Maybe switching to another team in the organization could work, but otherwise, start looking for another job.</p><p>If you embark on a path of revenge against a narcissist, (a) you’ll debase yourself by doing what they do (but probably less skillfully); and (b) they’ll just take your actions as validation of their own victimhood. I’m sorry to admit that the cliché is true: the best “revenge” is living well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e5VGRpOnOUNibOz7" /><figcaption>G.O.B. creates “illusions”</figcaption></figure><h4>Wait, what’s with the title, “Smoke, Mirrors, and Extinguishers?”</h4><p>“Smoke and mirrors” conveys the deception, false reality, and manipulation tactics involved in narcissistic abuse. “Mirrors” also refers to how abuse can reflect back on an abuser, once a victim starts to react negatively. “Extinguishers” are the tactics we can employ to put out fires of chaos and anxiety that are fueled by narcissists, and they’re also the friends and colleagues who have our backs. I don’t know, it’s a catchy title.</p><h4>Further reading</h4><ul><li><a href="https://www.shrm.org/topics-tools/news/managing-smart/damage-done-dealing-narcissists-workplace"><em>The Damage Done: Dealing with Narcissists in the Workplace</em></a></li><li><a href="https://www.som.org.uk/occupational-health-learning/Psychological%20Hazard/Narcissism-and-Narcissistic-personality-disorder-in-the-work-place.html"><em>Narcissism and Narcissistic personality disorder in the work place</em></a></li><li><a href="https://www.gsb.stanford.edu/insights/how-narcissistic-leaders-destroy-within"><em>How Narcissistic Leaders Destroy from Within</em></a></li><li><a href="https://davidburkus.com/2010/08/seven-things-to-expect-from-your-narcissistic-employee/"><em>7 Things to Expect From Your Narcissistic Employee</em></a></li><li><a href="https://www.psychologytoday.com/us/blog/life-in-the-intersection/201804/is-narcissism-the-cost-being-american"><em>Is Narcissism the Cost of Being an American?</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33f87399376c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Witch Engineering 2022]]></title>
            <link>https://lucjross.medium.com/witch-engineering-part-1-513888544d17?source=rss-9525d53f20d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/513888544d17</guid>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[halloween]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Lucas J. Ross]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 06:25:55 GMT</pubDate>
            <atom:updated>2026-04-16T20:52:53.327Z</atom:updated>
            <content:encoded><![CDATA[<p>Friends who know my spouse and I know that Halloween and the surrounding season bring us much joy. For me, it has a lot to do with living in central Texas and leaving the oppressively hot summer behind. It provides a freedom from air conditioned spaces that invariably sparks my creative energies.</p><p>In the year 2020, coronavirus brought some anxieties that put a twist on how my creativity manifested. From this, together with fond memories of childhood trick-or-treating, a tradition I call the “spooky hackathon” was born.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEKR413ixLuE&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEKR413ixLuE&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FEKR413ixLuE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad0566ae673aad34a48967f28132173f/href">https://medium.com/media/ad0566ae673aad34a48967f28132173f/href</a></iframe><p>My day job typically consists of backend server software development. It’s all pretty abstract and nothing I build for work can be held in hand or heard/smelled/tasted. I figured building an animatronic would be a nice diversion because it’s so “close to the metal.” It’s a little like the difference between cooking a meal yourself and authoring one of those life stories for a recipe on the Internet. The smell of burning solder and plastic is a little sickening but also part of a very sensory and intimate engineering experience. In enterprise software, the fastest code build &amp; deploy processes take minutes and the reward is no more than a checkmark on your screen, and you’re forced to find your dopamine hit elsewhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*U_TnN_3KUL09LnNcjOOStQ.png" /><figcaption>Floor piano, 2021</figcaption></figure><p>For Halloween 2021 I decided to tone down the creepiness a bit and make a big floor piano. I incorporated a game where it plays a musical interval, and when a trick-or-treater repeats it by stepping on the matching keys, treats are dispensed (from the candy conveyor I made for the previous year’s display). Visit <a href="https://www.instagram.com/p/CVt6gSvtVAM/?utm_source=ig_web_copy_link">this Instagram post</a> for videos. (For some reason Medium no longer lets you embed Instagram posts in an article).</p><p>My Halloween 2022 project was more ambitious. The rest of this article is devoted to showcasing its development.</p><h3>The Weejee Board</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*ktkMUAjgyHwvu_dDjsCU5g.png" /></figure><p>Visit <a href="https://www.instagram.com/p/CkZv8adtc7N/?utm_source=ig_web_copy_link">this Instagram post</a> for videos of my “weejee” in action.</p><p>I think I got the inspiration for this from a friend who mentioned Ouija(TM) boards at a party. Yes, “Ouija” is a registered trademark of a board game company and I honestly haven’t made much effort to avoid infringing on it besides using the spelling “weejee.” Anyway, I figured it would be fun to have a weejee board with a planchette (the pointy piece that players traditionally move around with their hands) that moves around by itself to answer questions. As an experienced software developer I had no doubt that this was doable. The ways people these days are having their floors vaccuumed and music selected to play on the stereo are a couple of encouraging realities that came to mind. It would be a haunted hybrid Alexa-Roomba. I started the project at the beginning of October, 2022.</p><h4>Implementation</h4><p>One strategy that I adopted for this project that I believe was critical to its success was defining constraints early on, both to simplify the implementation and to optimize the end result for the user (trick-or-treater) experience. Robotics is a complex field with which I was relatively unfamiliar when I started on this, so it was important to identify the simplest solutions to various problems to ensure I’d have an enjoyable product within my timeline of four weeks. Also complicating the matter was that it’s hard to stare at a computer screen anymore after a full day of doing so for my day job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYDshOmuWdDWnrJv52pmrQ.png" /><figcaption>Not the final design</figcaption></figure><p>This initial design served me well to the end with a few notable exceptions. I wrote a Spring Boot server in Kotlin, not Java, because Kotlin is a <a href="https://kotlinlang.org/docs/comparison-to-java.html">better</a> language. <a href="https://github.com/lucjross/weejeebot/tree/8d68f55387049e983f9c1a7869c7713936df4ae9">Check out my source code</a> if you like.</p><p>I used the <a href="https://www.arduino.cc/">Arduino</a> microcontroller platform because it’s a classic, popular choice and I had already become familiar with it through other projects (prior years’ Halloween displays and some home automation tinkering). C++ isn’t my best language, but Arduino doesn’t demand particularly fancy programming technique. Practically speaking, being limited to a single execution <a href="https://en.wikipedia.org/wiki/Thread_(computing)">thread</a> and kilobytes of RAM and program space are what really set it apart from programming for modern general-purpose computers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*VH6GaBiVoFFuFt89" /><figcaption>Zumo tank with ankle-destroying plow attachment</figcaption></figure><p>The basic platform for the robot is the <a href="https://www.pololu.com/product/2509">Zumo</a>. It’s about four inches wide and provides headers for a classic-form-factor Arduino. One major challenge with the Zumo was that a lot of the Arduino I/O pins are used by the Zumo driver shield. As I’ll show later, I added a second Arduino for functionality that the Zumo-driving Arduino couldn’t accommodate. It was also tricky to get a feel for how activating a motor with a “speed” (a signed integer representing the degree of power applied to the motor) would correspond to actual velocities; some independent factors, including friction of the treads on the surface and the amount of juice left in the batteries, make it difficult to predict how far it will go in some period of time. Some experiments were done in advance to define constants that predict straight-line velocities, and the bot takes measurements after periods of movement to figure out where it has really ended up.</p><p><strong>Location &amp; orientation. </strong>An early idea was to install a camera on the underside of the planchette pointing downward, so that a microcontroller could take pictures of the board at various times to determine both location and orientation. This seemed possible because the board surface would be covered mostly with complete sets of numbers and letters as well as distinct drawings, which means a picture taken of any given (say) 2cm by 2cm square on the board could be reliably matched up with a board location without any other reference. I eventually realized, however, that the techniques used to do this share a solution space with some of the most challenging ones in computer science, namely the area of <em>computer vision</em>. I spent a few evenings playing around with the most popular open-source CV library, <a href="https://opencv.org/">OpenCV</a>, but found the learning curve so steep that it was doubtful that I could figure it out within the timeline.</p><p>I needed another option, and when I brought it up with my spouse, she noted that on <em>Criminal Minds,</em> the detectives or whoever often locate things by triangulating. That inspired me to look for solutions that could provide distances between the planchette and the edges of the board. The most obvious option for that was the popular <a href="https://lastminuteengineers.com/arduino-sr04-ultrasonic-sensor-tutorial/">ultrasonic sensor</a>. They’re inexpensive and provide good enough precision (+/- a centimeter or two). Some other options I ruled out were laser and infrared distance sensors; they have a minimum functional distance of 10 or 20cm, and the board is only around 60cm from top to bottom, which would leave the planchette “blind” within much of the board area. (Shorter reflections are too fast for common light-based sensors to measure, and better sensors are extremely expensive.)</p><p>To give the ultrasonic pulses something to bounce off of, I put walls around the board, just high enough to encompass the vertical span of ultrasonic transmitters &amp; receivers placed around the robot. I figured three or four of them would provide enough data for determining location.</p><p>In addition, determining orientation is facilitated by a magnetometer (an electronic compass) built into the Zumo shield. The program obtains a zero value for the <em>x</em> axis of the board by measuring the direction of Earth’s magnetic north and subtracting an operator-supplied offset for the orientation of the board itself.</p><p>At least two annoying problems came about with the ultrasonic sensors. When the planchette was oriented at angles approaching diagonals (some degrees off from either axis), pulses would bounce off walls onto other walls before getting back to the robot, causing wildly inaccurate readings (Figure 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ZaPhc5XgnNrehGO6Ic4gfQ.png" /><figcaption>Figure 1: Confused robot</figcaption></figure><p>Another issue is that within the middle area of the board, even with four sensors on the robot, location can’t be determined if the planchette is in a more-or-less diagonal orientation (Figure 2). Adding more sensors to fill the gap seemed like an overly complicated path to go down, and anyway, I only had four sensors on hand. This necessitated some further constraints on how the planchette uses sonar to determine location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*f5FDWdw8TZ6ZIEZHbrkYfA.png" /><figcaption>Figure 2: Same distances with same orientation: true location is indeterminate</figcaption></figure><p>I noticed when a pulse is sent perpendicular to a wall it virtually never results in a multiple-bounce echo. So, my solution to these problems was to constrain the robot to try to determine location only while it’s oriented toward the top of the board. (Any orientation in alignment with the <em>x</em> or <em>y</em> axis would work, but the top orientation fits the desired user experience — there’s no reason it should ever end up pointing downward.) After any stage of moving around the board, it turns to orient itself toward the top of the board, takes a little time to measure location, and then turns to where it needs to go next. I used two pairs of sensors, each placed opposite of each other. That way each pair provides two measurements that usually sum to the distance between opposite walls. When they don’t because a sensor didn’t hear the echo or some other measurement error occurred, it settles for whichever measurement is smaller (closer measurements are more accurate). This strategy provides the additional advantage of being able to calculate position without the use of trigonometric functions like arctan2, which are a lot of work for an 8-bit Arduino CPU.</p><p>Also worth noting is that it’s important to avoid crosstalk among the sensors (one sensor’s receiver getting the echo of a different sensor’s transmitter). To that end, I used the common convention of having sensors send their pulses about 20 milliseconds apart from each other. Incidentally this helps save on input pin usage: having the echoes from all the sensors come in at different times means they can all come in on the same pin instead of four of them. (For anyone thinking of duplicating this, note that diodes should be placed after sensor outputs to avoid reverse current flows.)</p><p>Location-finding was a doozy, but things went pretty smoothly from there.</p><p><strong>System architecture. </strong>I didn’t have one Arduino that would serve all functions of the system so I used two, each with different capabilities, in addition to an external application that serves as the “brains” behind the whole experience. Figure 3 illustrates the functions performed by each component and how they communicate. One thing I realized, to my discomfort, was that this ended up looking like a traditional organizational hierarchy, the structure in which all my corporate trauma has originated: a chief executive gives commands to middle management which in turn gives commands to workers who perform physical labor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhDGPKXePCFT7mth6I9ldA.png" /><figcaption>Figure 3</figcaption></figure><p>“POI” in the diagram stands for “point of interest” and refers abstractly to a letter or number contained in an answer (or a yes/no answer). This intermediate concept serves to separate concerns. The Weejee Service tells the net/display MCU (microcontroller unit) what answers to give, the net/display MCU splits those up into individual POIs and tells the Zumo MCU what POIs it needs to visit, and the Zumo MCU queues those POIs up and translates them into x/y coordinates to which it will physically go.</p><p>I designed all parts of the system to be reactive to commands over network/serial interfaces and perform tasks asynchronously. This is partly to conserve energy that would otherwise be consumed to frequently “poll” other components for states or tasks, considering that the Arduinos, motors, and LCD, together draw power from four AA batteries. It also avoids blocking operations which aren’t great with a single-threaded and interrupt-reliant processing model. For instance, when the net/display MCU sends a POI to the Zumo MCU, it doesn’t wait around for the Zumo to finish its various movements. The Zumo MCU sends a signal when it’s done spelling something out, and the net/display MCU reacts by displaying a smiley face.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*XztAioJ2uQHBm2oXpmAEew.png" /><figcaption>“Enjoy your prophecy!”</figcaption></figure><p>The Weejee Service needs a lot more computational power than an Arduino can provide, as it performs bidirectional streaming of audio to Amazon’s Transcribe service in exchange for transcriptions. It also needed some logic to recognize keywords and syntax in those transcriptions to identify question types (who, what, when, where…). An early constraint I placed on the system was that it won’t try to be ChatGPT or anything. This logic picks a semantically-valid but not-necessarily-sensical number or word from a list based on the question type. This had pretty entertaining results, but I made it part of the laptop-based backend to accommodate future improvements that might require more computing power.</p><p>Indeed, a year later, I integrated a LLM with Google’s PaLM API — since decommissioned and replaced with their Gemini API — to provide more interesting responses. I used this system prompt, interpolating the Amazon Transcribe output:</p><blockquote>Pretending you are a psychic, provide a cryptic answer to the following question using a single word with fewer than ten characters: “&lt;user question&gt;” (Don’t say any of these words: [&lt;previously provided answers&gt;])</blockquote><p><strong>Other notables</strong></p><ul><li>I don’t have a schematic for the connections between Arduinos and components. It was all wired up on the fly. <a href="https://github.com/lucjross/weejeebot/tree/8d68f55387049e983f9c1a7869c7713936df4ae9/arduino/sketches">The code</a> has some macros for pin assignments, and I’m happy to answer any specific questions the reader may have about how things were connected.</li><li>If someone says “hey Ouija!” before the bot is done spelling something out, it’ll stop what it’s doing and go back to the “what’s your question?” state. I thought it best to be as responsive to the user as possible.</li><li>I incorporated <a href="https://www.amazon.com/gp/product/B08G7Y87VY">this LCD</a>. The font used in the LCD is stored on the net/display MCU as a set of bitmaps, which I generated with the <a href="https://github.com/riuson/lcd-image-converter">lcd-image-converter</a> tool.</li><li>The board and planchette top are made of wood left over from a bathroom renovation. I spray-painted base coats of light brown, and members of my family and I painted everything on the board with paintbrushes. Probably not the most efficient solution —with a Cricut machine we could have make stencils for the letters — but we had fun with it.</li><li>The title of this article was inspired by a colleague, to whom I mentioned this project, calling me a “witch engineer.” I appreciated that and I’m owning it.</li></ul><h3>Conclusion</h3><p>Thanks for reading and happy Halloween!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=513888544d17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Requests from Google Pub/Sub Push Subscriptions in Spring Boot Cloud Run Applications]]></title>
            <link>https://levelup.gitconnected.com/handling-requests-from-google-pub-sub-push-subscriptions-in-spring-boot-cloud-run-applications-d686c36811a1?source=rss-9525d53f20d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d686c36811a1</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[google-pubsub]]></category>
            <dc:creator><![CDATA[Lucas J. Ross]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 12:10:48 GMT</pubDate>
            <atom:updated>2022-11-11T21:01:05.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*UAC_veT-PYRHQfBI" /></figure><p><a href="https://cloud.google.com/run/docs">Cloud Run</a> is a serverless application platform, which means apps deployed there can’t be expected to be running all the time and therefore won’t work with the default “pull” subscription type.</p><p>A push subscription calls an HTTP endpoint, which is how a Cloud Run service is triggered. There are examples of endpoints built for this purpose in <a href="https://cloud.google.com/run/docs/triggering/pubsub-push#run_pubsub_handler-java">the docs</a>, but the Java example is very basic. Here’s a decent way of writing a request handler that will work with the Spring framework.</p><p>Say you have (in Terraform) a topic for events in the lives of characters from the critically-acclaimed Showtime show, <a href="https://www.sho.com/yellowjackets">Yellowjackets</a>, and a subscription that filters on actions taken by Lottie:</p><pre>resource &quot;google_pubsub_subscription&quot; &quot;example&quot; {<br>  name   = &quot;yellowjackets-events---lottie&quot;<br>  topic  = data.google_pubsub_topic.yellowjackets_events.name<br>  filter = &quot;attributes.character = \&quot;Lottie\&quot;&quot;<br>  push_config {<br>    push_endpoint = &quot;${google_cloud_run_service.app.status[0].url}/lottie-events&quot;<br>    oidc_token {<br>      service_account_email = data.google_service_account.pubsub_invoker.email<br>    }<br>  }<br>}</pre><p>Message bodies might look like this:</p><pre>{<br>  &quot;date&quot;: &quot;1996-10-01&quot;,<br>  &quot;creepyStatement&quot;: &quot;We won&#39;t be hungry much longer&quot;,<br>  &quot;visionType&quot;: &quot;AERIAL_INFERNO&quot;<br>}</pre><p>The Spring Boot request handler could be written as such:</p><pre>@RestController<br>@Slf4j<br>public class PubSubPushController {</pre><pre>    @RequestMapping(value = &quot;/lottie-events&quot;,<br>                    method = RequestMethod.<em>POST</em>,<br>                    produces = MediaType.<em>APPLICATION_JSON_VALUE</em>,<br>                    consumes = MediaType.<em>APPLICATION_JSON_VALUE</em>)<br>    public ResponseEntity&lt;?&gt; receiveLottieEvent(<br>            HttpServletRequest req<br>    ) throws Exception {<br>        // (using Jackson)<br>        JsonNode bodyNode = objectMapper.readTree(req.getReader());<br>        String base64Data = bodyNode.get(&quot;message&quot;)<br>                .get(&quot;data&quot;).asText();<br>        byte[] data = Base64.<em>getDecoder</em>().decode(base64Data);<br>        LottieEvent event = objectMapper.readValue(<br>                data, LottieEvent.class);<br>        log.info(event.getCreepyStatement());</pre><pre>        return new ResponseEntity&lt;&gt;(HttpStatus.<em>OK</em>);<br>    }<br>}</pre><p>But I find that a bit noisy for a controller method. It has to read the raw pub/sub message, get the message.data property as text — and that’s a Base64-encoded string, so you have to decode that, and so on. We could abstract that away so we can immediately get what we need from the controller method parameter.</p><p>Let’s make a container for the method parameter, where T could be a LottieEvent:</p><pre>@Data  // (Lombok)<br>public class PubSubPushRequest&lt;T&gt; {</pre><pre>    private final T body;<br>    private final Map&lt;String, Object&gt; attributes;<br>    // you might want headers here too<br>}</pre><p>Then, implement a <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/method/support/HandlerMethodArgumentResolver.html">HandlerMethodArgumentResolver</a>:</p><pre>@Component<br>public class PubSubArgumentResolver<br>        implements HandlerMethodArgumentResolver {</pre><pre>    private final ObjectMapper objectMapper;</pre><pre>    public PubSubArgumentResolver(ObjectMapper objectMapper) {<br>        this.objectMapper = objectMapper;<br>    }</pre><pre>    @Override<br>    public boolean supportsParameter(MethodParameter parameter) {<br>        return PubSubPushRequest.class<br>                .isAssignableFrom(parameter.getParameterType());<br>    }</pre><pre>    @Override<br>    public Object resolveArgument(<br>            MethodParameter parameter,<br>            ModelAndViewContainer mavContainer,<br>            NativeWebRequest webRequest,<br>            WebDataBinderFactory binderFactory<br>    ) throws Exception {<br>        HttpServletRequest req = webRequest<br>                .getNativeRequest(HttpServletRequest.class);<br>        ParameterizedType dataType = (ParameterizedType)<br>                parameter.getGenericParameterType();<br>        Class&lt;?&gt; dataClass = (Class&lt;?&gt;)<br>                dataType.getActualTypeArguments()[0];<br>        JsonNode bodyNode = objectMapper.readTree(req.getReader());<br>        String base64Data = bodyNode.get(&quot;message&quot;).get(&quot;data&quot;)<br>                .asText();<br>        byte[] data = Base64.<em>getDecoder</em>().decode(base64Data);<br>        Object dataObj = objectMapper.readValue(data, dataClass);</pre><pre>        Map&lt;String, Object&gt; attributes = objectMapper.convertValue(<br>                bodyNode.get(&quot;message&quot;).get(&quot;attributes&quot;),<br>                new TypeReference&lt;Map&lt;String, Object&gt;&gt;() {});</pre><pre>        return new PubSubPushRequest&lt;&gt;(dataObj, attributes);<br>    }<br>}</pre><p>…and register it:</p><pre>@Configuration<br>public class WebMvcConfiguration implements WebMvcConfigurer {</pre><pre>    private final PubSubArgumentResolver pubSubArgumentResolver;</pre><pre>    public WebMvcConfiguration(<br>            PubSubArgumentResolver pubSubArgumentResolver<br>    ) {<br>        this.pubSubArgumentResolver = pubSubArgumentResolver;<br>    }</pre><pre>    @Override<br>    public void addArgumentResolvers(<br>            List&lt;HandlerMethodArgumentResolver&gt; resolvers<br>    ) {<br>        resolvers.add(pubSubArgumentResolver);<br>    }<br>}</pre><p>Finally, we can update the controller method:</p><pre>// ...<br>public ResponseEntity&lt;?&gt; receiveLottieEvent(<br>        PubSubPushRequest&lt;LottieEvent&gt; pushRequest<br>) throws Exception {</pre><pre>    LottieEvent event = pushRequest.getBody();<br>// ...</pre><p>Much better! And PubSubPushRequest can be used for other events from other subscriptions. That is, if you’re sure you really want to know what these ladies are up to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-iwf7RR2AfBpdTn2.png" /><figcaption>By now it seems pretty clear which varsity girls’ soccer player becomes “antler queen”</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d686c36811a1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/handling-requests-from-google-pub-sub-push-subscriptions-in-spring-boot-cloud-run-applications-d686c36811a1">Handling Requests from Google Pub/Sub Push Subscriptions in Spring Boot Cloud Run Applications</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Climate Change as a Link Between Gender Inequality and the February 2021 North American Winter…]]></title>
            <link>https://medium.com/climate-conscious/climate-change-as-a-link-between-gender-inequality-and-the-february-2021-north-american-winter-a1923a3208fa?source=rss-9525d53f20d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1923a3208fa</guid>
            <category><![CDATA[science]]></category>
            <category><![CDATA[climate-change]]></category>
            <category><![CDATA[texas]]></category>
            <category><![CDATA[gender-inequality]]></category>
            <category><![CDATA[overpopulation]]></category>
            <dc:creator><![CDATA[Lucas J. Ross]]></dc:creator>
            <pubDate>Wed, 03 Mar 2021 21:04:24 GMT</pubDate>
            <atom:updated>2021-03-03T21:04:24.000Z</atom:updated>
            <content:encoded><![CDATA[<h3>Climate Change as a Link Between Gender Inequality and the February 2021 North American Winter Storms</h3><h4>How a look beyond inadequate energy infrastructure for the cause of weather-related tragedy can identify other causes of human suffering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ozT-gsAShbotvS5tU8mvg.jpeg" /><figcaption>source: <a href="https://burst.shopify.com/@ndekhors">Nicole de Khors</a>, <a href="https://burst.shopify.com/">Burst</a></figcaption></figure><p>As a resident of Austin, I naturally have thought a lot about the recent historic, unprecedented, record-breaking, rather odd <a href="https://en.wikipedia.org/wiki/February_13%E2%80%9317,_2021_North_American_winter_storm">winter</a> <a href="https://en.wikipedia.org/wiki/February_15%E2%80%9320,_2021_North_American_winter_storm">storms</a> and ensuing losses of life and property. Some people simply blame Republicans, which <a href="https://www.nytimes.com/2021/02/21/us/texas-electricity-ercot-blackouts.html">is somewhat fair</a> and certainly was amplified by infamous narcissist <a href="https://nymag.com/intelligencer/2021/02/ted-cruz-flees-texas-for-cancun-ditches-family-poodle.html">Ted Cruz’s politically-puzzling vacation</a> during the peak of our hardship. Climate change is <a href="https://www.cnn.com/2021/02/20/weather/texas-winter-storm-power-outages-climate-change/index.html">commonly</a> mentioned in the context of the storm to imply a causal relationship, and I lean that way, though it’s hard to say for sure.</p><p>I’ve dug a little deeper and in an unusual direction. This is the development of a hypothesis, food for thought, and maybe not much more besides some links to in-depth articles. I’ll start off with the most immediately apparent event and work backward.</p><h4>Winter Storm Uri/Viola and climate change</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*dKtUJh0cFYXzTXf_.jpeg" /><figcaption>source: <a href="https://www.noaa.gov/multimedia/infographic/science-behind-polar-vortex-you-might-want-to-put-on-sweater">NOAA</a></figcaption></figure><p><a href="https://www.smithsonianmag.com/smart-news/how-winter-storm-uri-has-impacted-us-180977055/">Climate scientists differ</a> on whether weather events involving extremely cold temperatures can be attributed to global warming. The concept is unintuitive but has some proponents. “Some studies say the warming Arctic might be causing a ‘wavy’ jet stream that is pushing Arctic air further south, into places like Texas,” <a href="https://www.rollingstone.com/culture/culture-news/austin-texas-ice-storm-climate-change-1129183/">says Jeff Goodell in Rolling Stone</a>. In <a href="https://www.houstonchronicle.com/news/houston-texas/environment/article/Will-climate-change-make-winter-storms-more-15958789.php">an interview by the Houston Chronicle</a>, NASA scientist Gavin Schmidt explains:</p><blockquote>We know that, during the winter, the Arctic has warmed up a lot. The temperature difference between the tropics and the poles has actually gone down a little bit. There’s some indication that that will make the situation slightly more wavy.</blockquote><blockquote>Then there’s other data that suggests that if you go higher up in the atmosphere, the situation reverses, and that would suggest less waviness.</blockquote><p>Sure, there are plenty of <a href="https://www.treehugger.com/polar-vortex-linked-to-climate-change-5112639">tree huggers</a> and <a href="https://earthjustice.org/features/how-climate-change-is-fueling-extreme-weather">environmental-activist lawyers</a> claiming that our pipes froze and burst because we burned too many dead dinosaurs, but nobody can really be sure.</p><p>For the sake of argument, pretend for a moment that we’re talking about an extreme summer heatwave leading to many heatstroke deaths, blackouts from everyone trying to run their AC at the same time, and so on. Those things happen every year in Texas. It’s clear that global warming only makes that sort of thing worse and more frequent, so it’s not far-fetched to think the same would happen at the other extreme. If you can’t get behind this assumption, you’ll probably want to stop reading here because I’m going with it.</p><h4>Climate change and overpopulation</h4><p>The phrase “climate change” carries a virtually universal connotation of human-induced environmental destruction, and that’s precisely what makes it just as real as a <a href="https://www.kxan.com/investigations/parents-be-wary-of-storing-water-in-bathtubs/">bathtub full of snow</a> in a Texas home during… you get the idea.</p><p>It seems to follow that the more humans there are, the more climate change is going to happen. Is that really the case? New technology, processes, and regulations, are always being implemented to reduce and counteract our carbon footprint.</p><p>Unfortunately, our best efforts to mitigate the environmental impact of increasing population have failed by a wide margin to keep up. Here is a sampling of findings on the subject:</p><ul><li>According to a <a href="https://www.biologicaldiversity.org/programs/population_and_sustainability/pdfs/OSUCarbonStudy.pdf">2009 study</a>, each child born in the U.S. increases the “carbon legacy” of their mother (the “carbon emissions of [her] descendants, weighted by their relatedness to [her]”) by 5.7 times. (No offense, mom…)</li><li>The same study shows that having a child results in about 40 times more greenhouse gases than one saves by performing various environmentally conscious actions (recycling, using LED bulbs, driving a Prius) over a lifetime.</li><li><a href="https://iopscience.iop.org/article/10.1088/1748-9326/aa7541">A related study</a> found that having one fewer child saves 58.6 tons of CO2 emissions per year. For comparison, the study states that living car-free saves 2.4 tons of CO2 per year.</li><li>Carbon dioxide emissions and population <a href="https://www.sciencedirect.com/science/article/pii/S2468203916300711">correlate highly</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*D5rjcI7qQuseaKvV.png" /><figcaption>source: <a href="https://populationmatters.org/campaign-graphics">Population Matters</a></figcaption></figure><p>Of course, responsible behavior and smart planning can help. <a href="https://www.pnas.org/content/112/16/4999">People living in cities generate less CO2</a> than those living in the suburbs, for instance. It just doesn’t make as big of a difference as, say, never having been born. Boy, that sounds mean, doesn’t it?</p><p>So far, I’ve talked about emissions by developed countries, but what about the developing world? It’s commonly known that birth rates are higher in poorer countries. In the country of Niger in 2018, <a href="https://en.wikipedia.org/wiki/List_of_sovereign_states_and_dependencies_by_total_fertility_rate">the average woman had 6.9 children.</a> It’s also safe to say that their rate of consumption is much lower — in 2018, <a href="https://en.wikipedia.org/wiki/List_of_countries_by_carbon_dioxide_emissions_per_capita">each U.S. citizen generated 16.1 tons of CO2</a> while each Nigerien generated an amount equal to around one percent(!) of that. So does it really make a difference for the purpose of climate stabilization to worry about growth in populations with such a small impact? <a href="https://www.populationconnection.org/africa-globaldev/">According to Population Connection</a>:</p><blockquote>…a singular correlation between population and environmental catastrophe is, in fact, a dangerous oversimplification.</blockquote><p>I’ll put aside for the moment that ignoring population growth in the third world disregards the basic tragedy of the conditions the people of Niger and surrounding states are living in (more on that to follow). It’s a big problem for the developing world not so much because of how their emissions impact us, but more because of how our emissions impact them. Extreme droughts related to climate change are cited in the 2019 <a href="https://library.wmo.int/doc_num.php?explnum_id=10421">State of the Climate in Africa</a> report as a contributor to an increase in malnourished people in sub-Saharan Africa by 45 percent within seven years.</p><p>Still, folks in developing countries contribute to climate change too. In early stages of industrialization, <a href="https://www.cgdev.org/media/developing-countries-are-responsible-63-percent-current-carbon-emissions#:~:text=Developing%20Countries%20Are%20Responsible%20for,Emissions%20%7C%20Center%20For%20Global%20Development">they tend to pollute a lot</a>. According to <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.159.84&amp;rep=rep1&amp;type=pdf">one study</a>, “a 40 percent reduction in per capita emissions in the developed regions would be outweighed solely by the effects of demographic growth elsewhere in the world” over the period of 2000–2050. China’s population growth rate has stabilized at 0.4 percent annually, but their current crowded population of 1.4 billion stems from a government-encouraged birth rate in the 1960s of around six per woman. (In the 80s, they said “oops!” and implemented their fascist <a href="https://en.wikipedia.org/wiki/One-child_policy">Family Planning Policy</a>.) To be fair, <a href="https://ourworld.unu.edu/en/toxic-e-waste-dumped-in-poor-nations-says-united-nations">a lot of their pollution is essentially the developed world’s fault</a> (we’ve thrown much of our dirtiest industry over the fence to them).</p><h4>Overpopulation and gender inequality</h4><p>What makes someone want to have a bunch of babies? I wouldn’t know, but it stands to reason that one wouldn’t do it if she thought she had better things to do. In the countries with the highest birth rates (central/west Africa), women aren’t even <em>allowed </em>to have other things to do. To be clear, <a href="https://www.walkfree.org/news/2019/forced-and-child-marriage-in-africa-as-a-manifestation-of-gender-based-violence-and-inequality/">many women — and girls — in those countries are forced to bear children</a>.</p><p>Looking at the big picture: comparing the aforelinked list of birth rates by country with <a href="https://webcache.googleusercontent.com/search?q=cache:OmcLfKdRftUJ:https://www.nationalgeographic.com/culture/2019/10/peril-progress-prosperity-womens-well-being-around-the-world-feature/+&amp;cd=4&amp;hl=en&amp;ct=clnk&amp;gl=us">this report on gender inequality by country</a>, there’s a clear correlation. Norway, the report’s number-one country for gender equality, is ranked 167th in birth rate (well below replacement rate). <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4387654/">An Iranian study</a> showed a correlation between stereotypical gender attitudes and higher birth rates. That gets to my main point: generally, advancing rights of women and girls would reduce the number of children they have (which, in turn, would do a lot to slow down global warming and associated weather phenomena). It’s worth noting that mortality rates, although higher in developing countries, don’t have much effect on relative rates of total population growth.</p><p><a href="https://www.afr.com/world/asia/gender-equality-a-remedy-for-falling-asian-birth-rates-20190314-p5145a">Some</a> <a href="https://wappp.hks.harvard.edu/3-things-you-should-know-about-low-birth-rates-and-gender-inequality">sources</a> conclude that improving gender equality would actually increase birth rates. I was skeptical but it makes sense in the narrow context of societies that are already fairly egalitarian. They point out that when men accept a more equal share of child-rearing responsibilities, women — who work, whether they have children or not — have more time and energy free to have more children. If they can expect to bear the responsibilities of both a 50’s housewife and — like — a 90’s professional lady with the shoulder pads and everything, then they won’t bother. By that token, it seems that a graph plotting equality scores against birth rates would have a minimal birth rate somewhere near but not all the way to the far right (not politically, obviously).</p><p>What about other solutions for overpopulation? Some advocate for economic development as a way to promote progressive gender norms and thus reduce birth rates. That causality <a href="https://economicdynamics.org/meetpapers/2012/paper_116.pdf">has somewhat played out in the developed world</a>. It seems to work both ways: <a href="https://www.elibrary.imf.org/view/IMF071/23551-9781513590363/23551-9781513590363/ch01.xml">GDP is 25 percent lower</a> on average in countries with a female-to-male school-enrollment ratio less than 0.75. <a href="https://wafmag.org/2017/03/surviving-underground-economy-women-miners-south-africa/">Efforts have been made in Africa to put more women into mines</a> to collect our precious metals for us and ostensibly to empower them with access to a source of income. I’m not sure that improving conditions for women by way of expanding an economy and/or vice versa really gets at the heart of the ecology issue — it hasn’t proven helpful in that regard — but maybe.</p><p>There are also the <a href="https://en.wikipedia.org/wiki/Pentti_Linkola">eco-fascists</a> who believe that humanity is irredeemably destructive and stupid and that some eco-dictator should take over the world and force everyone to throw away their technology and stop reproducing. I won’t entertain this maniacal notion, but I must admit that at times, I’ve been overwhelmed by all the cruelty in the world and thus tempted to take such a pessimistic stance.</p><h3>Conclusion</h3><p>Our primary focus for the dual purpose of slowing climate change and improving the lives of all humans should be on empowering women, especially those whose state of oppression is <a href="https://www.nbcnews.com/news/all/army-children-toil-african-mica-mines-n1082916">exploited</a> by the developed world.</p><p>I’d like to share my primary inspiration for this article. The <a href="https://www.populationmedia.org/">Population Media Center</a> is a non-profit organization that believes we can save the planet through cultural change. Their <a href="https://www.populationmedia.org/projects/east-los-high/">educational and entertaining productions</a> for TV, film, and radio, are tailored to demographics in which women and girls lack basic reproductive rights. Their approach is humane and I hope that you’ll consider supporting their cause.</p><p>I hope this writing has been educational and entertaining as well. Special thanks to our neighbors for letting us take water from their pool when Austin ran out of water so we could flush our toilets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1923a3208fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/climate-conscious/climate-change-as-a-link-between-gender-inequality-and-the-february-2021-north-american-winter-a1923a3208fa">Climate Change as a Link Between Gender Inequality and the February 2021 North American Winter…</a> was originally published in <a href="https://medium.com/climate-conscious">Climate Conscious</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What gardening has taught me about developing software and vice versa]]></title>
            <link>https://medium.com/swlh/what-gardening-has-taught-me-about-developing-software-and-vice-versa-5cc3d88ba641?source=rss-9525d53f20d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cc3d88ba641</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[gardening]]></category>
            <dc:creator><![CDATA[Lucas J. Ross]]></dc:creator>
            <pubDate>Fri, 03 Jul 2020 21:39:58 GMT</pubDate>
            <atom:updated>2020-07-07T02:18:27.043Z</atom:updated>
            <content:encoded><![CDATA[<p>Gardening as a metaphor for developing software was, as far as I can tell, first mentioned by Andy Hunt and Dave Thomas in their 1999 book, <em>The Pragmatic Programmer</em>. When it first occurred to me to write on the topic, I hadn’t heard the idea before, as I haven’t yet finished reading the book. It’s on the top of my list, I swear! And knowing those fellows came up with the same idea, I certainly get a feeling of validation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIufMQuAb-gR-5Da-hOl6Q.png" /><figcaption>An enterprise integration garden, the sort of thing I’m seeing in my dreams these days</figcaption></figure><p>I’m fairly new to gardening, at least in the outdoors, which presents unique challenges where I live. In central Texas, triple-digit temperatures occur between the months of May and September, and are practically an everyday thing in August at this point. Rain isn’t too scarce, but in the Spring months there can be a lot of it, and in the summer, turf grass dies without supplemental irrigation. Winters dip into the 20s Fahrenheit from time to time. So, any plant you expect to live for more than a year has to be hardy to both extreme heat and frost, to both drought and drenching. And then, there are the pests, such as grubs that feast on plant roots before they drill up out of the ground and turn into a flying, buzzing nuisance. So, I’ve certainly made a few mistakes, terminated the lives of some lovely green organisms before their prime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*FQATyx9QFI6QAiy8kkPaCg.jpeg" /><figcaption>Red tropical sage, a central Texas native, is hardy and easy to grow</figcaption></figure><p>Similarly — and I admit this might be one of the strangest context switches you’ll experience today — in programming, I never get the sense that I have a full grasp of whatever technology I’m putting to use. I get just familiar enough with a set of technologies to build a thing that makes some money for somebody and then hope that most of those technologies haven’t been abandoned when it comes to building something else.</p><p>So, for what it’s worth, here are some comparisons between software development and gardening that have crossed my mind while planting one of many <a href="https://plants.ces.ncsu.edu/plants/liriope-muscari/">Liriope</a>s or writing yet another REST endpoint.</p><h4>The end result will never match the original design</h4><p>I created my first ornamental garden within a north-facing corner of my house. Initially, water from heavy rain poured off the edge of the roof and landed on cedar bark mulch I’d placed underneath, dislodging it and flinging mud around. Over the course of a year, much of it washed down into an adjacent low point that I had landscaped with river rock, which doesn’t really benefit from mulching. So, around the area under the eaves, I replaced the mulch with pea gravel, which keeps the soil moist enough and doesn’t float. Soon after that, I had gutters installed. If functional gutters had been present originally, I would never have needed to replace the mulch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZMv-1mXzZpuyepz4zExHg@2x.jpeg" /><figcaption>I suppose the gravel creates a nice contrast</figcaption></figure><p>In <a href="https://www.artima.com/intv/garden.html">an interview with the authors of <em>The Pragmatic Programmer</em></a>, Hunt points out that software development is not really comparable to construction or even the major engineering disciplines.</p><blockquote>It doesn’t work that way with software. […] The garden doesn’t quite come up the way you drew the picture. This plant gets a lot bigger than you thought it would. You’ve got to prune it. You’ve got to split it. You’ve got to move it around the garden. This big plant in the back died. You’ve got to dig it up and throw it into the compost pile. […]</blockquote><p>I can attest to the idea that building things with wood or metal is not easy for someone with a software development mindset. I’ve managed to put together a 4&#39;x8&#39; tool shed with wood framing, and from that I learned that even such a simple structure requires planning of most details in advance. Any measurement recorded incorrectly results in wasted materials and time. I frequently caught myself cutting a board at the wrong angle or nailing something upside down, and then becoming annoyed because I’m used to having a backspace key for that sort of thing. In the end, it has to match the original plan, or it’ll be an ugly, possibly hazardous structure. In contrast, with a Java development environment, you can create a fully functional web server by running one standard build-tool command to generate one from an archetype. You can delete it five seconds later, and all that will have been lost is maybe a few cents’ worth of electricity. With gardening, you’re free to make a lot of mistakes. Your hand trowel is your backspace key. The implementation shapes the design.</p><p>In “<a href="https://medium.com/@cmaitchison/are-you-a-software-gardener-f79eba5b7fb7">You are NOT a Software Engineer!</a>” Chris Aitchison points out:</p><blockquote>Would you try to plan a garden in such detail that you would know where each leaf will be positioned before you plant a single seed? Would people expect estimates (or are they promises in your organisation?) on exactly how many flowers will have bloomed in one year? Would you have an incentive tied to that? Things that would be perfectly reasonable to plan for a bridge seem a little ridiculous when you are talking about a garden.</blockquote><h4>Leave room for growth</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gD8-vWd7KR6S69EsTrKLNg.jpeg" /><figcaption>Surely it won’t get much bigger than that</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*II577V4VViAJUu8wSXxudg.jpeg" /><figcaption>WHAT</figcaption></figure><p>My local favorite gardening retailer, <a href="https://tngaustin.com/">The Natural Gardener</a>, pointed me to this great Texas-native perennial, Fall Aster. I wish I’d paid attention when they mentioned how big it would get. It looked like the second photo a year after planting something like the tiny plant in the first photo. It’s not just big, <a href="https://davesgarden.com/guides/articles/view/4244">it also spreads aggressively</a> by its roots.</p><p>As you’ve probably guessed, the analogy here is with scalability. Can an actual garden be designed with horizontal scalability, like a Cassandra database? Vertical stacking of vegetation in the physical space, like with hydroponics, might be analogous to scaling data storage “horizontally” by adding additional data replicas. I don’t know — given that any garden has physical space constraints, a garden has to be a monolith, albeit one with a much higher degree of pleasurability than a Java web server built in 2005.</p><h4>Expect maintenance and value maintainability</h4><p>A homebuilder doesn’t expect to hang around and do on-demand maintenance on the house they’re building for years after someone moves into it. You can’t take your CPU from Intel Corporation to a repair shop when it fries out, which occurs almost never with normative use. In contrast, a piece of software without regular maintenance is, by and large, useless software. A library that I find on GitHub without any commits in the past two or three months is usually one that I would consider “abandonware.”</p><p>Consider one tendency common among talented software developers, a desire to create patterns, even frameworks, to promote efficiency in developing sets of similar features. In his <a href="https://www.toptal.com/javascript/are-big-front-end-frameworks-bad">thorough article on the pros and cons of frameworks</a>, Juan Carlos Arias Ambriz points out one way in which frameworks can fail us:</p><blockquote><strong>That tangle of weeds you’re walking through is growing thorns.</strong> Have you ever been in the situation where you’re using your framework and trying to add a library to it, just to realize that the library version you need doesn’t work well with the framework version that you’re using? Sometimes it takes more effort to make two pieces of code work together than it does to just write the code yourself. And since the frameworks and libraries that you use are often built on other frameworks and libraries that can have hidden incompatibilities that you can’t even anticipate, the problem can grow exponentially more complex, reaching a point where they’re impossible to manage if you want the project to keep growing.</blockquote><p>Exponential growth of complexity brings exponential decline in maintainability. And there are other ways in which we get ourselves tangled up: we write hard-to-test code and afterward, we write tests, which then end up being convoluted and brittle. We neglect to write documentation for a function, and two weeks later we look at it again and can’t remember what it was supposed to do.</p><p>Then there are the maintainability anti-patterns at the organizational level, like having “<a href="https://i.redd.it/u6bpgzolm1c11.jpg">rockstars</a>” build major features and then having “junior” developers fix their bugs. I admit the former is a fun job to have and it’s not the worst thing in the world to create work for entry-level contributors. For my garden, ideally I’d rather not do the work of periodically reapplying mulch, trimming things back following frost periods, and so forth — I’d rather “outsource” that work.</p><p>A garden is a lot like a web app in that you have to keep yourself on “pager duty” to keep it alive. Some techie-gardeners have built automatic watering systems using <a href="https://www.youtube.com/watch?v=9h3JKwUsn2A">Arduinos and moisture sensors</a> that raise alerts about potential droopy-leaf conditions.</p><h4>Prioritize that which is most worthwhile</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*A-naPjhXNBIyN-iT3tusRg.jpeg" /><figcaption>DON’T: Mulch volcano</figcaption></figure><p>As an aside, the young (pear?) tree in the above photo will have a hard enough time in the Texas heat without someone having created a “<a href="https://extension.psu.edu/mulch-volcanoes-are-erupting-everywhere">mulch volcano</a>” around it. The root system of this tree probably will start growing up into the mulch to avoid being smothered by it, and lower roots may rot. In keeping with the theme, this is sort of like having within object-oriented program code a class inheritance hierarchy twenty levels deep. A deep class hierarchy lends itself to tight coupling and weak encapsulation— the base classes suffer from <em>code rot</em>! Still with me?</p><p>In conditions of drought, water use can be limited, in which case gardeners have to make compromises and prioritize irrigation based upon the value of each kind of plant to the overall landscape. <a href="https://cals.arizona.edu/yavapai/anr/hort/byg/archive/droughtmanagementinyourlandscape.html">Generally</a>, young trees should be given priority for watering, as they are sensitive and costly to replace. Next in line are perennials and fruits/vegetables. The lowest priority for supplemental water should be annuals and turf grass and other cheap vegetation maintained for appearances.</p><p>If you’ve worked at a scrappy start-up company, you know what it means to make sacrifices due to resource limitations. When deliverables are late, a team may neglect its commitment to open-source contribution. If traffic to your e-commerce site suddenly skyrockets and your web servers scale poorly, you’ll probably have to put R&amp;D on hold while you put out fires. One may consider the challenges a developer might have faced at a small, travel-related business when COVID-19 struck: if they weren’t laid off themselves, half of their team might have disappeared. Maybe they were in the process of replacing a relational database full of years of production data with a NoSQL store for the fun of it, but that isn’t happening now.</p><h3>Conclusion</h3><p>Thanks for reading! Do you know of a way I could keep the ball rolling with this comparison? Please share in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cc3d88ba641" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/what-gardening-has-taught-me-about-developing-software-and-vice-versa-5cc3d88ba641">What gardening has taught me about developing software and vice versa</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laying the Rails from AWS API Gateway to ECS Fargate | Part II]]></title>
            <link>https://levelup.gitconnected.com/laying-the-rails-from-aws-api-gateway-to-ecs-fargate-part-ii-7b9294ead2e4?source=rss-9525d53f20d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b9294ead2e4</guid>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[application-load-balancer]]></category>
            <category><![CDATA[elastic-container-service]]></category>
            <category><![CDATA[network-load-balancer]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Lucas J. Ross]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 20:48:24 GMT</pubDate>
            <atom:updated>2020-05-04T12:27:01.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSruvb9Fm65k6QO5G-pirg.png" /></figure><p>Previously on <em>E.R.</em>, I described an integration line from API Gateway to a VPC Link.</p><p><a href="https://medium.com/@lucjross/laying-the-rails-from-aws-api-gateway-to-ecs-fargate-part-i-debf754d6a8b">Laying the Rails from AWS API Gateway to ECS Fargate | Part I</a></p><p>This second part will cover the rest, from the Network Load Balancer to ECS Tasks. Let’s jump in.</p><h3>Network Load Balancer</h3><h4>Rationale</h4><p>Why connect API Gateway to a Network Load Balancer and not directly to an Application Load Balancer? Basically, that’s because VPC Service Endpoint connects only to a NLB, and the VPC Service Endpoint is API Gateway’s— uh, gateway to our VPC.</p><p>Hypothetically, if we wanted API Gateway to get to our service over the Internet, we could use an Internet-facing ALB with a public DNS name, but we don’t want our ALB accessible from the Internet. If it were, we would have another potential security hole, especially considering we aren’t integrating authentication with the ALB, but only with the gateway. So, I made the load balancers internal, which precludes attaching public IPs to them. That makes them unreachable by anything outside of the VPC (or peered VPCs). The VPC Service Endpoint, however, can be attached to a NLB regardless of its subnet associations.</p><p>Our implementation could be much simpler if Amazon did one little thing: allow Cognito client-credentials authentication in Application Load Balancer listener rules. As far as I can tell, it integrates only with the “authorization code grant” and “implicit grant” flows, which are intended for humans with web browsers. You can see in the diagram that an internal ALB interfaces directly with ECS tasks. If ALB supported the simple client credentials OAuth flow, we would just use an external ALB instead, and then, API Gateway wouldn’t necessarily add much.</p><h4>Infrastructure implementation</h4><p>Let’s create the NLB and its non-service-specific resources.</p><pre>resource &quot;aws_lb&quot; &quot;network&quot; {<br>  name = &quot;${var.stage}-nlb&quot;<br>  load_balancer_type = &quot;network&quot;<br>  enable_cross_zone_load_balancing = true<br>  internal = true<br>  subnets = var.private_subnet_ids<br>  access_logs {<br>    enabled = true<br>    bucket = var.nlb_logs_bucket_id<br>    prefix = &quot;&quot;<br>  }<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;nlb_80&quot; {<br>  name = &quot;nlb-80&quot;<br>  protocol = &quot;TCP&quot;<br>  port = 80<br>  target_type = &quot;ip&quot;<br>  vpc_id = var.vpc_id<br>  proxy_protocol_v2 = false<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;nlb_443&quot; {<br>  name = &quot;nlb-443&quot;<br>  protocol = &quot;TLS&quot;<br>  port = 443<br>  target_type = &quot;ip&quot;<br>  vpc_id = var.vpc_id<br>  proxy_protocol_v2 = false<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;nlb_80&quot; {<br>  load_balancer_arn = aws_lb.network.arn<br>  protocol = &quot;TCP&quot;<br>  port = 80<br>  default_action {<br>    type = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.nlb_80.arn<br>  }<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;nlb_443&quot; {<br>  load_balancer_arn = aws_lb.network.arn<br>  protocol = &quot;TLS&quot;<br>  port = 443<br>  certificate_arn = var.server_certificate_arn<br>  default_action {<br>    type = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.nlb_443.arn<br>  }<br>}</pre><p>We’ve created two target groups, one for TCP on port 80 and one for TCP with TLS on port 443. API Gateway doesn’t actually allow non-secure HTTP traffic, but I figured that for internal load balancers, providing a non-TLS pathway would be nice for intra-VPC integrations with our example service (<em>ice-station-zebra</em>). Also, it’s a remnant of my initial, mistaken conception that API Gateway does allow port 80, and I’m an LB listener hoarder — I have hundreds more, just collecting network dust.</p><p>There are no <em>listener rules</em> for these listeners because the default_action for each listener will suffice for routing to the target groups. Also, the server certificate for the nlb_443 listener can be either self-signed or real-certificate-authority-signed. It’s not like public websites, which should be assumed to be illegitimate when they present a self-signed or otherwise shady SSL certificate. Traffic from clients who have already accepted the certificate on the API Gateway side should be able to assume that whatever’s behind the gateway is trustworthy as well, so for internal components, the certificate is just a logistical requirement.</p><h3>Application Load Balancer</h3><p>You may be wondering why we’re using the ALB at all when an NLB can target ECS Tasks directly. ALB supports more sophisticated routing rules and can forward traffic on more than one port. NLBs offer higher performance, as they operate at a lower level, but they don’t provide the path-based routing capability we need for this integration, and anyway, Amazon recommends and supports ALB for load balancing with ECS Fargate.</p><h4>Infrastructure</h4><p>When we provision the ALB, we’ll need to give it a Security Group, unlike with the NLB to which Security Groups do not apply. We can simply allow all egress on all ports and all ingress on port 80, since it’s internal to the VPC. The default target group is not necessarily used, but we need one for the listeners’ default actions.</p><pre>resource &quot;aws_security_group&quot; &quot;alb_internal&quot; {<br>  vpc_id = var.vpc_id<br>  name = &quot;alb-internal&quot;<br>}<br><br>resource &quot;aws_security_group_rule&quot; &quot;alb_internal_egress&quot; {<br>  type = &quot;egress&quot;<br>  from_port = &quot;0&quot;<br>  to_port = &quot;0&quot;<br>  protocol = &quot;-1&quot;<br>  cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  security_group_id = aws_security_group.alb_internal.id<br>}<br><br>resource &quot;aws_security_group_rule&quot; &quot;alb_internal_http_ingress&quot; {<br>  type = &quot;ingress&quot;<br>  from_port = 80<br>  to_port = 80<br>  protocol = &quot;tcp&quot;<br>  cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  security_group_id = aws_security_group.alb_internal.id<br>}<br><br>resource &quot;aws_lb&quot; &quot;internal&quot; {<br>  name = local.internal_alb_name<br>  internal = true<br>  load_balancer_type = &quot;application&quot;<br>  security_groups = [<br>    aws_security_group.vpc.id,<br>    aws_security_group.alb_internal.id,<br>  ]<br>  subnets = var.private_subnet_ids<br>  idle_timeout = 60<br>  ip_address_type = &quot;ipv4&quot;<br>  access_logs {<br>    enabled = true<br>    bucket = var.alb_internal_access_logs_bucket_id<br>    prefix = &quot;&quot;<br>  }<br>}<br><br>resource &quot;aws_lb_target_group&quot; &quot;alb_internal_default&quot; {<br>  name = &quot;alb-internal-default&quot;<br>  port = 80<br>  protocol = &quot;HTTP&quot;<br>  vpc_id = var.vpc_id<br>  target_type = &quot;ip&quot;<br>  deregistration_delay = 10<br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;alb_internal_http&quot; {<br>  load_balancer_arn = aws_lb.internal.arn<br>  port = 80<br>  protocol = &quot;HTTP&quot;<br>  default_action {<br>    target_group_arn = aws_lb_target_group.alb_internal_default.arn<br>    type = &quot;forward&quot;<br>  }<br>}<br><br>resource &quot;aws_lb_listener&quot; &quot;alb_internal_http_443&quot; {<br>  count = local.nlb_count<br>  load_balancer_arn = aws_lb.internal.arn<br>  port = 443<br>  protocol = &quot;HTTPS&quot;<br>  certificate_arn = var.server_certificate_arn<br>  default_action {<br>    target_group_arn = aws_lb_target_group.alb_internal_default.arn<br>    type = &quot;forward&quot;<br>  }<br>}</pre><p>As my diagram shows, this load balancer is the point at which TLS is terminated. The reader’s needs for termination may vary, and it could alternatively be done at the NLB or within the ECS Tasks. I chose to terminate at the ALB because it’s as close to the services as possible without the complication of installing certificates on them.</p><h4>Static IPs</h4><p>To introduce an ALB directly behind the NLB, we have to tackle an incompatibility between them. The IP addresses of an ALB are dynamic, which is fine for the usual case of referencing them with a DNS CNAME record, but an NLB has no way of keeping up with the changes by itself. To solve this, I’ll provide an implementation of the AWS blog article, <a href="https://aws.amazon.com/blogs/networking-and-content-delivery/using-static-ip-addresses-for-application-load-balancers/"><em>Using static IP addresses for Application Load Balancers</em></a>.</p><p>First, we’ll create the “IP list” bucket.</p><pre>resource &quot;aws_s3_bucket&quot; &quot;internal_alb_static_ips&quot; {<br>  bucket = &quot;${var.stage}-internal-alb-static-ips&quot;<br>  acl = &quot;private&quot;<br>  region = data.aws_region.this.name<br><br>  versioning {<br>    enabled = true<br>  }<br>}</pre><p>Then we’ll provide IAM resources to the Lambda. It needs access to CloudWatch, S3, and Elastic Load Balancing.</p><pre>data &quot;aws_iam_policy_document&quot; &quot;lambda_assume_role&quot; {<br>  statement {<br>    actions = [&quot;sts:AssumeRole&quot;]<br>    principals {<br>      type = &quot;Service&quot;<br>      identifiers = [&quot;lambda.amazonaws.com&quot;]<br>    }<br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;nlb_tg_to_alb_lambda&quot; {<br>  name = &quot;nlb-tg-to-alb-lambda&quot;<br>  assume_role_policy = data.aws_iam_policy_document.lambda_assume_role.json<br>}<br><br>data &quot;aws_iam_policy_document&quot; &quot;nlb_tg_to_alb_lambda&quot; {<br>  statement {<br>    actions = [<br>      &quot;logs:CreateLogGroup&quot;,<br>      &quot;logs:CreateLogStream&quot;,<br>      &quot;logs:PutLogEvents&quot;,<br>    ]<br>    resources = [&quot;arn:aws:logs:*:*:*&quot;]<br>  }<br>  statement {<br>    actions = [<br>      &quot;s3:GetObject&quot;,<br>      &quot;s3:PutObject&quot;,<br>    ]<br>    resources = [&quot;${aws_s3_bucket.internal_alb_static_ips.arn}/*&quot;]<br>  }<br>  statement {<br>    actions = [<br>      &quot;elasticloadbalancing:RegisterTargets&quot;,<br>      &quot;elasticloadbalancing:DeregisterTargets&quot;,<br>    ]<br>    resources = [<br>      aws_lb_target_group.nlb_80.arn,<br>      aws_lb_target_group.nlb_443.arn,<br>    ]<br>  }<br>  statement {<br>    actions = [&quot;elasticloadbalancing:DescribeTargetHealth&quot;]<br>    resources = [&quot;*&quot;]<br>  }<br>  statement {<br>    actions = [&quot;cloudwatch:putMetricData&quot;]<br>    resources = [&quot;*&quot;]<br>  }<br>}<br><br>resource &quot;aws_iam_role_policy&quot; &quot;nlb_tg_to_alb_lambda&quot; {<br>  role = aws_iam_role.nlb_tg_to_alb_lambda.name<br>  policy = data.aws_iam_policy_document.nlb_tg_to_alb_lambda.json<br>}</pre><p>Next, go ahead and download the Lambda function from the link in the AWS tutorial, and unzip it in your infrastructure project.</p><p>Before we create the Lambda functions with Terraform, we might need to make a slight change to the Lambda code. If your NLB uses only port 443, you don’t need to do this. If you want traffic on port 80 to be routed from the NLB as well, then the Lambda needs to be altered so that it saves its IP list with object names that are specific to the target group and not just to the ALB. To that effect, make changes according to this Git diff. (Picture for context, text for copy+pasting. Medium is not the best medium for sharing code.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFcppAMVVwgoPVqpccQJqQ.png" /></figure><pre>PENDING_DEREGISTRATION_FILENAME = &#39;Pending deregistration IP list of {}.json&#39;.format(ALB_DNS_NAME)<br>ACTIVE_IP_LIST_KEY = &quot;{}/{}/{}&quot;\<br>       .format(NLB_TG_ARN, ALB_DNS_NAME, ACTIVE_FILENAME)<br>PENDING_IP_LIST_KEY = &quot;{}/{}/{}&quot;\<br>       .format(NLB_TG_ARN, ALB_DNS_NAME, PENDING_DEREGISTRATION_FILENAME)</pre><p>We can package the Lambda using this shell script, which I made just for reproducibility — it probably only needs to be run once. The cd is performed so that zip will package only the contents, as Lambda will not appreciate the upload if the handler code is not at the package root.</p><pre><strong>#!/bin/sh<br></strong>set -e<br><br>(cd populate_NLB_TG_with_ALB &amp;&amp; zip -r -FS ../package/nlb-tg-to-alb-lambda.zip .)</pre><p>Now, once that shell script has been run, we can create the Lambdas.</p><pre>locals {<br>  alb_static_ips_lambda_zip_path = &quot;${path.module}/package/nlb-tg-to-alb-lambda.zip&quot;<br>}<br><br>resource &quot;aws_lambda_function&quot; &quot;nlb_tg_to_alb_80&quot; {<br>  filename = local.alb_static_ips_lambda_zip_path<br>  function_name = &quot;nlb-tg-to-alb-80&quot;<br>  role = aws_iam_role.nlb_tg_to_alb_lambda.arn<br>  handler = &quot;populate_NLB_TG_with_ALB.lambda_handler&quot;<br><br>  source_code_hash = filebase64sha256(local.alb_static_ips_lambda_zip_path)<br><br>  runtime = &quot;python2.7&quot;<br>  memory_size = 128<br>  timeout = 300<br><br>  environment {<br>    variables = {<br>      ALB_DNS_NAME = aws_lb.internal.dns_name<br>      ALB_LISTENER = &quot;80&quot;<br>      S3_BUCKET = aws_s3_bucket.internal_alb_static_ips.id<br>      NLB_TG_ARN = aws_lb_target_group.nlb_80.arn<br>      MAX_LOOKUP_PER_INVOCATION = 50<br>      INVOCATIONS_BEFORE_DEREGISTRATION = 10<br>      CW_METRIC_FLAG_IP_COUNT = true<br>    }<br>  }<br>}<br><br>resource &quot;aws_lambda_function&quot; &quot;nlb_tg_to_alb_443&quot; {<br>  filename = local.alb_static_ips_lambda_zip_path<br>  function_name = &quot;nlb-tg-to-alb-443&quot;<br>  role = aws_iam_role.nlb_tg_to_alb_lambda.arn<br>  handler = &quot;populate_NLB_TG_with_ALB.lambda_handler&quot;<br><br>  source_code_hash = filebase64sha256(local.alb_static_ips_lambda_zip_path)<br><br>  runtime = &quot;python2.7&quot;<br>  memory_size = 128<br>  timeout = 300<br><br>  environment {<br>    variables = {<br>      ALB_DNS_NAME = aws_lb.internal.dns_name<br>      ALB_LISTENER = &quot;443&quot;<br>      S3_BUCKET = aws_s3_bucket.internal_alb_static_ips.id<br>      NLB_TG_ARN = aws_lb_target_group.nlb_443.arn<br>      MAX_LOOKUP_PER_INVOCATION = 50<br>      INVOCATIONS_BEFORE_DEREGISTRATION = 10<br>      CW_METRIC_FLAG_IP_COUNT = true<br>    }<br>  }<br>}</pre><p>A CloudWatch cron job triggers invocations of the Lambdas, and the CloudWatch events service is permitted to invoke them.</p><pre>resource &quot;aws_cloudwatch_event_rule&quot; &quot;nlb_tg_to_alb_cron&quot; {<br>  name = &quot;nlb-tg-to-alb-cron&quot;<br>  schedule_expression = &quot;rate(1 minute)&quot;<br>  is_enabled = true<br>}<br><br>resource &quot;aws_cloudwatch_event_target&quot; &quot;nlb_tg_to_alb_cron_80&quot; {<br>  rule = aws_cloudwatch_event_rule.nlb_tg_to_alb_cron.name<br>  target_id = &quot;TriggerStaticPort80&quot;<br>  arn = aws_lambda_function.nlb_tg_to_alb_80.arn<br>}<br><br>resource &quot;aws_cloudwatch_event_target&quot; &quot;nlb_tg_to_alb_cron_443&quot; {<br>  rule = aws_cloudwatch_event_rule.nlb_tg_to_alb_cron.name<br>  target_id = &quot;TriggerStaticPort443&quot;<br>  arn = aws_lambda_function.nlb_tg_to_alb_443.arn<br>}<br><br>resource &quot;aws_lambda_permission&quot; &quot;allow_cloudwatch_80&quot; {<br>  statement_id = &quot;AllowExecutionFromCloudWatch&quot;<br>  action = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.nlb_tg_to_alb_80.function_name<br>  principal = &quot;events.amazonaws.com&quot;<br>  source_arn = aws_cloudwatch_event_rule.nlb_tg_to_alb_cron.arn<br>}<br><br>resource &quot;aws_lambda_permission&quot; &quot;allow_cloudwatch_443&quot; {<br>  statement_id = &quot;AllowExecutionFromCloudWatch&quot;<br>  action = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.nlb_tg_to_alb_443.function_name<br>  principal = &quot;events.amazonaws.com&quot;<br>  source_arn = aws_cloudwatch_event_rule.nlb_tg_to_alb_cron.arn<br>}</pre><p>To sum up the ALB discussion: we’ve created an Application Load Balancer with two listeners (443 and 80) and a mechanism for the Network Load Balancer to stay connected to the ALB.</p><h4>Service</h4><p>At this point, we can bring our focus back to the realm of the individual service. You’ll need to create Load Balancer Target Groups for each one. That should be okay <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-limits.html">if the LB won’t serve more than around 50 services</a>, assuming each uses a pair of Target Groups (for HTTP and HTTPS). For more services, add more LBs.</p><p>This Terraform configuration creates at least one Target Group, each named with the service name and a random, six-character, hexadecimal suffix. I’ve used a blue_green boolean variable for support of AWS CodeDeploy, which does blue-green/canary-style deployments of ECS Tasks by switching traffic (or portions of traffic) from one target group to another. This is kind of why I used the random TG names instead of “blue”/”green” or small integers — I wanted to avoid thinking of them as having any natural order or associating them with activeness/inactiveness, as either of them could be serving traffic at any time, and you don’t know without looking at the Listener Rules. I won’t cover deployment concerns here, so just pretend you didn’t see the count arguments, but it’s worth considering for your production environments.</p><pre>resource &quot;random_id&quot; &quot;target_group_http_80&quot; {<br>  count = var.blue_green ? 2 : 1<br>  byte_length = 3<br>}</pre><pre>resource &quot;aws_alb_target_group&quot; &quot;http_80&quot; {<br>  count = var.blue_green ? 2 : 1<br>  name = &quot;${substr(var.name, 0, 20)}-${random_id.target_group_http_80[count.index].hex}&quot;<br>  protocol = &quot;HTTP&quot;<br>  port = 80<br>  vpc_id = var.vpc_id<br>  slow_start = 30<br>  stickiness {<br>    type = &quot;lb_cookie&quot;<br>  }<br>  target_type = &quot;ip&quot;<br>  health_check {<br>    path = local.health_checks.path<br>    port = 8080<br>    timeout = local.health_checks.timeout<br>    interval = local.health_checks.interval<br>    matcher = &quot;200-299&quot;<br>  }<br>}</pre><p>Since <em>infra</em> is in another root module, we’ll need to make inferences about the ALB we’ve set up.</p><pre>data &quot;aws_alb_listener&quot; &quot;http_80&quot; {<br>  load_balancer_arn = var.internal_alb_arn<br>  port = 80<br>}</pre><pre>data &quot;aws_alb_listener&quot; &quot;https_443&quot; {<br>  load_balancer_arn = var.internal_alb_arn<br>  port = 443<br>}</pre><p>Next we’ll create a Listener Rule for port 80 with particular behaviors defined:</p><ul><li>It will match a request if it’s for a URL starting with “http://api.abq.com/ice-station-zebra/”. Note that, if you also need to serve precisely the root path, “/ice-station-zebra”, you’ll need another Listener Rule with that path pattern (only one of each condition type is allowed on a single rule).</li><li>If a request is matched, the ALB will respond with a 301 and redirect the user to the same URL, but on port 443.</li></ul><p>Again, port 80 is not really needed for the purpose of integrating with API Gateway, so this is just a safeguard. If we want another service in the VPC to invoke <em>ice-station-zebra</em> through the port 80 Listener, then we could create another Listener Rule. It wouldn’t have the redirect but would need another condition to permit intra-VPC traffic, such as a source-ip with a VPC CIDR block.</p><p>We’ll also create a Listener Rule for port 443, which has the same request conditions but will pass traffic along to the target group. The 443 rule forwards to the port 80 Target Group, which makes it a TLS terminator (😎).</p><pre>resource &quot;aws_alb_listener_rule&quot; &quot;http_80&quot; {<br>  listener_arn = data.aws_alb_listener.http_80.arn</pre><pre>  action {<br>    type = &quot;redirect&quot;<br>    redirect {<br>      port = data.aws_alb_listener.https_443.port<br>      protocol = data.aws_alb_listener.https_443.protocol<br>      status_code = &quot;HTTP_301&quot;<br>    }<br>  }<br>  <br>  condition {<br>    host_header {<br>      values = [&quot;api.abq.com&quot;]<br>    }<br>  }<br>  <br>  condition {<br>    path_pattern {<br>      values = [&quot;/ice-station-zebra/*&quot;]<br>    }<br>  }<br>}</pre><pre>resource &quot;aws_alb_listener_rule&quot; &quot;http_443&quot; {<br>  listener_arn = data.aws_alb_listener.http_443.arn</pre><pre>  action {<br>    type = &quot;forward&quot;<br>    target_group_arn = aws_alb_target_group.http_80.arn<br>  }<br>  <br>  condition {<br>    host_header {<br>      values = [&quot;api.abq.com&quot;]<br>    }<br>  }<br>  <br>  condition {<br>    path_pattern {<br>      values = [&quot;/ice-station-zebra/*&quot;]<br>    }<br>  }<br>}</pre><h3>Elastic Container Service… Service</h3><p>Now, without going into too much detail around ECS, let’s make ourselves a Service and associate it with our ALB. Assume we already have an ECS cluster, task definition, and any appropriate Security Groups.</p><pre>resource &quot;aws_ecs_service&quot; &quot;non_blue_green&quot; {<br>  name = &quot;ice-station-zebra&quot;<br>  task_definition = local.task_definition<br>  desired_count = local.desired_task_instance_count<br>  deployment_maximum_percent = 200<br>  deployment_minimum_healthy_percent = 100<br>  launch_type = &quot;FARGATE&quot;<br>  platform_version = &quot;1.3.0&quot;<br>  scheduling_strategy = &quot;REPLICA&quot;<br><br>  load_balancer {<br>    container_name = &quot;app&quot;<br>    container_port = 8080<br>    elb_name = null<br>    target_group_arn = aws_alb_target_group.http_80.arn<br>  }<br><br>  cluster = var.ecs_cluster_arn<br>  propagate_tags = &quot;TASK_DEFINITION&quot;<br><br>  deployment_controller {<br>    type = &quot;ECS&quot;<br>  }<br><br>  network_configuration {<br>    security_groups = compact(concat(var.ecs_security_group_ids, [<br>      aws_security_group.ecs_service.id,<br>    ]))<br>    subnets = var.private_subnet_ids<br>    assign_public_ip = false<br>  }<br><br>  depends_on = [aws_alb_listener_rule.http_80, aws_alb_listener_rule.https_443]<br>}</pre><p>Did we just… is that it? I think so!</p><h3>Summary</h3><p>Requests will come into API Gateway at “https://api.abq.com/ice-station-zebra/*” and will pass through a VPC Service Endpoint (I covered all of that in Part I). Traffic will then make its way through an NLB and an ALB and finally, will land in our ECS Tasks. The Tasks’ responses will take the same path in the opposite direction.</p><p>I hope this has been helpful for you. As always, I’m happy to hear your feedback and thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b9294ead2e4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/laying-the-rails-from-aws-api-gateway-to-ecs-fargate-part-ii-7b9294ead2e4">Laying the Rails from AWS API Gateway to ECS Fargate | Part II</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laying the Rails from AWS API Gateway to ECS Fargate | Part I]]></title>
            <link>https://levelup.gitconnected.com/laying-the-rails-from-aws-api-gateway-to-ecs-fargate-part-i-debf754d6a8b?source=rss-9525d53f20d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/debf754d6a8b</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[elastic-container-service]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Lucas J. Ross]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 10:12:31 GMT</pubDate>
            <atom:updated>2020-06-30T19:06:54.180Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to building network pathways between two incongruous products (with Terraform)</h4><h4>Obsolescence Notice</h4><p>On March 12, Amazon published “<a href="https://aws.amazon.com/blogs/compute/building-better-apis-http-apis-now-generally-available/">Building faster, lower cost, better APIs — HTTP APIs now generally available</a>.” With that, I recommend that readers who wish to integrate API Gateway with an ALB ignore the instructions in this article involving an NLB and a target updater function. Instead, the VPC Link should be routed to an ALB directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSruvb9Fm65k6QO5G-pirg.png" /></figure><h3>Introduction</h3><p>Amazon offers exceptional flexibility when it comes to deploying and serving an application in a secure and development-friendly manner. Among the many benefits of this are the unique opportunities it presents with regard to drawing pictures of code, such as the above. On the other hand, sometimes that breadth of offerings creates situations where two seemingly compatible things, like an API gateway and a backend API, turn out to be pretty tricky to put together. I’d gladly accept that tradeoff over having to deal with an inflexible, prescriptive platform, but some of the subtle details of these integrations remain mysterious until you really dig in.</p><p>This series of articles will guide the reader in implementing a full integration path from API Gateway to ECS Fargate, including AWS Cognito client authentication at the front end (the gateway), a private integration with a VPC, load balancing, and secure HTTP. HCL for Terraform will be my primary means of showing configuration details, so I’ll assume you’re familiar with that tool as well as the general functions of the cloud resources involved. I’ll start at the gateway and work my way back (or forward, if you’re a backend developer).</p><p>This article is part one of two. The first will end with a discussion of the VPC Link, and the second will pick up from there.</p><h4>A note on code examples</h4><p>I always wonder, upon finding a code example to steal from a blog or Stack Overflow answer, where it might live within my app ecosystem. For this example, let’s assume we have a good number of backend services that we’d like to expose through the gateway. Some of the Terraform configuration will need to go into a shared project for infrastructure (hereafter, <em>infra</em>), which supplies resources to be shared by many components. Other configuration will go into a project for a single, exemplar service, which I’ll call <em>ice-station-zebra</em> as an homage to the best show currently on television, <em>Better Call Saul</em> (AMC, Mondays). Therefore, for each code example, I’ll try to provide context to that effect.</p><h4>Special thanks</h4><p>Some implementations herein are borrowed from the article <a href="https://www.bluematador.com/blog/static-ips-for-aws-application-load-balancer"><em>How to Use Static IPs for AWS Application Load Balancer</em></a>.</p><h3>Cognito</h3><p>Before setting up API Gateway, we should get this prerequisite out of the way. We’ll define a user pool and a <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-assign-domain.html">user pool domain</a> in our <em>infra</em> project. If your setup has different accounts for different stages (dev, prod, etc.) in your development pipeline, this should probably be applied on a per-environment (per-AWS-account) basis, as application users are a stage-specific entity.</p><pre>resource &quot;aws_cognito_user_pool&quot; &quot;users&quot; {<br>  name = &quot;users&quot;<br>}</pre><pre>resource &quot;aws_cognito_user_pool_domain&quot; &quot;users&quot; {<br>  domain = &quot;${var.stage}-users&quot;<br>  user_pool_id = aws_cognito_user_pool.users.id<br>}</pre><p>In our <em>ice-station-zebra</em> project, for each stage, we can pull in the ID of that user pool and set up the basics for Cognito authentication with the <a href="https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/">client credentials flow</a>, which is typical for machine-to-machine authentication. For simplicity, I’m configuring only <em>authentication</em> here and not an <em>authorization </em>mechanism—that’s another topic — so the <em>resource server</em> is mostly a placeholder. The aws_cognito_user_pool_client is the App Client.The attribute aws_cognito_user_pool_client.this.id provides the “username” for client_credentials authentication.</p><pre>data &quot;aws_cognito_user_pools&quot; &quot;users&quot; {<br>  name = &quot;users&quot;<br>}</pre><pre>locals {<br>  user_pool_id = tolist(data.aws_cognito_user_pools.users.ids)[0]<br>  cognito_idp_name = &quot;cognito-idp.${data.aws_region.current.name}.amazonaws.com/${local.user_pool_id}&quot;<br>}<br><br>resource &quot;aws_cognito_resource_server&quot; &quot;this&quot; {<br>  identifier = &quot;ice-station-zebra&quot;<br>  name = &quot;ice-station-zebra&quot;<br>  user_pool_id = local.user_pool_id<br>  scope {<br>    scope_name = &quot;read&quot;<br>    scope_description = &quot;Read&quot;<br>  }<br>  scope {<br>    scope_name = &quot;edit&quot;<br>    scope_description = &quot;Edit&quot;<br>  }<br>}<br><br>resource &quot;aws_cognito_user_pool_client&quot; &quot;this&quot; {<br>  name = var.name<br>  user_pool_id = local.user_pool_id<br>  supported_identity_providers = [&quot;COGNITO&quot;]<br>  generate_secret = true<br>  allowed_oauth_flows_user_pool_client = true<br>  allowed_oauth_flows = [&quot;client_credentials&quot;]<br>  allowed_oauth_scopes = aws_cognito_resource_server.this.scope_identifiers<br>}</pre><pre>output &quot;cognito_client_secret&quot; {<br>  sensitive = true<br>  value = aws_cognito_user_pool_client.this.client_secret<br>}</pre><p>I went ahead and added an output for the client secret (the password). Please keep in mind that Terraform stores some sensitive values in its state as plain text, so protect the state file and be cautious with running terraform output.</p><h3>API Gateway</h3><h4>Infrastructure</h4><p>Let’s go ahead and set up API Gateway in the <em>infra </em>project. As described in the Cognito section, this could be defined once per environment. Alternatively, it could be included in a “shared” configuration such that each API Gateway “stage” points to a different AWS environment account. This seems like what they had in mind with the stage feature, but whether you make effective use of it depends on how literally you take the notion that resources specific to a stage should be separated from those of another. With a single gateway for multiple stages, a CI/CD system might have to perform particular actions on the gateway during deployments, especially if a canary-type deployment is desired, whereas this approach treats it like any other resource.</p><pre>resource &quot;aws_api_gateway_account&quot; &quot;this&quot; {<br>  cloudwatch_role_arn = aws_iam_role.api_gateway_cloudwatch.arn<br>}</pre><p>Here’s that IAM role with an attached AWS-managed policy that allows API Gateway to push logs to CloudWatch.</p><pre>data &quot;aws_iam_policy_document&quot; &quot;api_gateway_assume_role&quot; {<br>  statement {<br>    actions = [&quot;sts:AssumeRole&quot;]<br>    principals {<br>      type = &quot;Service&quot;<br>      identifiers = [&quot;apigateway.amazonaws.com&quot;]<br>    }<br>  }<br>}</pre><pre>resource &quot;aws_iam_role&quot; &quot;api_gateway_cloudwatch&quot; {<br>  name = &quot;api-gateway-cloudwatch&quot;<br>  assume_role_policy = data.aws_iam_policy_document.api_gateway_assume_role.json<br>}</pre><pre>data &quot;aws_iam_policy&quot; &quot;api_gateway_cloudwatch&quot; {<br>  arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs&quot;<br>}</pre><pre>resource &quot;aws_iam_role_policy_attachment&quot; &quot;api_gateway_cloudwatch&quot; {<br>  role = aws_iam_role.api_gateway_cloudwatch.id<br>  policy_arn = data.aws_iam_policy.api_gateway_cloudwatch.arn<br>}</pre><p>Now, acting as API developers, we need to figure out which URL our consumers will use for the <em>ice-station-zebra</em> API. By default, a REST API provides an ugly URL, https://<em>{restapi-id}</em>.execute-api.<em>{region}</em>.amazonaws.com/<em>{stage}</em>. That URL can be used for integrations with AWS Lambda, but to use it for an integration with ECS tasks would require having a TLS certificate for that subdomain at various points along the integration path, and that certificate would not be obtainable by anyone except possibly Jeff Bezos. So, let’s pretend we own a domain, <em>abq.com</em>, and let’s say we have a TLS certificate for all its subdomains (<em>*.abq.com</em>)<em>.</em> I’d like the service’s REST API to be available at base path “https://api.abq.com/ice-station-zebra” and all its subpaths. This is for the sake of providing a thorough example, and you may wish to have a URL base path as simple as “https://ice-station-zebra.com” if you can see <em>ice-station-zebra</em> representing a singular monolithic backend.</p><p>Worth noting is that API Gateway also supports “HTTP APIs.” As of this writing, <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html">REST API is a more versatile option</a>; I’ll be a bit conservative and use a REST API for this example.</p><p>The first step for establishing this URL is to <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html">set up a <em>custom domain name</em></a> for a set of services that includes <em>ice-station-zebra</em>. This configuration is shared by multiple backend APIs and goes into the <em>infra</em> configuration. I’ve chosen to create a <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/create-regional-api.html">“regional” API</a>, which offers greater control over geographical distribution; the default endpoint type is EDGE. I’ve imported a TLS certificate in ACM, but if you use ACM for your Certificate Authority, there’s a <a href="https://www.terraform.io/docs/providers/aws/r/acm_certificate.html">resource</a> you can use instead of a data source.</p><pre>data &quot;aws_acm_certificate&quot; &quot;star_dot_abq_dot_com&quot; {<br>  domain = &quot;*.abq.com&quot;<br>}</pre><pre>resource &quot;aws_api_gateway_domain_name&quot; &quot;com_abq_api&quot; {<br>  domain_name = &quot;api.abq.com&quot;<br>  endpoint_configuration {<br>    types = [&quot;REGIONAL&quot;]<br>  }<br>  regional_certificate_arn = data.aws_acm_certificate.star_dot_abq_dot_com.arn<br>  security_policy = &quot;TLS_1_2&quot;<br>}</pre><h4>Service</h4><p>Before we can set up the “/ice-station-zebra” path, we need to Terraform our service-specific REST API in our <em>i-s-z</em> project. We can also set up the <em>authorizer</em>, which sets up Cognito authentication for the entire REST API. Now, all requests to our REST resources must include an “Authorization” header. The header value will be a Base-64-encoded JSON Web Token (and, oddly, must <strong>not</strong> be prefixed with “Bearer”).</p><pre>resource &quot;aws_api_gateway_rest_api&quot; &quot;this&quot; {<br>  name = &quot;ISZAPIv1&quot;<br>  endpoint_configuration {<br>    types = [&quot;REGIONAL&quot;]<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_authorizer&quot; &quot;cognito&quot; {<br>  name = &quot;${aws_api_gateway_rest_api.this.name}CognitoUserPoolAuthorizer&quot;<br>  type = &quot;COGNITO_USER_POOLS&quot;<br>  rest_api_id = aws_api_gateway_rest_api.this.id<br>  provider_arns = data.aws_cognito_user_pools.users.arns<br>  identity_source = &quot;method.request.header.Authorization&quot;<br>}</pre><p>One of the basic features of a gateway is allowing you to define REST resources with some standard specification like OpenAPI and integrating them with their respective backend endpoints. That practice is <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-method-settings.html">well-documented</a>, so here we’re going to be appropriately lazy and take advantage of the API Gateway <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/setup-http-integrations.html">HTTP Proxy</a> feature. It’s actually a great option for integrating a third-party/black-box kind of service that you host yourself and that has a self-defined API.</p><p>We’ll define a <em>resource</em> with subpath “{proxy+}” as well as a <em>method</em> for the proxy resource. The method’s reference to the “proxy” request parameter ensures that the proxied path fragment will be available in the <em>integration</em>. The integration is then able to pass that path fragment along to the integrated component, whatever that may be.</p><pre>resource &quot;aws_api_gateway_resource&quot; &quot;proxy&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.this.id<br>  parent_id = aws_api_gateway_rest_api.this.root_resource_id<br>  path_part = &quot;{proxy+}&quot;<br>}</pre><pre>resource &quot;aws_api_gateway_method&quot; &quot;proxy&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.this.id<br>  resource_id = aws_api_gateway_resource.proxy.id<br>  http_method = &quot;ANY&quot;<br>  authorization = &quot;COGNITO_USER_POOLS&quot;<br>  authorizer_id = aws_api_gateway_authorizer.cognito.id<br>  request_parameters = {<br>    &quot;method.request.path.proxy&quot; = true<br>  }<br>  authorization_scopes = aws_cognito_resource_server.this.scope_identifiers<br>}</pre><pre>resource &quot;aws_api_gateway_integration&quot; &quot;this&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.this.id<br>  resource_id = aws_api_gateway_resource.proxy.id<br>  http_method = aws_api_gateway_method.proxy.http_method<br>  integration_http_method = &quot;ANY&quot;<br>  type = &quot;HTTP_PROXY&quot;<br>  uri = &quot;https://api.abq.com/ice-station-zebra/{proxy}&quot;<br>  connection_type = &quot;VPC_LINK&quot;<br>  connection_id = &quot;$${stageVariables.vpcLinkId}&quot;<br>  request_parameters = {<br>    &quot;integration.request.path.proxy&quot; = &quot;method.request.path.proxy&quot;<br>  }<br>}</pre><p>As an aside, I probably wouldn’t use aws_api_gateway_resource and related resources to define a REST API, other than a proxying one. aws_api_gateway_rest_api takes a body argument, allowing you to <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/create-api-using-swagger.html">define everything with an OpenAPI/Swagger specification</a>. The imported spec needs some special attributes defined for API Gateway, but still seems a lot more maintainable for an API with a large number of resources. And the resource aws_api_gateway_documentation_part seems awkward compared to defining “description” attributes on resources. This is my hunch — your mileage may vary.</p><p>Further, we need <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-deploy-api.html">a <em>deployment</em> and a <em>stage</em></a>. This part is messy for a couple of reasons. Terraform can’t manage state for API Gateway stages without some tweaking. The community around the AWS Terraform provider seems to favor using create_before_destroy on the deployment, for instance, so that the stage isn’t left hanging with an invalid deployment ID. I found it occasionally necessary to run terraform taint on the deployment resource to force changes in other resources to be deployed. <a href="https://github.com/terraform-providers/terraform-provider-aws/issues/11344">There are open issues</a> with these resources, so use with caution. Also, in testing this, I found that deploying the REST API takes a while, and the previous deployment will stick around for a minute or two. That lag can be confusing if you’re expecting immediate feedback.</p><p>The vpc_link stuff will be explained in the next section.</p><pre>resource &quot;aws_api_gateway_deployment&quot; &quot;this&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.this.id<br>  stage_name = var.stage<br>  depends_on = [aws_api_gateway_integration.this]<br><br>  variables = {<br>    // just to trigger redeploy on resource changes<br>    resources = join(&quot;, &quot;, [aws_api_gateway_resource.proxy.id])<br><br>    // note: redeployment might be required with other gateway changes.<br>    // when necessary run `terraform taint &lt;this resource&#39;s address&gt;`<br>  }<br><br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}</pre><pre>data &quot;aws_api_gateway_vpc_link&quot; &quot;env&quot; {<br>  name = var.stage<br>}</pre><pre>resource &quot;aws_api_gateway_stage&quot; &quot;this&quot; {<br>  deployment_id = aws_api_gateway_deployment.this.id<br>  rest_api_id = aws_api_gateway_rest_api.this.id<br>  stage_name = aws_api_gateway_deployment.this.stage_name<br>  access_log_settings {<br>    destination_arn = aws_cloudwatch_log_group.api_gateway.arn<br>    // Common Log Format<br>    format = &quot;$context.identity.sourceIp $context.identity.caller $context.identity.user [$context.requestTime] \&quot;$context.httpMethod $context.resourcePath $context.protocol\&quot; $context.status $context.responseLength $context.requestId&quot;<br>  }<br>  variables = {<br>    vpcLinkId = data.aws_api_gateway_vpc_link.env.id<br>  }<br>}</pre><p>We also need to map the REST API to a <em>base path</em> to be appended to our domain. Getting this right in conjunction with the proxy path and the integration URI was confusing — if only I had had a <a href="https://medium.com/swlh/a-tale-of-two-aws-iam-roles-in-springfield-d19a4f9ffd91?source=friends_link&amp;sk=b6a97091062d1013cac2b36ac01181cd">Simpsons analogy</a> for it! Basically, the part of the path that is proxied in the request method’s “{proxy}” placeholder will go onto the end of the base path mapping, and that URL becomes the request that the gateway makes to the API’s integrations. The end result is that <a href="https://en.wikipedia.org/wiki/The_Myth_of_Sisyphus">the URL that comes in is the same one that goes out</a>.</p><pre>resource &quot;aws_api_gateway_base_path_mapping&quot; &quot;this&quot; {<br>  domain_name = &quot;api.abq.com&quot;<br>  api_id = aws_api_gateway_rest_api.this.id<br>  stage_name = aws_api_gateway_stage.this.stage_name<br>  base_path = &quot;ice-station-zebra&quot;<br>}</pre><p>The integration URI hostname doesn’t technically have to be the same as the custom domain name, but it’s a practical choice for a couple reasons. I’ll show in the next section that the private link between API Gateway and your VPC requires you to own a domain name for which you’re able to modify public DNS records. You may as well reuse that property for internal purposes.</p><p>Finally, let’s create a CloudWatch Log Group with a name in <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html">a specific format that API Gateway will recognize</a>.</p><pre>resource &quot;aws_cloudwatch_log_group&quot; &quot;api_gateway&quot; {<br>  name = &quot;API-Gateway-Execution-Logs_${aws_api_gateway_rest_api.this.id}/${aws_api_gateway_deployment.this.stage_name}&quot;<br>  retention_in_days = 7<br>}</pre><h3>VPC Link</h3><p>Integrating API Gateway with resources in a VPC starts with a <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-private-integration.html">VPC Link</a> to a Network Load Balancer. I’ll go over the NLB in a later section, but it is a prerequisite of the VPC Link. This — and most other resources from this point on— fit into the realm of <em>infrastructure.</em></p><pre>resource &quot;aws_api_gateway_vpc_link&quot; &quot;this&quot; {<br>  name = var.stage<br>  target_arns = [aws_lb.network.arn]<br>}</pre><p>A VPC Link is a <a href="https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-service.html">VPC Endpoint Service</a> with one entry in its list of “Whitelisted principals”: the root of the AWS-managed account that serves API Gateway for the configured region (<a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-api-with-vpclink-accounts.html">there’s a list</a>).</p><p>In case you’re following this article as a tutorial, here is a basic Network Load Balancer.</p><pre>resource &quot;aws_lb&quot; &quot;network&quot; {<br>  name = &quot;nlb&quot;<br>  load_balancer_type = &quot;network&quot;<br>  enable_cross_zone_load_balancing = true<br>  internal = false<br>  subnets = var.private_subnet_ids<br>}</pre><h4>Private DNS</h4><p>Creating the vpc_link resource with Terraform is just a start, and there is a bit of manual work required. The VPC Link starts out with its private DNS name missing. Without it, the gateway will return cryptic 500 errors, as it’s trying to hit a VPC endpoint URI that doesn’t match the interpolated integration URI. We configured the integration resource with uri = &quot;https://api.abq.com/ice-station-zebra/{proxy}&quot;; that endpoint doesn’t exist until we define it as a private DNS name. This <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started-with-private-integration.html">isn’t really explained in the docs</a>. This screenshot shows the kind of end result that we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C8R8ECSWhpni3oUXNKKoQw.png" /></figure><p>The private DNS name needs to be “Verified” before it will be accessible. Here’s how I did it:</p><ol><li>In the AWS console, set the private DNS name (e.g., “api.abq.com”).</li><li>The “Domain verification status” should now be “Pending.” Get the “Domain verification name” and “Domain verification value.”</li><li>With your DNS provider, register a TXT record for the domain name with the value <em>{domain verification name}</em>=<em>{domain verification value}</em>. (Just an equals sign between them.)</li><li>In the AWS console, hit the button to verify the DNS name.</li><li>Wait like, 10 minutes.</li></ol><p>In the aws_api_gateway_stage, we referenced this VPC Link’s ID under variables. That allows us to reference it with “${stageVariables.vpcLinkId}”. Amazon recommends this over defining the ID directly so that “you can easily switch to different VPC links for the API by changing the stage variable value.” If you don’t switch stages, this indirection probably isn’t useful.</p><h3>Summary</h3><p>In this first part of a two-part series, I’ve demonstrated how to integrate AWS API Gateway, Cognito, and VPC Service Endpoints. I’d love to hear your feedback. I’ll post Part II sometime this week. Thanks for reading.</p><h4>Follow-Up</h4><p>Part II:</p><p><a href="https://medium.com/@lucjross/laying-the-rails-from-aws-api-gateway-to-ecs-fargate-part-ii-7b9294ead2e4">Laying the Rails from AWS API Gateway to ECS Fargate | Part II</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=debf754d6a8b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/laying-the-rails-from-aws-api-gateway-to-ecs-fargate-part-i-debf754d6a8b">Laying the Rails from AWS API Gateway to ECS Fargate | Part I</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Tale of Two AWS IAM Roles (in Springfield)]]></title>
            <link>https://medium.com/swlh/a-tale-of-two-aws-iam-roles-in-springfield-d19a4f9ffd91?source=rss-9525d53f20d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d19a4f9ffd91</guid>
            <category><![CDATA[identity-management]]></category>
            <category><![CDATA[the-simpsons]]></category>
            <category><![CDATA[role-based-access-control]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Lucas J. Ross]]></dc:creator>
            <pubDate>Mon, 23 Mar 2020 04:55:04 GMT</pubDate>
            <atom:updated>2020-03-24T20:07:14.126Z</atom:updated>
            <content:encoded><![CDATA[<p>As a long-time fan of classic <em>The Simpsons</em>, when I need an analogy to help a colleague or myself to comprehend a subject, I find it natural to make use of characters and situations from the show. In this article, I’d like to share one on a topic that at first I found confusing, IAM Roles in AWS and the way users assume them.</p><p>A little context: any developer of infrastructure for software in the cloud will, early in that effort, need to figure out how users (both human and machine) are going to be able to access various resources. A best practice is to use multiple accounts to ensure separation among a development environment, a production environment, a management account, and possibly many others. You probably wouldn’t want an IAM user for a given person defined in every one of those accounts; managing permissions for every user in your organization would be terribly repetitive. Also, in most organizations there exist a number of different business functions, and a user who may access Redshift and Kinesis data streams should not necessarily be able to mess around with network infrastructure and backend services.</p><p>That’s where role-based access control comes in, and AWS offers two essential strategies for implementing it. One is <em>federation</em>, which involves either Single Sign-On with a directory server or third-party authentication using a web identity provider like Google. A user logs into one of these services to obtain temporary credentials for an IAM user with user-specific policies assigned by the authentication server. The other strategy is <em>delegation</em>, and in this approach, IAM users defined in only one account are allowed to assume certain roles (in that account or in others) that have certain policies. This article will address the latter.</p><p>In case you’re wondering which one would be better for your situation, the SSO approach scales better and is practically a necessity for a larger and more mature organization that uses many third-party services and possibly multiple cloud providers. Delegation is less messy and may be easier to manage for a smaller user base, especially if it doesn’t have a dedicated systems/security administrator. One advantage of delegation is that all things IAM (even users) can be defined entirely in code using a tool like Terraform. The two approaches may be combined to obtain the advantages of both.</p><h3>The Analogy</h3><p>Bart Simpson attends Springfield Elementary from time to time and when he does, we can say that he is assuming the role of student at the school. That role is assumed on a temporary basis, and only by specific users (school-aged children who live east of the railroad tracks).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MX7T6W5jNGB_b5hLPgnzRw.png" /></figure><p>In IAM terms, the Simpsons home and Springfield Elementary could be aliases for two accounts. user/bart is defined in the “Simpsons home.” Bart is part of an IAM Group, school-aged-children, and it’s Bart’s membership in that Group that gives him the ability to assume roles. Although Marge Simpson probably doesn’t think of her three children in terms of user groups, having Policies attached directly to Users in a organization larger than the Simpsons family brings problems with manageability and consistency, and so, it’s best practice to assign Users to Groups with group-level Policies.</p><p>The ability of Bart to assume the role of student entails a bidirectional relationship with Springfield Elementary. Marge has enrolled Bart in school, conferring upon him (attaching to his IAM Group) a Policy such as:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: {<br>    &quot;Effect&quot;: &quot;Allow&quot;,<br>    &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>    &quot;Resource&quot;: &quot;arn:aws:iam::&lt;school account ID&gt;:role/student&quot;<br>  }<br>}</pre><p>And in turn, Springfield Elementary also allows Bart to assume the role of student there, forming (begrudgingly) a <em>trust relationship</em> with him. A Policy is attached to or defined on role/student:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: {<br>    &quot;Effect&quot;: &quot;Allow&quot;,<br>    &quot;Principal&quot;: {<br>      &quot;AWS&quot;: &quot;arn:aws:iam::&lt;Simpsons home account ID&gt;:root&quot;<br>    },<br>    &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>  }<br>}</pre><p>It would be ideal in this case to use the Group school-aged-children as the Principal, but IAM Groups cannot be used as Principals. The Policy must reference either the specific user— e.g., “arn:aws:iam::&lt;Simpsons home account ID&gt;:user/bart” — or the entire Account as defined above.</p><h4>Extending the Analogy</h4><p>Occasionally the school sends students on field trips. Due to budget cuts, a frequent destination of them is the Cracker Factory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zb7dyvDzhaBCP5inRzcr1w.png" /></figure><p>Consider that a child generally does not go straight from home to a field trip destination — Marge has no impetus to allow Bart to travel to the cracker factory on his own. He’s able to assume role/field-trip-attendant only as a student, so we attach a Policy like this to the student role (yes, roles may assume other roles):</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: {<br>    &quot;Effect&quot;: &quot;Allow&quot;,<br>    &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>    &quot;Resource&quot;: &quot;arn:aws:iam::&lt;Cracker Factory&gt;:role/field-trip-attendant&quot;<br>  }<br>}</pre><p>And, just as Springfield Elementary allows Bart to attend school, the cracker factory allows Springfield Elementary students to tour their facilities.</p><p>Further, Marge provides Bart with a permission slip —user/bart has a Policy attached— that allows him to visit the cracker factory only within certain hours. user/bart is already able to assume role/field-trip-attendant by assuming it indirectly through role/student; this policy effectively introduces additional constraints by taking advantage of <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html">IAM policy evaluation logic</a>.</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: {<br>    &quot;Effect&quot;: &quot;Allow&quot;,<br>    &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>    &quot;Resource&quot;: &quot;arn:aws:iam::&lt;Cracker Factory&gt;:role/field-trip-attendant&quot;,<br>    &quot;Condition&quot;: {<br>      &quot;DateGreaterThan&quot;: {<br>        &quot;aws:CurrentTime&quot;: &quot;2020-03-01T17:00:00Z&quot;<br>      },<br>      &quot;DateLessThan&quot;: {<br>        &quot;aws:CurrentTime&quot;: &quot;2020-03-01T18:59:59Z&quot;<br>      }<br>    }<br>  }<br>}</pre><p>At this point I should mention that this implementation is an oversimplification of the analogy case. Of course, Springfield Elementary won’t just allow any student to leave for a tour of the cracker factory at any time, as much as the children may yearn to do so. The student role could be given a Policy that at all times, mirrors the permissions granted to the students by the parents on an individual basis.</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: {<br>    &quot;Effect&quot;: &quot;Allow&quot;,<br>    &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>    &quot;Resource&quot;: &quot;arn:aws:iam::&lt;Cracker Factory&gt;:role/field-trip-attendant&quot;,<br>    &quot;Condition&quot;: {<br>      &quot;StringLike&quot;: {<br>        &quot;aws:userid&quot;: [<br>          &quot;arn:aws:iam::&lt;Simpsons home&gt;:user/bart&quot;,<br>          &quot;arn:aws:iam::&lt;Van Houten home&gt;:user/milhouse&quot;,<br>          ...<br>        ]<br>      },<br>      &quot;DateGreaterThan&quot;: ...,<br>      &quot;DateLessThan&quot;: ...<br>    }<br>  }<br>}</pre><p>However, an actual AWS scenario would have all accounts managed by one team, not by disparate groups (parents, school, cracker factory manager) that aren’t necessarily synced with each other, so one might consider these additional role constraints overly defensive.</p><h4>Some Practical Notes</h4><ul><li>The permission “sts:AssumeRole” may be allowed for Users, Roles, Services, and <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html">a few other principal types</a>.</li><li>In the AWS Console, a role may be assumed by going into the account dropdown in the upper right and selecting Switch Role. The <a href="https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html">CLI command</a> is aws sts assume-role --role-arn &lt;arn&gt;.</li><li><a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html">Permissions boundaries</a> are a perfectly cromulent way to define user permissions in broad strokes. A role-level boundary could allow “ec2:*”, while a user group that can assume that role could have a more restrictive policy that denies, say, “ec2:AuthorizeSecurityGroupIngress”.</li><li>Note that assumed role sessions (time-limitation entities created upon assuming a role) have a maximum duration of twelve hours (more than enough for Bart’s school day, not including detention). An exception to this is a role session obtained by assuming a role from another role, which is limited to one hour. When that’s not enough, the role must be assumed directly by the user.</li></ul><h3>Summary</h3><p>My goal for this was to share a simple analogy for IAM roles and role assumptions. It’s my sincere hope that this writing has embiggened your spirit. I welcome your feedback and thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d19a4f9ffd91" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-tale-of-two-aws-iam-roles-in-springfield-d19a4f9ffd91">A Tale of Two AWS IAM Roles (in Springfield)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>