<?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 Jan Groth on Medium]]></title>
        <description><![CDATA[Stories by Jan Groth on Medium]]></description>
        <link>https://medium.com/@jan.groth.de?source=rss-f45ce30b5f86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*efGwPwlTbVm9FzXYCrPLQw.jpeg</url>
            <title>Stories by Jan Groth on Medium</title>
            <link>https://medium.com/@jan.groth.de?source=rss-f45ce30b5f86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:48:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jan.groth.de/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[No Time for Tests? — 12 Recommendations on Unit-Testing AWS Lambdas in Python]]></title>
            <link>https://medium.com/swlh/no-time-for-tests-12-recommendations-on-unit-testing-aws-lambdas-in-python-6a74ca8bb0c1?source=rss-f45ce30b5f86------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a74ca8bb0c1</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Jan Groth]]></dc:creator>
            <pubDate>Tue, 18 Aug 2020 11:11:59 GMT</pubDate>
            <atom:updated>2020-08-20T12:36:39.394Z</atom:updated>
            <content:encoded><![CDATA[<h4>AWS Lambda — serverless — Python — DEVOPS</h4><h3>No Time for Tests? — 12 Recommendations on Unit-Testing AWS Lambdas in Python</h3><h4>This is the second of two articles about writing and testing DevOps-y Lambdas. It focuses on implementing readable and meaningful unit tests that don’t require complicated setups.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZ2EuJcS1t0rfd8kOrwDjQ.png" /></figure><p>Much like software applications, infrastructure provisioning has moved away from monolithic solutions, shifting focus towards decoupled components and utilisation of public service APIs. Tasks that traditionally would have required a great deal of orchestration and heavy tooling have transformed into lightweight event-driven services. Frameworks like the <a href="https://aws.amazon.com/serverless/sam/">AWS Serverless Application Model</a> (AWS SAM) have come a long way and make it easy to implement complex applications in a “microservice-style”, often with little more than a few Lambdas as building blocks.</p><p>In the <a href="https://medium.com/swlh/10-recommendations-for-writing-pragmatic-aws-lambdas-in-python-5f4b038caafe">previous article</a>, I’ve shared my thoughts on implementing readable, testable and maintainable AWS Lambdas. In this article, I’ll write about <strong>unit-testing the code</strong>.</p><p>From my own experience, I know that unit tests can be tricky for many DevOps projects — Which seems to be mostly due to the mechanics of writing good tests, as well as people’s creativity when it comes to why it’s just not the right time for it :)</p><p>This is not the place to argue against ‘there is no time for tests’ (for the record: I wholeheartedly disagree), so let me move on to demonstrate that writing meaningful tests for AWS Lambda is not difficult at all.</p><h3>What to expect</h3><p>I will be using the same exemplary problem statement than before (“<em>Restricting inbound and outbound traffic for default security groups”</em>), but will now focus at the testing side of things.</p><p>The complete working example can be found on GitHub:</p><p><a href="https://github.com/jangroth/writing-aws-lambdas-in-python">github.com/jangroth/writing-aws-lambdas-in-python</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFHiX__niSEO9lMhTTaBGQ.png" /></figure><p>All source code examples are taken from there. You are welcome to follow along by setting up the project yourself.</p><h3><em>Writing tests that are easy to read and to maintain</em></h3><p>Let’s start by looking at the setup and structure of tests. To me, the benchmark for a good test is how well it covers the source code and how easy it is to read.</p><p>I’m using pytest for the examples, mostly because I like the modern syntax and <em>fixtures</em> as a technique to help to keep tests readable. However, using unittest from the Python SDK is completely acceptable and only requires minor changes.</p><p><strong>1. Make tests easy to run—and hard to ignore</strong></p><p>Here is something that I think the Java ecosystem does a little better than Python: Projects usually follow the same directory layout, and by default building a project will already include running all tests, simply because build tools follow conventions and know where to find everything.</p><p>In Python, the tooling landscape is different, and there is no one single directory layout that most projects implement. Often, this means that setting up a project and figuring out how to run the tests is up to the quality of the documentation.</p><p>If you are not already set with your build system, I recommend implementing a makefile with an explicit test-target. While there are many different build systems out there, from my experience makefiles are widely understood and easy to install.</p><pre>check: <em>## Run linters<br>   ...</em></pre><pre><strong>test: check <em>## Run tests<br>   </em>PYTHONPATH=./src pytest </strong>--cov=src --cov-report term-missing<strong><br>   @echo &#39;*** all tests passing ***&#39;</strong></pre><pre>deploy: <strong>test</strong> [...] <em>## Deploy project<br>   ...</em></pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/75ffaa03dabd1cbc0db9d569a27b902bb6146e3a/Makefile#L31"><em>source</em></a>]</pre><p>If you already have a build system in place, by all means, use that. Just make sure it’s running your tests both explicitly on a test target and implicitly on the build and deploy targets.</p><p><strong>2. Mock out external dependencies</strong></p><p>In the <a href="https://medium.com/swlh/10-recommendations-for-writing-pragmatic-aws-lambdas-in-python-5f4b038caafe">first article</a>, I mentioned that using classes and moving the initialisation of external dependencies into the constructor would simplify the creation of test objects. Here is how it works:</p><p>In Python, the typical way of instantiating an object is by invoking its constructor:</p><pre>obj = <strong>RevokeDefaultSg()</strong></pre><pre>class <strong>RevokeDefaultSg</strong>:<br>    def <strong>__init__</strong>(self, region=&quot;ap-southeast-2&quot;):<br>        self.<strong>logger</strong> = logging.getLogger(...)<br>        self.<strong>ec2_client</strong> = boto3.client(...)<br>        self.<strong>ec2_resource</strong> = boto3.resource(...)<br>   ...</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/75ffaa03dabd1cbc0db9d569a27b902bb6146e3a/src/revokedefaultsg/app.py#L27"><em>source</em></a>]</pre><p>This code will initialize logger and boto helpers.</p><p>For tests, this is problematic, because we do not want to call out into AWS from unit tests. Instead, we can use an alternative way to instantiate objects: In Python, the __new__ -method creates an instance of a class without invoking the constructor (<a href="https://docs.python.org/3/reference/datamodel.html#object.__new__">documentation</a>). In tests, this allows to create a ‘skeleton’ instance that has its individual instance attributes replaced by mocks:</p><pre>def obj():<br>    obj = <strong>RevokeDefaultSg.__new__(RevokeDefaultSg)</strong><br>    obj.logger = <strong>MagicMock()</strong><br>    obj.ec2_client = <strong>MagicMock()</strong><br>    obj.ec2_resource = <strong>MagicMock()</strong><br>    return obj</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/91c94af83e89102edc76158cdbf2cbfdfbe7e2e3/tests/unit/test_revoke_default_sg.py#L51"><em>source</em></a>]</pre><p>A concrete test can then use this skeleton object (more on fixture in the next chapter) and set up the mocks according to the test case:</p><pre><strong>@fixture</strong><br>def <strong>obj</strong>():<br>    ...</pre><pre>def test_should_tag_if_ingress_was_revoked(<strong>obj</strong>):<br>    mock_sg = MagicMock()<br>    mock_sg.ip_permissions = &quot;ingress&quot;<br>    mock_sg.ip_permissions_egress = None<br>    <strong>obj.ec2_resource.SecurityGroup.return_value</strong> = mock_sg</pre><pre>    obj._revoke_and_tag(TEST_SG)<br>    ...</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/91c94af83e89102edc76158cdbf2cbfdfbe7e2e3/tests/unit/test_revoke_default_sg.py#L99"><em>source</em></a>]</pre><p>This is how both execution paths for _revoke_and_tag() look for original and test invocation side by side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-L1fvQa1P2IzMIYd4dkHWA.png" /></figure><p>Looping back to the initial statement — the fundamental idea of this strategy is → <em>identifying</em> things that are hard to set up in unit-tests<em>, </em>→<em>bundling</em> them in a single location, →<em>bypassing</em> invocation for testing and →<em>injecting </em>mocks where required.</p><p>A variant of this approach is patching objects or modules using @patch rather than bypassing code execution with __new__. While the results are similar, I prefer the constructor-based approach. That’s probably my Java development background as well as a lack of understanding of Python’s import name-spacing model, which usually leaves me without a clue how to debug patches if they don’t do what they should. For me, bypassing initialization just works.</p><p><strong>3. Create test data in re-usable helper methods</strong></p><p>Almost always tests need data to process.</p><p>For example, if we want to test process_event(), we must provide it with a sample Lambda event that it can run against:</p><pre>def <strong>process_event</strong>(self, <strong>event</strong>):<br>    sg_id = self._extract_sg_id(<strong>event</strong>)<br>    if self._is_default_sg(sg_id):<br>        self.logger.info(...)<br>        self._revoke_and_tag(sg_id)<br>    else:<br>        self.logger.info(...)<br>    return &#39;SUCCESS&#39;</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/75ffaa03dabd1cbc0db9d569a27b902bb6146e3a/src/revokedefaultsg/app.py#L75"><em>source</em></a>]</pre><p>A sample event isn’t complicated and could easily be created in the test itself:</p><pre>&quot;id&quot;: &quot;12345678-b00a-ede7-937b-b4da1faf5b81&quot;,<br>&quot;detail&quot;: {<br>   &quot;eventVersion&quot;: &quot;1.05&quot;,<br>   &quot;eventTime&quot;: &quot;2020-02-05T12:34:56Z&quot;,<br>   &quot;eventSource&quot;: &quot;ec2.amazonaws.com&quot;,<br>   &quot;eventName&quot;: &quot;AuthorizeSecurityGroupIngress&quot;,<br>   &quot;eventID&quot;: &quot;12345678-6466-4720-955e-e342e782d405&quot;,<br>   &quot;eventType&quot;: &quot;AwsApiCall&quot;,<br>   &quot;requestParameters&quot;: {<br>      &quot;groupId&quot;: &quot;sg-123&quot;<br>   }<br>}</pre><p>However, events aren’t exactly small and have a lot more data than we are interested in, so creating them on a per-test base would add noise and repetition. A better strategy is implementing dedicated helper methods for test data. For more complex scenarios different helpers can be combined or can build on each other.</p><p>Conveniently, pytest has a handy feature called ‘<a href="https://docs.pytest.org/en/2.8.7/fixture.html">fixture</a>’, which allows to annotate a method and have its output injected into test cases. This example uses two fixtures — one for the test event and one for the skeleton object (see issue above):</p><pre><strong>@fixture</strong><br>def <strong>good_event</strong>():<br>    return {<br>        &quot;id&quot;: &quot;3469fd4b-b00a-ede7-937b-b4da1faf5b81&quot;,<br>        &quot;detail&quot;: {<br>        ...<br>            }<br>        }<br>    }</pre><pre><strong>@fixture</strong><br>def <strong>obj</strong>():<br>    obj = RevokeDefaultSg.__new__(RevokeDefaultSg)<strong><br></strong>    ...</pre><pre>def test_that_uses_good_event(<strong>obj,</strong> <strong>good_event</strong>):<br>    ...<br>    <strong>obj</strong>.process_event(<strong>good_event</strong>)<br>    ...</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/91c94af83e89102edc76158cdbf2cbfdfbe7e2e3/tests/unit/test_revoke_default_sg.py#L15"><em>source</em></a>]</pre><p>Whether you use fixtures or prefer to call methods explicitly, having dedicated helpers for test data creation is a clean technique to keep noise out of the test itself and to allow re-use across multiple tests.</p><p><strong>4. Test one thing at a time and mock out complexity</strong></p><p>It can be tempting to squeeze multiple aspects into one test case and to fire off a whole series of assertions at the end — But usually, that’s not a good idea: Complex tests can be a nightmare to understand and to maintain.</p><p>When it comes to testing, readability counts at least as much as for production code; or maybe even more so, as tests are often written in a ‘fire and forget’ style. Focusing on a single condition per test case makes it much easier to understand the test and to grasp the problem in case of failure.</p><p>For example, let’s say we want to test the path where a security group is not the default security group and nothing should be revoked. That’s everything printed in bold:</p><pre>def process_event(self, event):<br><strong>    sg_id = self._extract_sg_id(event)<br>    if self._is_default_sg(sg_id):</strong><br>        self.logger.info(...)<br>        self._revoke_and_tag(sg_id)<br>    <strong>else:</strong><br><strong>        self.logger.info(...)</strong><br><strong>    return &#39;SUCCESS&#39;</strong></pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/75ffaa03dabd1cbc0db9d569a27b902bb6146e3a/src/revokedefaultsg/app.py#L75"><em>source</em></a>]</pre><p>To create a test case, let’s look at what is simple and straightforward to accomplish:</p><ul><li>_extract_sg_id() only extracts data from a dict — this can easily be called, provided that the incoming event contains the right data (taken care of by a fixture).</li><li>_is_default_sg() needs to call out to the EC2-API —<em> </em>not so easy to test, and even more importantly, not relevant for this test case. Replacing the method with a mock allows focusing on what we want to test. All we have to do is set up the mock to return False when called.</li><li>the else branch is tricky, as we are testing for ‘nothing to happen’. However, we can invert the logic and make sure that the if branch was not called. For that, we replace _revoke_and_tag() with a mock and assert that it was not invoked. This is easy with MagicMock.assert_not_called()(<a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_not_called">link</a>).</li></ul><p>Putting everything together the test looks like this:</p><pre>def test_should_process_event_and_do_nothing_if_non_default_sg(...):<br>    obj._is_default_sg = MagicMock(return_value=<strong>False</strong>)<br>    obj._revoke_and_tag = MagicMock()<br><br>    obj.process_event(good_event)<br><br>    obj.<strong>_is_default_sg.assert_called_once_with(TEST_SG)</strong><br>    obj.<strong>_revoke_and_tag.assert_not_called()</strong></pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/91c94af83e89102edc76158cdbf2cbfdfbe7e2e3/tests/unit/test_revoke_default_sg.py#L69"><em>source</em></a>]</pre><p>That’s five simple lines of code for a complete test case!</p><p>By the way, testing the alternative path through the method (‘<em>is</em> default security group and <em>should</em> be revoked’) is almost easier, as we can assert directly on the _revoke_and_tag()mock and don’t have to invert logic:</p><pre>def test_should_process_event_and_revoke_if_default_sg(obj, good_event):<br>    obj._is_default_sg = MagicMock(return_value=<strong>True</strong>)<br>    obj._revoke_and_tag = MagicMock()<br><br>    obj.process_event(good_event)<br><br>    obj.<strong>_is_default_sg.assert_called_once_with(TEST_SG)</strong><br>    obj.<strong>_revoke_and_tag.assert_called_once_with(TEST_SG)</strong></pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/91c94af83e89102edc76158cdbf2cbfdfbe7e2e3/tests/unit/test_revoke_default_sg.py#L69"><em>source</em></a>]</pre><p><strong>5. Use ridiculously obvious variable and parameter names</strong></p><p>Unlike production code, in tests it doesn’t really matter how many variables you use or how you name them. The only goal is to make tests as readable as possible.</p><p>For example, we could have called the fixtures something like event1, event2 and event3. But how much more obvious are names like good_event, bad_event and unknown_event? This test case doesn’t leave the shadow of a doubt of what’s going on:</p><pre>def test_should_raise_exception_if_wrong_event(obj, <strong>bad_event</strong>):<br>    with pytest.raises(UnknownEventException):<br>        obj._extract_sg_id(<strong>bad_event</strong>)</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/91c94af83e89102edc76158cdbf2cbfdfbe7e2e3/tests/unit/test_revoke_default_sg.py#L137"><em>source</em></a>]</pre><p>Similarly, it can be a good idea to extract constants only for the purpose of giving them a name that’s self-explanatory:</p><pre><strong>DEFAULT_GROUP</strong> = {&quot;GroupName&quot;: &quot;default&quot;}<br><strong>NOT_A_DEFAULT_GROUP</strong> = {&quot;GroupName&quot;: &quot;not default&quot;}</pre><pre>def <strong>test_should_find_default_sg</strong>(obj):<br>    obj.ec2_client.describe_security_groups.return_value = {&quot;SecurityGroups&quot;: [<strong>DEFAULT_GROUP</strong>]}<br><br>    assert obj._is_default_sg(TEST_SG)<br><br><br>def <strong>test_should_find_non_default_sg</strong>(obj):<br>    obj.ec2_client.describe_security_groups.return_value = {&quot;SecurityGroups&quot;: [<strong>NOT_A_DEFAULT_GROUP</strong>]}<br><br>    assert not obj._is_default_sg(TEST_SG)</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/91c94af83e89102edc76158cdbf2cbfdfbe7e2e3/tests/unit/test_revoke_default_sg.py#L9"><em>source</em></a>]</pre><p>Okay, one would have probably guessed the meaning of the dictionaries without the explicitly named constants. But with the constants, it’s just <em>impossible</em> to miss the purpose. Even more so if data structures are more complex than in this example.</p><h3>Saving yourself time and effort</h3><p>Finally, let’s look at a few ways that can save you time when writing tests. This is a collection of tips that I find useful, from using the best possible tooling to focusing on the right things to test:</p><p><strong>6. Did you know about debuggers?</strong></p><p>This is most likely a no-brainer if you have used other modern programming languages before. If not, my advice is to set yourself up with an environment that provides sophisticated support for Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmeFMdkj7_jV6LgpvX3amA.png" /></figure><p>A text editor will get you through <em>hello_world()</em>, but will leave you on your own when it comes to language-specific support like automated refactorings and — even more importantly — testing and debugging of complex code.</p><p>Combining good tests with a debugger gives you a powerful tool, where you can step through your code in an almost real-world scenario, completely in control of all aspects of the execution. Gone are the days when ‘debugging’ described the activity of gradually adding more and more print statements to the code.</p><p><a href="https://www.jetbrains.com/pycharm/">PyCharm</a> and <a href="https://code.visualstudio.com/">Visual Studio Code</a> are both excellent IDEs that are available for free. If you can’t decide between the two, simply go with what the majority of your peers are using.</p><p><strong>7. Make sure you saw every test case failing</strong></p><p>It might sound trivial, but it isn’t: People are making mistakes when writing code, and they also make mistakes when writing tests.</p><p>From my own experience, I can tell how frustrating it is to sink hours into debugging a problem, only to eventually find out that the base assumption ‘<em>the tests are passing</em>’ doesn’t mean that the code is doing what it’s supposed to do. Always succeeding tests are the worst kind of friends. And they are pretty easy to produce — a tiny mistake in the assertion logic could be all it takes.</p><p>A good safeguard against this is to make sure that tests are really failing when some conditions aren’t met. This can either be achieved by writing tests beforehand (also see the last tip about this), or by commenting the code that implements the feature under test.</p><p><strong>8. Order test cases by relevance</strong></p><p>This is tiny, but valuable when looking at a screen full of tests:</p><p>It’s easier for future readers — including yourself — to get the high-level picture before getting to the details, and to read about ‘happy’ cases before diving into error scenarios.</p><p>You don’t have to be religious about it, but it’s a real help to structure the test suite in a loose top-down style from ‘<em>very important for how the Lambda works</em>’ to ‘<em>edge cases it also covers</em>’:</p><pre>test_should_process_event_and_revoke_if_default_sg(...)<br>test_should_process_event_and_do_nothing_if_non_default_sg(...)</pre><pre>...</pre><pre>test_should_find_default_sg(...)<br>test_should_not_tag_if_nothing_was_revoked(...)</pre><pre>...</pre><pre>test_should_raise_exception_if_unknown_event(...)<br>test_should_raise_exception_if_bad_event(...)</pre><p><strong>9. Hate documenting your code? — Write a test instead</strong></p><p>This is so much better than documenting code in comments or — even worse — Confluence pages: Tests are the perfect tool to describe the behaviour of your code unambiguously. And it’s pretty hard to ignore a failing test, so unlike their traditional counterparts, they don’t quietly run out of date.</p><p>Using tests for documentation requires two things:</p><ul><li>An explicit test case for the aspects that matter</li><li>A name that describes the intention as clearly as possible</li></ul><p>I find the loose pattern <strong>test_should_</strong>[something that&#39;s expected]<strong>_if_</strong>[something that happened] working well for me:</p><pre>test_should_process_event_and_revoke_if_default_sg<br>test_should_process_event_and_do_nothing_if_non_default_sg<br>test_should_raise_exception_if_wrong_event</pre><p>In case of test failure, it’s already obvious what went wrong only by the name of the failing test. Want to understand what a certain Lambda does? Just read the test cases (ideally, they are ordered by relevance as per the previous tip).</p><p><strong>10. Seriously, don’t test <em>boto</em></strong></p><p>(Or any other frameworks — I’m just using boto as an example here.)</p><p>What I mean by this: When making requests to boto, the response will usually contain a JSON object that requires filtering to get the relevant data out:</p><pre>{<br>  &quot;SecurityGroups&quot;: [<br>    {<br>      &quot;Description&quot;: &quot;default VPC security group&quot;,<br>      &quot;GroupName&quot;: &quot;default&quot;,<br>      &quot;IpPermissions&quot;: [],<br>      &quot;OwnerId&quot;: &quot;123456789012&quot;,<br>      &quot;GroupId&quot;: &quot;sg-12345678&quot;,<br>      &quot;IpPermissionsEgress&quot;: [],<br>      &quot;Tags&quot;: [],<br>      &quot;VpcId&quot;: &quot;vpc-12345678&quot;<br>    }<br>  ],<br>  &quot;ResponseMetadata&quot;: {<br>    &quot;RequestId&quot;: &quot;12345678-3233-4eff-969f-7c6b43ff8f60&quot;,<br>    &quot;HTTPStatusCode&quot;: 200,<br>    &quot;HTTPHeaders&quot;: {<br>      &quot;x-amzn-requestid&quot;: &quot;12345678-3133-4eff-969f-7c6b43ff8f60&quot;,<br>      &quot;content-type&quot;: &quot;text/xml;charset=UTF-8&quot;,<br>      &quot;content-length&quot;: &quot;857&quot;,<br>      &quot;date&quot;: &quot;Sat, 02 May 2020 12:34:56 GMT&quot;,<br>      &quot;server&quot;: &quot;AmazonEC2&quot;<br>    },<br>    &quot;RetryAttempts&quot;: 0<br>  }<br>}</pre><p>Writing tests that cover parsing of dictionaries can be tempting — but chances are this is adding limited value. They mostly create noise and make it harder to focus on the important bits. Also, if boto ever changes the format of their response there’s nothing we can do about it in the first place — we’ll most likely end up adopting our code to their changes. So there’s no point in covering boto’s requests or responses in our tests!</p><p>I find a good pattern is isolating boto call <em>and</em> filtering operation to a single method:</p><pre>def _is_default_sg(self, sg_id):<br>    sec_groups = self.ec2_client.<strong>describe_security_groups</strong>(GroupIds=[sg_id])[&#39;SecurityGroups&#39;]<br>    return <strong>sec_groups[0][&#39;GroupName&#39;] == &#39;default</strong>&#39;</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/75ffaa03dabd1cbc0db9d569a27b902bb6146e3a/src/revokedefaultsg/app.py#L43"><em>source</em></a>]</pre><p>For unit tests, all that’s required is setting up the expectation for the <em>complete</em> method:</p><pre>obj.<strong>_is_default_sg</strong> = MagicMock(return_value=True)</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/91c94af83e89102edc76158cdbf2cbfdfbe7e2e3/tests/unit/test_revoke_default_sg.py#L60"><em>source</em></a>]</pre><p>That’s a single line of test code to set up even complex invocations — whilst being completely decoupled from the actual interaction with the framework.</p><p><strong>11. Don’t look too hard at the test coverage</strong></p><p>With pytest and pytest-cov, it’s very easy to measure test coverage — simply add some arguments to the pytestinvocation and produce a coverage report:</p><pre>pytest <strong>--cov=src --cov-branch --cov-report term-missing</strong></pre><pre>[...]</pre><pre>Name                              Stmts   Miss Branch BrPart  Cover   <br>--------------------------------------------------------------------<br>src/revokedefaultsg/app.py           59     11     12      1    83%   --------------------------------------------------------------------TOTAL                                59     11     12      1    83%</pre><p>While it does make sense to look at test coverage to identify untested code, don’t get too hung up the metric itself.</p><p>First of all, aiming for 100% — or near 100% — test coverage is not realistic; and closing the last 20% gap will cost a lot of extra effort. Second, it’s far more important to focus on the important bits and readability than on keeping test coverage above a certain threshold.</p><p>I remember writing tests for Java getters and setters only to keep the test coverage high and the numbers looking good on paper. What a waste of time and energy in hindsight.</p><p>Similarly, great test coverage doesn’t necessarily imply great tests. I’ve seen 90% coverage achieved by a single test case, comparing 1,000 lines of input with 10,000 lines of output. While the result looked impressive on paper, the failing test created a single assertion failure that’s 20,000 lines long. Impossible to understand without installing a whole range of diff tools on your computer.</p><p>My recommendation: Write tests around features, not around coverage.</p><p><strong>12. Consider giving test-driven development a try</strong></p><p>As a last tip, I want to ask you to look at <em>when</em> you are writing tests. Because implementing unit tests doesn’t have to be the last step in the process.</p><p>When thinking about a new feature, it’s perfectly feasible to write a new test case first, see it failing and then implement the code to make the test pass. When fixing a bug, why not starting with a test that surfaces the problem before fixing the code itself?</p><p>I can almost guarantee that your developer experience will be more rewarding and that oftentimes the quality of the outcome will be higher.</p><p>This is because tests allow you to change perspective: They put you in the shoes of the consumer and make you look at your code from a feature perspective.</p><p>Also, they give you the peace of mind that your code does what it’s supposed to do. This makes it much easier to continuously refactor to cater for new features — as opposed to ‘surgically inject’ more and more functionality into a code base that has become too complex to mess with.</p><p>And last but not least it’s pretty hard to make the same mistake twice if you already have a test case that proves the code is working.</p><h3>Resume</h3><p>Many of the tips and recommendation only scratch the surface of much deeper stories that go well beyond the scope of writing a single Lambda. If something has spawned your interest, I would like to encourage you to keep on reading about the topic. If I had to recommend a single book on writing better code, it would be “<a href="https://en.wikipedia.org/wiki/The_Pragmatic_Programmer">The Pragmatic Programmer</a>”, by Andrew Hunt and David Thomas.</p><p>In the article, I made the call to assume Python knowledge as a baseline and am not explaining any language features I’m using. This would have taken the focus away from the main topic and would have made it harder to follow along. However, I tried my best to make the code as readable as possible.</p><p>Also, a bit of a disclaimer about the example code I’m using: It’s a challenge to strike the balance between something simple enough to fit into the format of this article, but complex enough to illustrate problems well. If some recommendations seem like overkill for a Lambda with less than 100 lines of code, the picture looks completely different for bigger Lambdas in a more complex context.</p><p>And last but not least I want you to take away that one message behind all this: <em>Writing good code and good tests is a lot easier than people might think</em>.</p><p>Please leave a comment if you have a question or want to share your thoughts!</p><p>Happy Coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a74ca8bb0c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/no-time-for-tests-12-recommendations-on-unit-testing-aws-lambdas-in-python-6a74ca8bb0c1">No Time for Tests? — 12 Recommendations on Unit-Testing AWS Lambdas in Python</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[10 Recommendations for writing pragmatic AWS Lambdas in Python]]></title>
            <link>https://medium.com/swlh/10-recommendations-for-writing-pragmatic-aws-lambdas-in-python-5f4b038caafe?source=rss-f45ce30b5f86------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f4b038caafe</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Jan Groth]]></dc:creator>
            <pubDate>Sun, 31 May 2020 00:24:26 GMT</pubDate>
            <atom:updated>2020-08-19T23:28:38.734Z</atom:updated>
            <content:encoded><![CDATA[<h4>AWS Lambda — serverless — Python — DEVOPS</h4><h4>This article presents a collection of design patterns and best practices to implement AWS Lambdas in Python. It’s the first of two articles about writing and testing DevOps-y Lambdas.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLbOBybPtpC_eHTYkH231g.png" /></figure><p>Much like software applications, infrastructure provisioning has moved away from monolithic solutions, shifting focus towards decoupled components and utilisation of public service APIs. Tasks that traditionally would have required a great deal of orchestration and heavy tooling have transformed into lightweight event-driven services. Frameworks like the <a href="https://aws.amazon.com/serverless/sam/">AWS Serverless Application Model</a> (AWS SAM) have come a long way and make it easy to implement complex applications in a “microservice-style”, often with little more than a few Lambdas as building blocks.</p><p>In this series of two articles, I want to look at AWS Lambdas, written in Python, as the core elements of modern infrastructure stacks.</p><p>Taking a real-world application as an example, I will step through different aspects of source and test code and explain my approach and how it contributes to the overall goal: Implementing AWS Lambdas that are easy to understand, simple to monitor and fully unit-tested.</p><p>In this <strong>first article</strong>, I’ll introduce the example scenario and focus on the Lambda itself, looking at the source code and the patterns I used to increase <strong>readability</strong> and <strong>testability</strong>. Furthermore, I want to show how providing <strong>meaningful<em> </em>logging</strong> greatly reduces monitoring and debugging costs.</p><p>The <a href="https://medium.com/@jan.groth.de/no-time-for-tests-12-recommendations-on-unit-testing-aws-lambdas-in-python-6a74ca8bb0c1"><strong>second article</strong></a> will deep-dive into testing, explaining techniques to write <strong>effective unit-tests</strong> and demonstrate how they help <strong>reduce development efforts</strong>.</p><p>I have been a happy Java developer for many years, and most of the patterns that I’m using are well-known software development patterns — sometimes slightly adopted for cloud computing. If you have a developer background yourself, you’ve probably already seen many of them.</p><p>So what this article really is about: treating DevOps code like a software development project.</p><p>Before we start, let’s look at the example used throughout the article:</p><h3>A real-world example — restricting inbound and outbound traffic for default security groups</h3><figure><img alt="https://versent.com.au/" src="https://cdn-images-1.medium.com/max/348/0*qsxXe22AkaSE4sQX.png" /></figure><p>As a DevOps engineer at Versent, I’m helping clients with their cloud infrastructure. The example I picked for this article comes from a challenge we frequently face: making sure that AWS workloads comply with modern industry and security standards.</p><p>One aspect of this goal is setting guardrails for AWS resources so they don’t cause a security risk. This often requires deploying a sensible default configuration as well as putting controls in place that ensure that the system can’t drift at a later stage.</p><p>One approach to avoid drift is chaining reactive components to observe system events and take appropriate action if required:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CMsPE7HzjYoubi8N.png" /><figcaption>Observing system events with reactive components</figcaption></figure><p>This could, for example, be used to ensure that every new S3 has bucket logging enabled: On creation of a new bucket (create-bucket()API call in CloudTrail), an EventRule triggers a Lambda which programmatically enables bucket logging<em> </em>(put_bucket_logging() API call in boto).</p><p>For this article I’ve picked a slightly more complex scenario:</p><p><em>AWS VPCs are provisioned with </em><a href="https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#DefaultSecurityGroup"><em>default security groups</em></a><em> that allow all outbound and certain inbound traffic. While this is a good solution for AWS to get new users started quickly in their private accounts, it’s considered unsafe for production accounts and needs to be restricted to comply with the </em><a href="https://d1.awsstatic.com/whitepapers/compliance/AWS_CIS_Foundations_Benchmark.pdf"><em>AWS CIS Foundations Benchmark</em></a><em>.</em></p><p><em>As it’s not possible to delete default security groups all we can do is revoke egress and ingress on the existing groups. It’s not good enough to do this once, we also need to make sure that developers cannot simply re-open access at a later stage.</em></p><p>Following the layout suggested above, an implementation with AWS SAM can look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wR4cAWXSDu-HxU0C.png" /><figcaption>Automatically revoking ingress/egress for a security group</figcaption></figure><p><strong>(1)</strong> All API invocations are automatically logged to CloudTrail — per AWS account.<br><strong>(2)</strong> CloudTrail events are automatically forwarded to EventBridge.<br><strong>(3)</strong> An EventsRule listens to Ingress/Egress changes on security groups and triggers a Lambda.<br><strong>(4)</strong> The Lambda then revokes traffic rules if the security group is a default security group; to not drive developers insane over magically disappearing traffic rules it also adds a tag that explains what just happened.</p><p><strong>Example project</strong></p><figure><img alt="https://github.com/jangroth/writing-aws-lambdas-in-python" src="https://cdn-images-1.medium.com/max/1024/0*rPc_qmkjCs9g51VJ.png" /></figure><p>The complete working example can be found on GitHub:</p><p><a href="https://github.com/jangroth/writing-aws-lambdas-in-python">github.com/jangroth/writing-aws-lambdas-in-python</a></p><p>All source code examples are taken from there. You are welcome to follow along by setting up the project yourself.</p><h3>Making code readable and testable</h3><p>Imagine yourself on a support call in the middle of the night, staring at a piece of code that’s not doing what it’s supposed to be doing. On the other end of the call: The client, asking for updates every 30 seconds.</p><p>What’s more important at this moment: The fact that the code uses a semi-documented programming trick to squeeze out a marginal performance gain, or a slightly less performant version of the same code that you still understand at 2 a.m. in the morning?</p><blockquote><em>The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.</em></blockquote><blockquote>— Donald Knuth, author of “<a href="https://en.wikipedia.org/wiki/The_Art_of_Computer_Programming">The Art of Computer Programming</a>”</blockquote><p>As a universal rule of thumb: Write code that is as readable as possible, and only optimize for performance if you really have to.</p><p><strong>1. Linters are free as in beer</strong></p><p>A quick recommendation before we get started with code — integrating linters into your project doesn’t cost you more than a few lines in the makefile, but will almost certainly surface issues that you would have overlooked otherwise:</p><pre>check: <em>## Run linters<br>   </em><strong>flake8</strong><br>   <strong>yamllint</strong> -f parsable .<br>   <strong>cfn-lint</strong> -f parseable<br>   @echo &#39;*** all checks passing ***&#39;</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/Makefile#L24"><em>source</em></a>]</pre><p>Here, I use <a href="https://flake8.pycqa.org/en/latest/">flake8</a> for Python, <a href="https://yamllint.readthedocs.io/en/stable/">yamllint</a> for YAML and <a href="https://github.com/aws-cloudformation/cfn-python-lint">cfn-lint</a> for CloudFormation. This will provide good coverage for an AWS stack.</p><p>Now, let’s look at the actual Lambdas implementation:</p><p><strong>2. Separate the Lambda handler from the core logic</strong></p><p>This is also the first advice on <a href="https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html">Best Practices for Working with AWS Lambda Functions</a>: Logic in handlers can be difficult to follow and is extremely hard to test. I’ll talk about unit testing in the second article, but it’s the basic layout of the code that’s setting the scene for later testing.</p><p>This is a pattern that works well for me:</p><pre>class <strong>RevokeDefaultSg</strong>:<br> <br>   def <strong>process_event</strong>(self, event):<br>        # extract security group name from event<br>        # if security group is default security group:<br>        #   revoke ingress</pre><pre>def handler(event, context):<br>    return <strong>RevokeDefaultSg</strong>().<strong>process_event</strong>(event)</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L27"><em>source</em></a>]</pre><p>The core idea is to isolate the complete logic into a class, RevokeDefaultSg, with a single public entry point. This lays out the foundation for a top-down implementation approach, where process_event() contains the high-level logic and delegates work to private helper method.</p><p>An equally important aspect: Using a Python class for the logic creates an enclosure that makes it very easy to unit-test the Lambda. Actually, as we’ll see in the second article, <em>not using a class makes it much harder</em> to test the Lambda.</p><p><strong>3. Implement separate responsibilities in separate methods</strong></p><p>This is about readability as much as testability:</p><pre>class RevokeDefaultSg:    <br>   <br>   def <strong>_extract_sg_id</strong>(self, event):<br>        pass    <br>   <br>   def <strong>_is_default_sg</strong>(self, sg_id):<br>        pass    <br>   <br>   def <strong>_revoke_and_tag</strong>(self, sg_id):<br>        pass    <br>   <br>   def <strong>process_event</strong>(self, event):<br>        sg_id = self.<strong>_extract_sg_id</strong>(event)<br>        if self.<strong>_is_default_sg</strong>(sg_id):<br>            self.<strong>_revoke_and_tag</strong>(sg_id)<br>        return &#39;SUCCESS&#39;</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L27"><em>source</em></a>]</pre><p>All of the logic in process_event — the only public method and entry point — is delegated to helper methods. This makes the method itself extremely easy to understand and explains everything the Lambda does in just three lines of code. Ideally, process_event should tell the <em>whole</em> <em>story</em> of what the lambda does, without the need to look any further.</p><p><strong>4. Push external dependencies into small, low-level methods</strong></p><p>While it is possible to write unit tests for code that contains external dependencies, they still make testing life a little difficult.</p><p>In our example Lambda we need to tell whether a given security group id belongs to a default security group or not. This could be implemented as a straight boto call in process_event—but writing tests against 3rd party code at the entry-point level can quickly become painful. Also, checking for default security groups is a different task than processing the event itself and shouldn’t be part of the main method as per the previous section on separating responsibilities.</p><p>It’s much better for both testability and readability to extract the check into a separate method:</p><pre>def <strong>_is_default_sg</strong>(self, sg_id):<br>    sec_groups = self.<strong>ec2_client.describe_security_groups</strong>(...)<br>    return sec_groups[0][&quot;GroupName&quot;] == &quot;default&quot;</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L43"><em>source</em></a>]</pre><p><strong>5. Initialise external dependencies in the constructor if you can</strong></p><p>In the example above you’ve probably noticed that the boto client (ec2_client) is accessed through an instance attribute (<strong>self</strong>.ec2_client). This is only possible because the client — and all other dependencies — have already been initialised in the constructor:</p><pre>def <strong>__init__</strong>(self, region=&quot;ap-southeast-2&quot;):<br>    self.ec2_client = <strong>boto3.client</strong>(&quot;ec2&quot;, region_name=region)<br>    self.ec2_resource = <strong>boto3.resource</strong>(&quot;ec2&quot;, region_name=region)</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L28"><em>source</em></a>]</pre><p>Moving the creation and setup of external dependencies into the constructor has a few advantages:</p><ul><li>If there are any problems while creating dependencies, the code will fail immediately on object creation — this is much better than failing half-way through execution, potentially after data has already been manipulated.</li><li>Dependencies are often expensive to create. Sharing them across the code allows reuse, and constructors are a good location to keep them.</li><li><strong>Spoiler alert</strong><em>:</em> When unit-testing the Lambda we will create test objects without executing the constructor. Not having to deal with dependencies on object creation makes test setup much easier. This will be covered in the second article which focuses on testing aspects.</li></ul><h3>Making code easy to monitor and to debug</h3><p>Lambdas are tiny snippets of code that run independently in containers somewhere in the cloud. User interaction is not supported, and output typically only goes as far as CloudWatch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/0*Ieo_H1EB5Khg8pzD.png" /><figcaption>Decision tree for error handling</figcaption></figure><p>This removes all need to beautify output and translate error message into a user-friendly format. Logs in CloudWatch only have to be understandable to developers.</p><p>In many cases, it also removes the need to recover from erroneous situations. It’s much better to<em> fail hard and fast </em>— with trust in monitoring — than attempting to deal with a possible chain of problems at a rate of thousand invocations per second.</p><p><strong>6. Don’t handle errors just because you can</strong></p><p>Revisiting the example from above:</p><pre>def _is_default_sg(self, sg_id):<br>    sec_groups = self.<strong>ec2_client</strong>.describe_security_groups(...)[&#39;<strong>SecurityGroups</strong>&#39;]<br>    return sec_groups[0][&quot;<strong>GroupName</strong>&quot;] == &quot;default&quot;</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L43"><em>source</em></a>]</pre><p>There are many implicit assumptions in this code:</p><ul><li>ec2_client has been successfully created</li><li>describe_security_groups() returns a dict with the key &#39;SecurityGroups&#39;</li><li>This dict contains a list of dict with the key &#39;GroupName&#39; in it</li></ul><p>What are the options if any of these assumptions fail?</p><p>Not many, as another party <em>broke their contract</em> with us. Maybe boto has changed the semantics of the API call, or the AWS ec2 service itself now returns different results. It’s impossible to know what has gone wrong and why, and certainly there’s no reasonable way to recover from it. All we can do is fail and investigate the logs at a later stage. Most likely code will have to be changed to fix the problem.</p><p>It might look tempting to still wrap the code with try...except, just in case. But often this is adding more noise than providing benefits, as the standard Python stack trace should already contain the information required to start the investigation.</p><p><strong>7. Use custom exceptions for flow-specific errors</strong></p><p>Sometimes it is good to communicate a certain error explicitly.</p><p>For example, a Lambda function can be part of a greater piece of orchestration and be invoked from different sources. In this case, it’s useful to validate the incoming event as a precondition to our logic and to fail with a clear error message if something is unexpected.</p><p>Custom exceptions only take up two lines and are a great way to communicate individual errors:</p><pre>class <strong>UnknownEventException</strong>(Exception):<br>    pass</pre><pre>[...]</pre><pre>def _extract_sg_id(self, event):<br>    is_correct_event_source = ...<br>    is_correct_event_type = ...<br>    event_sg_id = ...</pre><pre>    if not (is_correct_event_source and is_correct_event_type and event_sg_id):<br>        <strong>raise UnknownEventException(f&quot;Cannot handle event: {event}&quot;)</strong><br>    return event_sg_id</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L34"><em>source</em></a>]</pre><p>This sends a clear message to CloudWatch and makes it easy to understand the problem.</p><p><strong>8. Use a logger and pick the right logging level</strong></p><p>All Lambda output ends up in CloudWatch — which makes it the central source for debugging and a general understanding of what’s going on. Not having enough information here can be problematic if something goes wrong. On the other hand, too much output makes it hard to see the forest for the trees.</p><p>printstatements are easy to use and don’t require any imports or configuration. While this might already sound sufficient, loggersgo a lot further: They add contextual information allow to bind the output to a logging level. This lets us control the amount of logging in relation to e.g. the environment the Lambda runs in.</p><p>When writing output under a certain logging level, it’s essential to use the different levels consistently. Otherwise, logging benefit gets watered-down and supporting services like CloudWatch Alarms are far less useful. The following convention has established as de-facto standard:</p><p><strong>error</strong> — something has gone seriously wrong. A developer (<em>you!</em>) needs to look at this, code will likely have to change. Raise an incident if this happens on a production system. Only use this level if you are ready to be woken up in the middle of the night about this.</p><p><strong>warning</strong> — something is unexpected, but we are still cool. E.g. a configuration value should have been there but wasn’t found. So we continue with a default value and log a warning. Someone should investigate.</p><p><strong>info</strong> — the normal level. Someone looking at the info-level output of a Lambda should easily understand what happened. It’s important to strike the balance between <em>too much</em> and <em>not enough.</em> Creating an if branch just to add a logging statement is acceptable if it makes the flow easier to follow:</p><pre>if self._is_default_sg(sg_id):<br>    self.logger.info(f&quot;Revoking ingress/egress [...]&quot;)<br>    self._revoke_and_tag(sg_id)<br><strong>else:<br>    self.logger.info(&quot;[...] nothing to do.&quot;)</strong></pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L77"><em>source</em></a>]</pre><p><strong>debug </strong>— fine-grained output that helps you develop the code and makes it possible to understand what’s going on a low level. Too noisy for info level. In this example there’s additional information about the exact action that was taken, adding to the general information already provided at info level:</p><pre>if security_group.ip_permissions:<br>    security_group.revoke_ingress(...)<br>    should_tag = True<br>    <strong>self.logger.debug(&quot;Revoking ingress rules&quot;)</strong><br>if security_group.ip_permissions_egress:<br>    should_tag = True  security_group.revoke_egress(...)<br>    <strong>self.logger.debug(&quot;Revoking egress rules&quot;)</strong><br>if should_tag:<br>    security_group.create_tags(...)<br>    <strong>self.logger.debug(&quot;Adding tag.&quot;)</strong><br>else:<br>    <strong>self.logger.debug(&quot;No ingress/egress rules found to revoke&quot;)</strong></pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L52"><em>source</em></a>]</pre><p><strong>9. Configure the minimum log level via CloudFormation</strong></p><p>Now, how can deploys to “prod” have a different minimum log level than deploys to “test”?</p><p>It’s a good practice to separate <em>configuration </em>— everything that is likely to vary between deployments — from the <em>application</em> and to store it in the environment.</p><p>For the Lambda, let’s bring the configuration up to CloudFormation parameter level, so that different stacks can be deployed with different settings:</p><pre>Parameters:<br>  <strong>minimumLogLevel</strong>:<br>    Type: String<br>    Default: DEBUG<br>...<br>Resources:<br>...<br>  RevokeDefaultSgLambda:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      CodeUri: ./src<br>      Handler: revokedefaultsg.app.handler<br>      Runtime: python3.7<br>      Role: !GetAtt RevokeDefaultSgLambdaRole.Arn<br>      Timeout: 900<br>      Environment:<br>        Variables:<br>          LOGGING: !Ref <strong>minimumLogLevel</strong></pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/default-sg-remediation.sam.yaml#L8"><em>source</em></a>]</pre><p>All that’s left for the Lambda is reading out the environment variable:</p><pre>class RevokeDefaultSg:</pre><pre>    def __init__(self):<br>        self.logger = logging.getLogger(self.__class__.__name__)<br><strong>        self.logger.setLevel(os.environ[&quot;LOGGING&quot;])</strong></pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L27"><em>source</em></a>]</pre><p>For further reading I recommend “<a href="https://12factor.net/config">The Twelve-Factor App</a>”: <em>Store config in the environment</em>; one of the factors of the twelve-factor methodology for building software-as-a-service applications.</p><p><strong>10. Decorators are an elegant way to log Lambda context</strong></p><p>Did you ever find yourself implementing the same statements for lambda invocation logging again and again? This is where Python decorators shine:</p><p>Simply define a decorator function somewhere in the Lambda code (or even better: in a <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">Lambda layer</a>):</p><pre>def <strong>notify_cloudwatch</strong>(function):<br>    @wraps(function)<br>    def wrapper(event, context):<br>        <strong>logger.info(f&quot;&#39;{context.function_name}&#39; - entry:&#39;{event}&#39;&quot;)</strong><br>        result = function(event, context)<br>        <strong>logger.info(f&quot;&#39;{context.function_name}&#39; - entry.&#39;{result}&#39;&quot;)</strong><br>        return result</pre><pre>    return wrapper</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L12"><em>source</em></a>]</pre><p>And annotate the handler functions:</p><pre><strong>@notify_cloudwatch</strong><br>def handler(event, context):<br>    return RevokeDefaultSg().process_event(event)</pre><pre>[→ <a href="https://github.com/jangroth/writing-aws-lambdas-in-python/blob/3db84f028381724eb37c5538c480733a7f62aea3/src/revokedefaultsg/app.py#L85"><em>source</em></a>]</pre><p>This is getting even more useful when using <a href="https://aws.amazon.com/step-functions/">AWS Step Functions</a> — where multiple Lambdas are often combined into one source file with multiple handler methods.</p><p>Also, this technique can easily be extended to serve different channels:</p><pre>@notify_cloudwatch<br><strong>@notify_slack<br></strong>def handler(event, context):<br>    return RevokeDefaultSg().process_event(event)</pre><h3>The End (for now)</h3><p>There’s surely much more out there to be considered, but from my experience, these 10 recommendations are a good baseline for implementing code that’s readable, maintainable and testable.</p><p>Some suggestions, like initialising external dependencies in constructors and pushing their usage out into small methods, might still seem a little strange — hopefully, this will change when we start looking at unit-testing the Lambda:</p><p><a href="https://medium.com/@jan.groth.de/no-time-for-tests-12-recommendations-on-unit-testing-aws-lambdas-in-python-6a74ca8bb0c1"><strong>No time for tests? — 12 Recommendations on unit-testing AWS Lambdas in Python</strong></a></p><p>In the meantime, please leave a comment if you have questions or want to share your thoughts.</p><p>Happy Coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f4b038caafe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/10-recommendations-for-writing-pragmatic-aws-lambdas-in-python-5f4b038caafe">10 Recommendations for writing pragmatic AWS Lambdas in Python</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>