<?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[Edrolo Engineering - Medium]]></title>
        <description><![CDATA[Notes from the Edrolo Web Development Team - Medium]]></description>
        <link>https://medium.com/edrolo-engineering?source=rss----395bea6c2ddb---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Edrolo Engineering - Medium</title>
            <link>https://medium.com/edrolo-engineering?source=rss----395bea6c2ddb---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:31:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/edrolo-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Writing Filters for the  AWS EC2 CLI]]></title>
            <link>https://medium.com/edrolo-engineering/writing-filters-for-the-aws-ec2-cli-a985c29b9267?source=rss----395bea6c2ddb---4</link>
            <guid isPermaLink="false">https://medium.com/p/a985c29b9267</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[aws-cli]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Kai Hirsinger]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 01:52:29 GMT</pubDate>
            <atom:updated>2020-06-02T01:49:53.252Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing Filters for the AWS EC2 CLI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*VFoMVBYQRXeytQqBfaudzg.jpeg" /></figure><p>I recently wrote a bash script that needed access to an EC2 host with a specific name. To do this I used the describe-instances command offered by the AWS CLI.</p><pre>$&gt; aws ec2 describe-instances</pre><p>Running this command returns a JSON blob describing all the EC2 instances setup in your AWS account. One (perfectly legitimate) way of dealing with this would be to pipe the results into a JSON parsing tool like <a href="https://stedolan.github.io/jq/">jq</a> and work out a suitable query for extracting the required instance. However I was curious about the <a href="https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options">filters</a> option that the was made available by the describe-instances command. This appears to enable some kind of filtering to take place on the server side, which would mean less data sent over the wire, a faster script, and a happier experience for the end user.</p><p>This post is a summary of some practical lessons I learned while using this option.</p><h3>A Filter is Either a String or a JSON Object</h3><p>Filters specified as a string have the general form.</p><pre>&quot;Name=ec2-property,Values=ec2-property-value&quot;</pre><p>Where ec2-property is one of the properties listed on <a href="https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options">this page,</a> and ec2-property-value is the value that will filtered from that property.</p><p>Filters can also be specified as a literal JSON object.</p><pre>&quot;[{\&quot;Name\&quot;: \&quot;ec2-property\&quot;,\&quot;Values\&quot;: [\&quot;ec2-property-value\&quot;]}]&quot;</pre><p>Either of these values can be passed directly to the filters option, and used to obtain a set of instances. For example this command will retrieve all the running instances from an AWS account.</p><pre>$&gt; aws ec2 describe-instances --filters &quot;Name=instance-state-name,Values=running&quot;</pre><p>This obtains the same result, but uses a JSON filter.</p><pre>$&gt; aws ec2 describe-instances --filters &quot;\<br>[<br>    {<br>        \&quot;Name\&quot;: \&quot;instance-state-name\&quot;,<br>        \&quot;Values\&quot;: [\&quot;running\&quot;]<br>    }<br>]&quot;</pre><h3>Multiple Values in a Single Filter are Combined Using a Boolean OR</h3><p>If multiple values are used in a filter term, each term is OR’d together to produce the final result. To demonstrate this, the example above can be expanded to retrieve all instances that are running or stopped.</p><pre>$&gt; aws ec2 describe-instances --filters &quot;Name=instance-state-name,Values=running,stopped&quot;</pre><p>The equivalent filter specified as a JSON object looks a little different, but returns the same result.</p><pre>$&gt; aws ec2 describe-instances --filters &quot;\<br>[<br>    {<br>        \&quot;Name\&quot;: \&quot;instance-state-name\&quot;,<br>        \&quot;Values\&quot;: [\&quot;running\&quot;, \&quot;stopped\&quot;]<br>    }<br>]&quot;</pre><h3>Multiple Filters are Combined Using a Boolean AND</h3><p>Where multiple filters are specified, each filter is AND’d together to produce the final result.</p><p>Let’s expand our example again to include instances that are running or stopped, <em>and</em> which exist in a specific VPC (note I’ve introduced line continuation markers here using the \ character to make the commands more legible).</p><p><strong>String</strong></p><pre>$&gt; aws ec2 describe-instances --filters \<br>&quot;Name=instance-state-name,Values=running,stopped&quot; \<br>&quot;Name=vpc-id,Values=XXX&quot;</pre><p><strong>JSON</strong></p><pre>$&gt; aws ec2 describe-instances --filters &quot;\<br>[<br>    {<br>        \&quot;Name\&quot;: \&quot;instance-state-name\&quot;,<br>        \&quot;Values\&quot;: [\&quot;running\&quot;, \&quot;stopped\&quot;]<br>    },   <br>    {<br>        \&quot;Name\&quot;: \&quot;vpc-id\&quot;,<br>        \&quot;Values\&quot;: [\&quot;XXX\&quot;]<br>    }<br>]&quot;</pre><h3>Filtering on Instance Tags is a Bit Special</h3><p>Writing a filter on an instance tag is a special case that isn’t very well documented. In general, the property name (tag) and the tag name are both specified in the Name part of the filter. The : character is used to separate the property name from the tag name. The value is specified in the Values part of the filter, which is no different from any other property.</p><p>For example:</p><p><strong>String</strong></p><pre>&quot;Name=tag:tagName,Values=tagValue&quot;</pre><p><strong>JSON</strong></p><pre>[{&quot;Name&quot;: &quot;tag:Name&quot;, &quot;Values&quot;: [&quot;definitely-not-a-crypto-miner&quot;]}]</pre><p>Putting this into practice, let’s expand our example once again to include all instances that are running or stopped from a specific VPC that have the name definitely-not-a-crypto-miner.</p><p><strong>String</strong></p><pre>$&gt; aws ec2 describe-instances --filters \<br>&quot;Name=instance-state-name,Values=running,stopped&quot; \<br>&quot;Name=vpc-id,Values=XXX&quot; \<br>&quot;Name=tag:Name,Values=definitely-not-a-crypto-miner&quot;</pre><p><strong>JSON</strong></p><pre>[<br>    {<br>        &quot;Name&quot;: &quot;instance-state-name&quot;,<br>        &quot;Values&quot;: [&quot;running&quot;, &quot;stopped&quot;]<br>    },<br>    {<br>        \&quot;Name\&quot;: \&quot;vpc-id\&quot;,<br>        \&quot;Values\&quot;: [\&quot;XXX\&quot;]<br>    },<br>    {<br>        &quot;Name&quot;: &quot;tag:Name&quot;,<br>        &quot;Values&quot;: [&quot;definitely-not-a-crypto-miner&quot;]<br>    }<br>]</pre><h3>JSON Filters Can be Stored in a File</h3><p>Complex filters can be easier to deal with if they’re isolated from the rest of your code. This is made possible by passing a JSON file as an argument to the filters option instead of explicitly specifying the JSON on the command line.</p><pre>$&gt; aws ec2 describe-instances --filters file://my_filter.json</pre><p>Where my_filter.json is a JSON file containing the filter from the previous example.</p><pre>$&gt; cat my_filter.json<br>[<br>    {<br>        &quot;Name&quot;: &quot;instance-state-name&quot;,<br>        &quot;Values&quot;: [&quot;running&quot;, &quot;stopped&quot;]<br>    },<br>    {<br>        \&quot;Name\&quot;: \&quot;vpc-id\&quot;,<br>        \&quot;Values\&quot;: [\&quot;XXX\&quot;]<br>    },<br>    {<br>        &quot;Name&quot;: &quot;tag:Name&quot;,<br>        &quot;Values&quot;: [&quot;definitely-not-a-crypto-miner&quot;]<br>    }<br>]</pre><p>Note the file:// prefix, which seems to be necessary if the command is going to parse the file as a file, rather than attempt to ingest the literal contents of the command line.</p><h3>You Can Use the Query Option to Parse the JSON Returned by the Command</h3><p>Something I didn’t look at in too much detail was the query option, which lets you further narrow the result set using the <a href="https://jmespath.org/">JMESPath</a> query language. I had no use for this, but it’s definitely something that might be useful if you’re dealing with a very large result set.</p><p>Alternatively you can fall back on our old friend <a href="https://stedolan.github.io/jq/">jq</a> at this point, which also lets you query the result (and has a really nice pretty-printer).</p><h3>That’s It!</h3><p>Hope you found some of the above useful, and thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a985c29b9267" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edrolo-engineering/writing-filters-for-the-aws-ec2-cli-a985c29b9267">Writing Filters for the  AWS EC2 CLI</a> was originally published in <a href="https://medium.com/edrolo-engineering">Edrolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous Integration with Buildkite]]></title>
            <link>https://medium.com/edrolo-engineering/continuous-integration-with-buildkite-8e282d15b5a1?source=rss----395bea6c2ddb---4</link>
            <guid isPermaLink="false">https://medium.com/p/8e282d15b5a1</guid>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[buildkite]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Danny Shaw]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 23:56:21 GMT</pubDate>
            <atom:updated>2020-01-07T00:09:44.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eO1-AHsR9yj0B0XSEysdxw.png" /></figure><p>Maintaining a large code base with a small development team requires diligence, discipline and - most importantly - a well oiled testing pipeline. Here I’ll speak a little about that last one, that is, how we do Continuous Integration at Edrolo.</p><p>The basic idea of Continuous Integration is to run an extensive set of tests on each change as developers go about adding or editing features, by having them run every literally time code changes. This way errors will be exposed very soon after they are introduced in the development process, and you’re more likely to know exactly what change has introduced the bug. It’s also important that the process happens as seamlessly as possible so that developers are not hindered or slowed down in their work.</p><p>Contrast this with older techniques of long running development branches that have large changes in them, and are only subject to perhaps longer winded integration testing at the <em>end</em> of development. This makes tracking down the source of errors exponentially harder, with more debugging required, and the integration of the new feature a far more painful process.</p><p>Here I will outline at a relatively high level the approach we take at Edrolo to test our code. A future post may go into detail about various aspects. If you’re interested in something particular, please feel free to leave a comment below.</p><h4>A quick summary of our world for context</h4><p><strong>Python/Django backend</strong></p><ul><li>Unit/Integration tested with <a href="https://docs.djangoproject.com/en/2.2/topics/testing/">Django Testing</a></li><li>Dependencies checked with <a href="https://github.com/pyupio/safety">Safety</a></li><li>Code formatting enforced with <a href="https://github.com/google/yapf">YAPF</a></li></ul><p><strong>Javascript/React frontend</strong></p><ul><li>Transpiled with <a href="https://babeljs.io/">Babel</a></li><li>Bundled with <a href="https://webpack.js.org/">Webpack</a></li><li>Unit tested with <a href="https://jestjs.io/">Jest</a></li><li>Code formatting enforced with <a href="https://prettier.io/">Prettier</a></li><li>Linted with <a href="https://eslint.org/">ESlint</a></li></ul><p><strong>AWS Infrastructure</strong></p><ul><li>CloudFormation linting with <a href="https://github.com/aws-cloudformation/cfn-python-lint">cfn-lint</a></li></ul><p><strong>Integration</strong></p><ul><li>End To End tested with <a href="https://cypress.io/">Cypress</a></li></ul><p><strong>Source Control</strong></p><ul><li>Maintained with <a href="https://git-scm.com/">Git</a></li><li>Hosted by <a href="https://github.com/">GitHub</a></li><li>master branch configured to require Pull Requests to alter code</li><li>Pull Requests require multiple developer approvals and tests to pass before merging.</li></ul><h3>Buildkite: The glue that holds it all together</h3><p>There are a lot of tools in that list. Ideally, if we want to keep code at a nice high quality, we’d run those that check and assert that both the application’s behaviour and the quality of the code is as we’d expect — every time code is changed.</p><p>To perform this task, we utilise a service called <a href="https://buildkite.com/">Buildkite</a>. Buildkite is an incredibly elegant piece of sticky tape that sits between your code repository, and machines you dedicate to testing and or deploying that code.</p><blockquote>“Buildkite is basically Bash-as-a-service”</blockquote><blockquote>- Anonymous Overheard</blockquote><p>Buildkite will monitor our GitHub repository, creating a new build for each commit on every branch (configurable). A build in our case is a single pipeline of steps that either prepare or test the code at that commit in various ways. Ultimately this results in a Pass or Fail which is reported back to GitHub&#39;s Checks API, and either permits or blocks merging on Pull Requests depending on if checks pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*sDMb_2WoA00sha-VQ_bdvQ.png" /><figcaption>A Pull Request with a successful CI Build</figcaption></figure><h4>Buildkite Basics</h4><p>Buildkite runs its jobs on your infrastructure by providing an agent binary which, when installed and running with your key will report itself to their platform as ready to accept any jobs that are scheduled. This can be as complex and scalable, or as small and simple as you need. You could run a single agent on a raspberry pi on premises if you wanted.</p><p>The configuration you choose will depend on how many developers you have or how elaborate your testing suite is. One agent instance can run one pipeline job at a time, so you can configure powerful machines to run many instances or many small machines to run several instances. Everything depends on the specifics of your use case and budget.</p><p>That all said, Buildkite offers a turnkey AWS elastic stack with plenty of configurable options (and sensible defaults) that will spin up an auto-scaling group of EC2 instances to provide a scalable solution to running as many builds as you need. We use this, and other than some tweaks on instance size and Spot Pricing, we’ve found it perfect out of the box.</p><h4>Pipeline Builds</h4><p>The first thing a build does is grabs an entire copy of your repository at a particular commit. Once downloaded a pipeline is executed. A pipeline can either be defined in the Buildkite platform, or as a yaml file in your code base. The latter is preferred so that changes are tracked.</p><p>Pipelines can do many things, but essentially they execute a series of commands or scripts stored in your repo which will either pass or fail. Pipelines have a rich plugin system available which enables tools such as <a href="https://github.com/buildkite-plugins/docker-buildkite-plugin">Docker</a> and <a href="https://github.com/buildkite-plugins/docker-compose-buildkite-plugin">docker-compose</a> to be utilised to set up test environments on the agent machine. This avoids the need to install and maintain dependencies. I will not go into the specifics of Docker here, but we do use it to run all of our steps so that dependencies can be provisioned at run time.</p><p>Pipeline steps can upload artifacts. These can be simply logs of the run, or screenshots, but could also be compiled code or other assets that may be required in later steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laFBqmg-fEhm-I-NHCxNMw.png" /><figcaption>Shell output is piped through to the Buildkite UI</figcaption></figure><h4>Our Pipeline</h4><p>Here is the outline of our CI pipeline. Where you see the word `wait` it means everything grouped before it is happening in parallel and “wait” will wait for them all to pass before moving onto the next step.</p><ul><li>Build Docker Images</li><li>wait</li><li>Compile frontend code with webpack and upload the built bundle and assets as artifacts</li><li>Run eslint to check code style</li><li>Run prettier in check mode to assert it is formatted as it should be</li><li>Run our suite of frontend unit tests with jest</li><li>Run cfn-lintover our CloudFormation stack files</li><li>Run safetyover our python dependencies</li><li>Run yapfin check mode to assert formatting</li><li>wait</li><li>Run our Django unit/integration tests (downloading and mounting the webpack assets first)</li><li>Run our cypressEnd to End tests (downloading and mounting the webpack assets first)</li></ul><p>Each step above is run in either a NodeJS docker container or a Python docker container prepared with all the dependencies required.</p><p>Logfiles, Screenshots and even videos of the End to End tests running are all uploaded as artifacts and available to help with debugging any errors that arise.</p><h4>Our Actual Pipeline</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db51e619ff97418401fc629cd8f2fcc3/href">https://medium.com/media/db51e619ff97418401fc629cd8f2fcc3/href</a></iframe><p>And here’s an example of the script to run ESLint</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d16de9f3045d3c635905915be4805d08/href">https://medium.com/media/d16de9f3045d3c635905915be4805d08/href</a></iframe><p>Basically just locating files in the docker volume and executing a command.</p><h4>Tips for pipelines</h4><ul><li>Each bash script that runs a step should include `set -euo pipefail` at the top so that any error will fail the build.</li><li>You don’t have to use bash, you can script things in whatever you want. Python could be a good choice.</li><li>A Docker environment makes things more flexible and maintainable. The isolation and deterministic nature makes things easy to think about and extra dependencies easy to install (once you learn the docker dance).</li><li>Use the out of the box <a href="https://buildkite.com/docs/tutorials/elastic-ci-stack-aws">Elastic CI Stack for AWS</a> (if you’re on AWS) and don’t fiddle with much until you have a real need.</li><li>Use Artifacts to store assets that other steps might need.</li></ul><h3>Conclusion</h3><p>A healthy set of tests to run, combined with a platform like Buildkite to orchestrate builds and feed back to Pull Requests in GitHub makes for a tight integration process. Once up and running, adding more tests just makes your system more and more robust.</p><p>Go forth and test!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e282d15b5a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edrolo-engineering/continuous-integration-with-buildkite-8e282d15b5a1">Continuous Integration with Buildkite</a> was originally published in <a href="https://medium.com/edrolo-engineering">Edrolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interpreting Exit Codes in Shell Scripts]]></title>
            <link>https://medium.com/edrolo-engineering/interpreting-exit-codes-in-shell-scripts-9ffbad70a78d?source=rss----395bea6c2ddb---4</link>
            <guid isPermaLink="false">https://medium.com/p/9ffbad70a78d</guid>
            <category><![CDATA[bitmask]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[shell-script]]></category>
            <category><![CDATA[linter]]></category>
            <dc:creator><![CDATA[Matt Fisher]]></dc:creator>
            <pubDate>Wed, 04 Dec 2019 02:06:20 GMT</pubDate>
            <atom:updated>2019-12-04T02:06:20.345Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A car dashboard speedometer showing the check engine warning light" src="https://cdn-images-1.medium.com/max/1000/1*wWy3CrrKjVbjwQBRWhaDQg.jpeg" /></figure><h4>When failure isn’t really failure</h4><p>At Edrolo, we maintain a continuous integration pipeline that uses command-line tools and shell scripts to run a number of pre-deployment checks on our code, like <a href="https://prettier.io/">Prettier</a> and <a href="https://github.com/google/yapf">YAPF</a>.</p><p>Recently, we wanted to add a step to <a href="https://en.wikipedia.org/wiki/Lint_(software)">lint</a> our <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-reference.html">CloudFormation templates</a>. We&#39;d had a couple of instances where typos in strings made it through code review and caused some confusing deployment failures. We found AWS Labs’ tool <a href="https://github.com/aws-cloudformation/cfn-python-lint">cfn-lint</a>, which was exactly what we were after.</p><p>So we can just add cfn-lint &quot;cloudformation/*.cfn.yml&quot; as a pipeline step and we&#39;re done! Right? Almost.</p><h4>Identifying Failure</h4><p>Steps in a CI pipeline need to make the pipeline fail if there are errors present. In a POSIX shell like bash, this is communicated by an <a href="https://en.wikipedia.org/wiki/Exit_status#POSIX">exit status</a>, which is zero if a process completed successfully, and some other integer value if there were problems. The exit status from the last executed command is stored in <a href="https://www.tldp.org/LDP/abs/html/internalvariables.html#XSTATVARREF">the </a><a href="https://www.tldp.org/LDP/abs/html/internalvariables.html#XSTATVARREF">$? variable</a>.</p><pre>$ echo &quot;Hello World!&quot;<br>Hello World<br>$ echo $?<br>0<br>$ wot<br>bash: wot: command not found<br>$ echo $?<br>127</pre><p>CI pipelines like <a href="https://buildkite.com/">Buildkite</a> interpret a non-zero exit status as a failure, and will halt the pipeline. However, cfn-lint is more granular than pass/fail - it reports whether there are errors, warnings, or informational messages by returning different exit statuses. In our case, we wanted to halt the pipeline if there were errors, but not if there were warnings. This would allow us to get the CI step in place and working before we had to fix all the warnings it would inevitably find in our templates.</p><h4>Capturing the exit status</h4><p>To achieve this, we had to capture the exit status from cfn-lint inside a wrapper script. That script can then report success in the presence of warnings.</p><p>First, we create a file named cfn-lint.sh and set up the shell environment to be <a href="https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/">a bit safer</a>.</p><pre>#!/bin/bash<br>set -uxo pipefail</pre><p>Setting -x causes bash to print each command before executing it, which is a <em>huge</em> help for debugging and particularly when you&#39;re playing with exit statuses, because even the echo command resets the $? variable.</p><p>Then we show a useful message with a pretty emoji, run the command and capture the exit status:</p><pre>echo &quot;--- :cloudformation: Linting CloudFormation templates&quot;</pre><pre>cfn-lint &quot;/app/cloudformation/*.cfn.yml&quot;; exit_status=$?</pre><p>Recording the exit status itself was a bit of a gotcha — the exit_status=$? was originally further down the script, and it was actually picking up the exit status from a variable assignment command, so it was always zero! It&#39;s now on the same line so that even if someone later inserts an echo on the next line for debugging, it won&#39;t change what&#39;s captured in exit_status.</p><h4>Interpreting the exit status</h4><p>Now we need to actually figure out what it means. Looking at the <a href="https://github.com/aws-cloudformation/cfn-python-lint/blob/ecc17535a2ecadf4c2a7830158936f1e4497f42f/src/cfnlint/core.py#L48">cfn-lint source code</a>, we can see that it’s using a <a href="https://en.wikipedia.org/wiki/Bit_field">bit field</a> to communicate the presence of info messages, warnings, and errors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/263fde5db0ed04ee1d7adaa1ea760364/href">https://medium.com/media/263fde5db0ed04ee1d7adaa1ea760364/href</a></iframe><p>To produce the exit status, this function ORs together 8, 4, and 2 as needed to indicate the presence of the different kinds of messages.</p><pre>╔═════════╦═════════╦════════╗<br>║  Level  ║ Decimal ║ Binary ║<br>╠═════════╬═════════╬════════╣<br>║  Info   ║    8    ║  1000  ║<br>║  Warn   ║    4    ║  0100  ║<br>║  Error  ║    2    ║  0010  ║<br>║  None   ║    0    ║  0000  ║<br>╚═════════╩═════════╩════════╝</pre><p>So if there are no messages at all, the exit status will be zero. If there are just info messages, the exit status will be 8. If there are warnings <em>and</em> errors, we&#39;ll get an exit status of 4 + 2 = 6 (in decimal), or 0100 | 0010 = 0110 (in binary). Info + warnings = 8 + 4 = 12, or 1000 | 0100 = 1100, and so on.</p><p>For the consuming script to interpret the exit status, we need to use the bitwise AND operator &amp;, and the same <a href="https://en.wikipedia.org/wiki/Mask_%28computing%29">bitmasks</a> to check for the different levels. It would also be possible to do it with integer arithmetic, but that&#39;s much less elegant.</p><pre>ERROR_MASK=2<br>WARNING_MASK=4<br>INFO_ERROR_MASK=8<br><br>if [ $(( exit_status &amp; ERROR_MASK )) -gt 0 ]<br>then<br>  echo &quot;Errors!&quot; &gt;&amp;2<br>  # Fail on errors<br>  exit 1<br>elif [ $(( exit_status &amp; WARNING_MASK )) -gt 0 ]<br>then<br>  echo &quot;Warnings!&quot; &gt;&amp;2<br>  # Don&#39;t fail on warnings<br>  exit 0<br>elif [ $(( exit_status &amp; INFO_ERROR_MASK )) -gt 0 ]<br>then<br>  echo &quot;Info&quot; &gt;&amp;2<br>  # Don&#39;t fail on info<br>  exit 0<br>else<br>  exit 0<br>fi</pre><p>If the exit status from cfn-lint indicates there are errors, we use &gt;&amp;2 to echo a message to stderr and exit with a final status of 1, indicating failure.<br><br>If there are warnings or info messages, we still echo a message to stderr but exit with a status of 0, indicating success!</p><h4>Wrapping up</h4><p>All that’s left to do is tell our CI pipeline to run our new cfn-lint.sh as a step, and we’ve eliminated one more way our deployments can fail.<br><br>The final shell script is below. It’s a personal choice whether to remove the -x setting — you’ll get quieter logs but lose visibility of what’s actually being run.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2a57e72581987ad090fee2ed0458909/href">https://medium.com/media/a2a57e72581987ad090fee2ed0458909/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ffbad70a78d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edrolo-engineering/interpreting-exit-codes-in-shell-scripts-9ffbad70a78d">Interpreting Exit Codes in Shell Scripts</a> was originally published in <a href="https://medium.com/edrolo-engineering">Edrolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[View Based Permissions in Django]]></title>
            <link>https://medium.com/edrolo-engineering/view-based-permissions-in-django-acb725f31e8f?source=rss----395bea6c2ddb---4</link>
            <guid isPermaLink="false">https://medium.com/p/acb725f31e8f</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kai Hirsinger]]></dc:creator>
            <pubDate>Thu, 14 Nov 2019 00:20:31 GMT</pubDate>
            <atom:updated>2019-11-14T00:23:33.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="keys" src="https://cdn-images-1.medium.com/max/640/1*qea_4cBd2vxAEJ0hHaUIdw.jpeg" /></figure><p>This post explains (using a very simple example) how we implemented a view-based permissions system using Django and Django REST Framework, and attempts to justify why we chose to do such a thing.</p><p>It can be read end-to-end for a re-cap of Django’s existing permissions system and the motivation for moving to a view-based permissions system. Alternatively the “View Based Permissions” section can be read in isolation for the implementation details.</p><h3>Model Based Permissions</h3><p>Django implements a form of the <a href="https://en.wikipedia.org/wiki/Role-based_access_control">role based access control architecture</a> where:</p><ul><li>A “role” is known as a “group”.</li><li>Both “permissions” and “users” are assigned to groups.</li><li>The permissions held by a user are determined by the group they are a part of ¹.</li><li>Permissions are associated with primitive create, read, update and delete operations on models. That is, when a new model is created, four permissions are automatically defined for creating, reading, updating and deleting instances of that model.</li></ul><p>As an example consider an application for making and selling sausages: sausage_factory. This application defines four models: Sausage, Casing, Filling and SausageSale.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f1b63274c5b10cdb1f4ed290f2fe8e1/href">https://medium.com/media/8f1b63274c5b10cdb1f4ed290f2fe8e1/href</a></iframe><p>Migrating the database will produce a set of sixteen permissions: four for each model. These can be accessed from the Django admin page, or by querying the Permission model in an interactive shell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70e0157e229cad7df07be114cf7f09f4/href">https://medium.com/media/70e0157e229cad7df07be114cf7f09f4/href</a></iframe><p>( As a side note, there will be other permissions after running the statements above, for brevity only those relating to the models defined earlier have been shown )</p><h3>Where This Approach Breaks Down</h3><p>As applications (and businesses) grow larger, user interactions may involve complex operations on multiple models. For example suppose the views in the sausage selling application were defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05c18c76bc7e66fec4555e4d9a4ac178/href">https://medium.com/media/05c18c76bc7e66fec4555e4d9a4ac178/href</a></iframe><p>In this example each view calls a helper function that implements a set of business rules (in this case for making or selling a sausage).</p><p>For the sake of the example, assume that each service implements some kind of complex business logic. Specifically let’s say that the make_sausage service will attempt to make a sausage with the specified name, out of the specified materials. It may also have some kind of fall-back logic to deal with corner cases such as where a sausage with the specified name has already been made, or the materials the sausage is being made from don&#39;t exist.</p><p>Managing model-based permissions in code like this is difficult because each process requires a mix of permissions on an unknown set of models. For example if we want to figure out which permissions are required to make sausages it will be necessary to know:</p><ul><li>Which models the make_sausage helper function interacts with, both directly within the function, and indirectly via foreign keys and/or many to many relationships.</li><li>Any models the helper function interacts with outside of the sausage_factory app.</li><li>How the helper function interacts with all the models indicated above (for example does it simply need read access, or does it need to create and delete model instances?).</li></ul><p>Establishing this is an exercise in and of itself. Consider also that what it means to make a sausage is likely to change over the lifetime of the business. The data that needs to be accessed to make a sausage (and how it is accessed) will not stay the same, and neither will the permissions. Locking down access to the application will therefore be an ongoing (and quite involved) concern.</p><p>This is also not intuitive for users requesting access to the application. These users only want to be able to make or sell sausages, and don’t necessarily want to be involved in the particulars of operations on specific database rows.</p><h3>View Based Permissions</h3><p>One possible solution to this problem is to move permissions up to the same level as the business logic. That is, implement permissions on views rather than models.</p><p>The code below implements this behavior in the sausage selling application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a735af7df079678b9fe7d5d27fdc0bfe/href">https://medium.com/media/a735af7df079678b9fe7d5d27fdc0bfe/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd22b5c3e58d1f702b7bdbfd458f6b1b/href">https://medium.com/media/fd22b5c3e58d1f702b7bdbfd458f6b1b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa1ddc71c2e4b75dab0711b91c8bc629/href">https://medium.com/media/aa1ddc71c2e4b75dab0711b91c8bc629/href</a></iframe><p>Starting in <strong>models.py</strong>, each permission is defined in the Meta class of PermissionContainer. This is an unmanaged model (meaning there is no corresponding table in the database) intended only for storing permissions. The reason it exists is that permissions must be defined in Django in the Meta class of a specific model. It doesn&#39;t make sense to tie a view based permission, which may interact with multiple models, to a single model. Therefore a new class is defined to hold these permissions ².</p><p>Note that the choice of name here is arbitrary. the name PermissionContainer was adopted only because it was descriptive and easily understood within our team.</p><p>In <strong>permissions.py</strong>, the logic underlying each permission is defined in a new set of classes overriding the BasePermission object from Django REST Framework. The important bit here is the implementation of the has_permission method. This takes a request and a view as arguments, and returns a boolean value indicating if the request is permitted to access the view.</p><p>In this case our method executes three checks to ensure that:</p><ol><li>A valid (ie: not-null) user object is attached to the request.</li><li>The user making the request is a staff member.</li><li>The user making the request has the required permission (ie: is in a group that is assigned to the required permission).</li></ol><p>Finally, in <strong>views.py</strong>, the permission is attached to the view via the permission_classes decorator, which is imported from rest_framework.decorators.</p><h3>Wrapping Up</h3><p>It’s worth noting that this approach isn’t intended to be the best way of doing permissions in Django — it’s just another way of doing it. There are no doubt use cases where it makes more sense to use the out of the box model-based approach.</p><p>That said, this was the approach that worked for our use case, and we believe there will be other projects that will benefit from this sort of “top-down” approach to permissions management.</p><p>[1]: Permissions may also be assigned directly to users, by-passing the role-based architecture entirely. This is not the approach taken here, but could suit some use cases.</p><p>[2]: Note that this doesn’t stop us from storing permissions on an existing model (for example using the Meta attribute on the Sausage class instead of defining a new model to act as a container). It could even be argued in this case that it’s more idiomatic storing the permissions directly on the Sausage class, as each of the actions is directly tied to instances of this class by it’s name. However recall the assumption that all of these actions are complex, and interact with a range of models across the project both directly and indirectly via foreign keys and database relationships. It therefore makes sense to separate permissions from model definitions for the reasons stated. Of course there will always be situations where it makes more sense to store permissions directly on a specific model, and this should be kept in mind when implementing a permissions system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb725f31e8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/edrolo-engineering/view-based-permissions-in-django-acb725f31e8f">View Based Permissions in Django</a> was originally published in <a href="https://medium.com/edrolo-engineering">Edrolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>