<?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 Moha Alsouli on Medium]]></title>
        <description><![CDATA[Stories by Moha Alsouli on Medium]]></description>
        <link>https://medium.com/@malsouli?source=rss-61575db35d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BjFT2mtrYwxa8vKs</url>
            <title>Stories by Moha Alsouli on Medium</title>
            <link>https://medium.com/@malsouli?source=rss-61575db35d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:01:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@malsouli/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[CI/CD: CodePipeline vs Jenkins Pipeline vs Bitbucket Pipelines]]></title>
            <link>https://malsouli.medium.com/ci-cd-codepipeline-vs-jenkins-pipeline-vs-bitbucket-pipelines-14c9a4d0d5d7?source=rss-61575db35d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/14c9a4d0d5d7</guid>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Moha Alsouli]]></dc:creator>
            <pubDate>Tue, 27 Apr 2021 12:21:25 GMT</pubDate>
            <atom:updated>2021-04-27T12:25:20.978Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*jCbayMNnK8CYQSsdbf2udA.png" /><figcaption>What tool do you use to orchestrate your CI/CD?</figcaption></figure><p>While helping a Product Owner set up for success recently, their Corporate IT asked us why did we choose <a href="https://aws.amazon.com/codepipeline/">CodePipeline</a> over <a href="https://www.jenkins.io/doc/book/pipeline/">Jenkins Pipeline</a> as the CI/CD orchestration tool because all of their other, slightly older, business units use Jenkins Pipelines. Well, here is why…</p><p><strong>Why do I prefer CodePipeline?</strong></p><ul><li>CodePipeline is an <em>AWS managed service</em>, meaning, it does not require management nor maintenance-overhead once it has been set up. Jenkins server on the other hand requires ongoing management of Jenkins itself, its plugins, integrations and the hosting OS (e.g. Linux or Windows).</li><li>CodePipeline is Highly Available and reliable<a href="https://aws.amazon.com/codepipeline/sla/"> with 99.9% SLA</a>. Jenkins server’s SLA depends on its architecture and dependencies so it varies but please let me know if you have it set up with 99.9% SLA.</li><li>CodePipeline only <a href="https://aws.amazon.com/codepipeline/pricing/">costs $1.00 per active pipeline per month</a>. An active pipeline is any pipeline that has run at least once in the billing month. For example, during active delivery sprints, if a project requires 2 Infrastructure pipelines (Develop for Dev and SIT plus Master for UAT and Prod) and 2 Application pipelines (same as the Infrastructure), this is only $4 a month regardless of use and frequency. Jenkins on the other hand is most likely hosted on EC2 instances (or containers) so its cost depends on the number of instances, their size, their uptime in hours and the number of projects sharing Jenkins which is unlikely to bring it down to $4 a month per project unless the instance is small and/or shared with many other projects which raises the below risk.</li><li>In CodePipeline, each pipeline runs separately, meaning, any number of pipelines can build and deploy simultaneously and continuously without blocking each other. Plus, within each pipeline, a deployment can be happening while a new build is getting prepared. In Jenkins, your configurations determine the number of executors you can run i.e. the number of pipelines that can run at the same time. Also, you cannot start a new run of a particular pipeline before completing its previous run.</li><li>CodePipeline can run builds and tests through <a href="https://aws.amazon.com/codebuild/">CodeBuild</a> which is also a reliable and cost effective AWS managed service that does not require ongoing management and comes <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-available.html">in many ready images</a> but you can also <a href="https://aws.amazon.com/blogs/devops/extending-aws-codebuild-with-custom-build-environments/">create your own</a>. Jenkins on the other hand requires setting up and integrating with build servers (or a local build environment).</li><li>CodePipeline integrates with AWS services seamlessly making deployments to CloudFormation, CodeDeploy, S3, ECS and Lambdas very secure and easy. Jenkins on the other hand requires setting up plugins and setting up the right AWS permissions to be able to deploy to AWS.</li></ul><p><strong>What if you need to trigger your pipeline from dynamic branches?</strong></p><p>CodePipeline, as you might know, can only be configured with static branches e.g. you can set up a Develop pipeline to pick up from the develop branch in your source code but not from a dynamic branch such as feature/*. If you need this flexibility, well, <a href="https://aws.amazon.com/blogs/devops/multi-branch-codepipeline-strategy-with-event-driven-architecture/">check out Henrique Bueno’s cool solution</a>!</p><p>But hey, if you’re on Bitbucket, you can also do that using <a href="https://bitbucket.org/product/features/pipelines">Bitbucket Pipelines</a>. Just note that if you want to deploy and/or push code to AWS from Bitbucket Pipelines, you will need to give your Bitbucket Pipelines programmatic access to AWS through Access Keys and/or SSH keys for CodeCommit. These permissions to deploy and manage your resources on AWS could introduce a vulnerability to your application as everyone in your organisation with access to your repo will have access to your AWS resources through the pipeline.</p><p>So, to solve this, restrict your Bitbucket Pipelines access to only s3:PutObject and/or codecommit:GitPush and let CodePipeline continue the orchestration. For example:</p><ul><li>You can use Bitbucket Pipelines to push code to CodeCommit where CodePipeline can pick up the code and start an execution. See <a href="https://jayproulx.medium.com/aws-codecommit-from-atlassian-bitbucket-and-bitbucket-pipelines-for-ci-offloading-4f1131695802">Jay Proulx’s post</a>.</li><li>You can use Bitbucket Pipelines to run tests on commits to your feature/* and hotfix/* branches but use CodePipeline to run tests, builds and deployments from your fixed branches such as develop and master.</li><li>You can use Bitbucket Pipelines to run tests and builds on your feature/* (or even release/*) branches, then push the build output to a fixed S3 location where CodePipeline can pick up the package from and deploy to the relevant environments and applications.</li></ul><p><em>Hot tip:</em> if you’re uploading a package to S3 from Bitbucket Pipelines as suggested above, add codepipeline-artifact-revision-summary to the S3 object’s metadata and CodePipeline will show this Revision Summary in the execution. E.g. the below command pushes a package with Bitbucket’s Commit ID (an available variable) as the Revision Summary:</p><pre>aws s3 cp --metadata codepipeline-artifact-revision-summary=${BITBUCKET_COMMIT} BackendPackage.zip s3://mypackagesbucket/Dev/BackendPackage.zip</pre><p><strong>Last but not least, if you must, you can use Jenkins Pipelines.</strong></p><p>I’m not against it. If your applications require Jenkins, and you have the skills or team to manage it, go with it. Jenkins is very customisable, has a lot of plugins and support online, and you can manage its <a href="https://www.jenkins.io/doc/book/pipeline/jenkinsfile/">pipelines using version controlled text files</a> - the same as you’d do with CodePipeline and Bitbucket Pipelines. But if you’re planning on using Jenkins, use it wisely. Plan and architect to your needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14c9a4d0d5d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decouple and De-Risk]]></title>
            <link>https://malsouli.medium.com/decouple-and-de-risk-1c861f07fe23?source=rss-61575db35d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c861f07fe23</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[decoupling]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Moha Alsouli]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 01:44:57 GMT</pubDate>
            <atom:updated>2021-03-08T01:44:57.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2i8_Mdoe9NVzTnMBX1ZBMQ.png" /><figcaption>Monolithic vs Micro Architecture</figcaption></figure><p><em>“Don’t put all your eggs in one basket” - while legacy architecture designs have helped us serve award winning apps for our clients back in the day, change was slow and deployments and maintenance tasks were always a headache requiring too much planning, effort and overhead. So, how did we improve on this?</em></p><p>At <a href="https://tigerspike.com/">Concentrix Tigerspike</a>, our inquisitive nature brings insight and innovation. And migrating our hosting services over from the local datacentre to <a href="https://aws.amazon.com/">AWS</a> back in 2013-2014 made it even easier and better to innovate and keep up with the latest best practices. With <a href="https://aws.amazon.com/">AWS</a>, you’re always presented with new services, solutions and opportunities for improvement.</p><p>Shared dependencies between applications bring shared risks; i.e. each application introduces its own risks to a bigger pool of risks shared by all applications.</p><p>So, without further ado, here are some of the approaches we’ve taken to decouple and de-risk the applications we build and manage wherever and whenever possible:</p><h4>Decouple your multiple applications on a shared infrastructure.</h4><p>This is pretty much decoupling 101. If you have multiple applications hosted on the same infrastructure, move them away from each other. The less they share, the fewer risks you would have. So, here are some infrastructure decoupling practices:</p><ul><li>If your applications are managed through one repository, split them. Creating new repos should be easy and straightforward with any provider, especially if you are hosting your own source code service, but look into <a href="https://aws.amazon.com/codecommit/features/">CodeCommit</a> if you’re looking for a reliable and cheap managed repo service that you can integrate so easily with other AWS services and developer tools.</li><li>If your applications share CI/CD pipelines, separate them. <a href="https://aws.amazon.com/codepipeline/features/">CodePipeline</a> makes it very easy to create pipelines and standardise them via <a href="https://docs.aws.amazon.com/codepipeline/latest/userguide/tutorials-cloudformation.html">CloudFormation templates</a>. Also, the sky is your limit with <a href="https://aws.amazon.com/codebuild/features/">CodeBuild</a> and <a href="https://aws.amazon.com/codedeploy/features/">CodeDeploy</a>. Check out my previous post “<a href="https://malsouli.medium.com/10-smart-ways-to-use-aws-codebuild-22a8ee0d9302">10 smart way to use CodeBuild</a>” for ideas.</li><li>If your applications are hosted on the same instance or same set of instances, separate them and deploy on different instances or different sets of instances. Use <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/LaunchTemplates.html">Launch Templates</a> and <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html">Auto Scaling Groups</a>, <a href="https://aws.amazon.com/elasticbeanstalk/">Elastic Beanstalk</a> or <a href="https://aws.amazon.com/opsworks/">OpsWorks</a> to manage your instances and their configurations. Also, make use of <a href="https://aws.amazon.com/elasticloadbalancing/">Elastic Load Balancing</a> to distribute traffic between your instances and to add an extra layer of protection in front of them. And once they’re up and running, make use of <a href="https://aws.amazon.com/compute-optimizer/">AWS Compute Optimizer</a> or <a href="https://aws.amazon.com/premiumsupport/technology/trusted-advisor/">Trusted Advisor Cost Optimization</a> checks to increase efficiency and avoid unnecessary costs. One big instance is not always cheaper nor always better than two smaller instances.</li><li>If your applications share a database instance or a set of database instances, separate them onto their own instances or own sets of database instances. Without a doubt, <a href="https://aws.amazon.com/rds/features/">RDS</a> is the best for this. With RDS, you can manage backups and read replicas easily, scale your instances vertically or horizontally in minutes, and you can migrate easily to RDS with the <a href="https://aws.amazon.com/dms/">Database Migration Service</a>.</li></ul><h4>Decouple the Frontend and Backend of your Full Stack applications.</h4><p>Another easy one, perhaps, that every Software Engineer with experience would agree with. Simply, split your application’s Frontend hosting from your Backend hosting. They should be hosted separately so when one is down or undergoing maintenance, the other is still functioning. Obviously, the Frontend relies on the Backend to function but you want the Frontend to still work and show “nice” error messages rather than crash when the Backend is not available. Treat them as two different applications with separate repos, separate CI/CD pipelines and independent hostings as much as possible. A simple “we’ll be back soon” or “try again in 5 minutes” in the Frontend gives a very different experience to the end user compared to a blue screen of death when there’s a memory, database or deployment issue in the backend!</p><p>You can use <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html">S3 for your static websites</a> and <a href="https://aws.amazon.com/s3/">contents storage</a>, <a href="https://aws.amazon.com/cloudfront/">CloudFront</a> for your CDN, <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/application_architecture.html">ECS for your Frontend or Backend containers</a>, <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started-with-lambda-integration.html">API Gateway and Lambda functions for your backend APIs</a> and <a href="https://aws.amazon.com/lambda/">processors</a>, or <a href="https://aws.amazon.com/ec2/">EC2</a> for anything you want to lift and shift as is.</p><h4>Categorise and decouple your Infrastructure as Code resources.</h4><p>Like many early adopters of <a href="https://en.wikipedia.org/wiki/Infrastructure_as_code">IaC</a>, our very early templates were either written per AWS service, which makes them too many, or for everything that makes up an application, which makes them too complicated. Imagine managing a template for VPCs, a template for Subnets, a template for RDS, a template for Load Balancers, etc. Too many. On the other hand, imagine managing one ~3000 lines template that includes everything for that application such as VPC, Subnets, RDS instances, Load Balancers, EC2 instances, IAM Roles, etc. Too complicated.</p><p>A few solid projects later, we found the sweet spot. We now group resources based on their logical service within the system we’re building. <em>For example</em>:</p><ul><li>Infrastructure templates: the templates where we can manage the networking (e.g. VPC &amp; Subnets) and security resources (e.g. IAM Roles). We can also add the resources that support-but-do-not-directly-host the application in this template if they’re not lengthy (e.g. S3 Buckets or Cognito User Pools). And, if the resources fit into the support-but-do-not-directly-host the application but they’re lengthy (e.g. RDS or Redis), we can add them to the infrastructure templates as <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html">Nested Stacks</a> (for <a href="https://aws.amazon.com/cloudformation/">CloudFormation</a>) or as <a href="https://www.terraform.io/docs/language/modules/index.html">Modules</a> (for <a href="https://www.terraform.io/">Terraform</a>). These templates should be hosted in an “Infrastructure” repository and deployed through an “Infrastructure” CI/CD pipeline. Also, these templates should be parameterised allowing us to deploy them multiple times to create however many environments we need (Dev, UAT, etc) consistently.</li><li>Application templates: the templates where we manage the resources that host one application directly e.g. API Gateway and Lambda Functions, ECS Services and Tasks or Launch Templates and Autoscaling Groups. These templates should be hosted in their respective application’s repository, managed with the application and deployed through the application’s CI/CD pipeline. This gives the application’s team ownership and accountability over their application. A good DevOps practice. These templates are also parameterised and deployed for the number of environments needed.</li><li>Supporting templates: these are the templates where we manage shared resources, account level resources, CI/CD resources, etc. These templates are usually deployed once per account or once per application and managed alongside the infrastructure templates.</li></ul><h4>Finally, refactor and decouple your monolithic applications.</h4><p>Perhaps, this is the first thing people think of when you start talking about decoupling; and this is where they give up. Decoupling monolithic apps could be overwhelming, time consuming and expensive when you look at it altogether! But, in reality, it doesn’t have to be. As you read so far, we have gone through different examples of decoupling and de-risking different things around the app. “Take the small wins to achieve the bigger goals”, and when you get to this stage, here are a few pointers to help you:</p><ul><li>For Backend apps: Look into your application’s backend and dig into the functionalities and services. If you have scheduled processes or backend tasks move them onto their own <a href="https://aws.amazon.com/ecs/?whats-new-cards.sort-by=item.additionalFields.postDateTime&amp;whats-new-cards.sort-order=desc&amp;ecs-blogs.sort-by=item.additionalFields.createdDate&amp;ecs-blogs.sort-order=desc">ECS containers</a> or, better, <a href="https://aws.amazon.com/lambda/">Lambda functions</a> and use a messaging service to invoke them such as <a href="https://aws.amazon.com/blogs/compute/choosing-between-messaging-services-for-serverless-applications/">SQS, SNS or EventBridge</a>. Then, for the core services, rearchitect them in a <a href="https://aws.amazon.com/microservices/">Microservices architecture</a>. The Microservices architecture could be made up of containers on <a href="https://aws.amazon.com/ecs/">ECS</a>, Kubernetes on <a href="https://aws.amazon.com/kubernetes/">EKS</a>, functions on <a href="https://aws.amazon.com/lambda/">Lambda</a> or a mix of all. So many options and all of them are right. The Microservices could be as big or as small as you want them. The idea is to decouple what you can.</li><li>For Frontend apps: This is relatively new but Frontends are now following the steps of backends as modern web apps have grown. There are so many services on AWS to help you decouple your Frontend but look into containers on <a href="https://aws.amazon.com/ecs">ECS</a> or static contents websites on <a href="https://aws.amazon.com/s3/">S3</a>. Also, take a look at the <a href="https://micro-frontends.org/">Micro Frontends</a> architecture for more ideas.</li><li>For Databases: I won’t bother you talking about refactoring and splitting databases. You can actually reduce the risks when you’re hosting multiple databases by simply moving them away from each other as mentioned earlier. If they’re on one big instance, move them to smaller suitable instances. If you have a master and replicas on the same host, move them away to different hosts. Better yet, move to a managed database service where you’re not relying on physical hosts nor on one or two hosts for management. Check out <a href="https://aws.amazon.com/rds/ha/">RDS High Availability and %99.95 SLA</a>.</li></ul><p>That’s all folks! I know I highlighted a lot of decoupling practices, and mentioned a dozen of AWS services and examples, in a 5 minutes read so I will leave you with that. The aim is to inspire anyone out there looking for ideas and to show how easy it is to get started.</p><p><a href="https://www.linkedin.com/in/mohaalsouli/"><em>Reach out or connect</em></a><em> if you would like to discuss more ideas. Otherwise, feel free to comment below or share this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c861f07fe23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Well Architected Framework]]></title>
            <link>https://malsouli.medium.com/the-well-architected-framework-d004f7bbf7ad?source=rss-61575db35d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d004f7bbf7ad</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[well-architected]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Moha Alsouli]]></dc:creator>
            <pubDate>Thu, 19 Nov 2020 22:04:32 GMT</pubDate>
            <atom:updated>2020-11-27T02:41:03.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*gJ8-n--JXg8CQ8ZA.png" /></figure><p><em>The </em><a href="https://aws.amazon.com/architecture/well-architected/"><em>Well Architected Framework</em></a><em>, put together by AWS, is a model to help architects and engineers design and build secure, high-performing, resilient, and efficient infrastructure, on any platform.</em></p><p>At <a href="https://tigerspike.com/">Tigerspike</a>, we pride ourselves on having the right people, resources and experience to design and build cutting edge technology for, and with, our customers, globally. The consultancy work that we do keeps us up to date with the latest operating, security, and architecture principles and best practices. However, without a framework, these principles and practices are always open for interpretation which makes room for flaws.</p><p>Since then, we’ve become an <strong>AWS Well Architected partner</strong>. This means: our architects always follow the Framework’s principles and understand the pros and cons of their decisions; and they’re capable of helping customers evaluate their workloads, identify areas of improvements, and prioritise remediations if any.</p><p>The Well Architected Framework describes key concepts, design principles, and architectural best practices in five pillars: Operational Excellence, Security, Reliability, Performance Efficiency and Cost Optimisation. While these are explained in detail in <a href="https://docs.aws.amazon.com/wellarchitected/latest/framework/welcome.html">the Framework’s documentation</a>, we, as an AWS Well Architected partner, can add value by reviewing and evaluating workloads through a set of questions designed to address all topics in these pillars. And with the answers, we measure how well aligned is the infrastructure with the current best practices and provide guidance for improvements.</p><p>These Well Architected Reviews can cover all pillars or focus on one or two; and they can be done once or regularly throughout the workloads lifecycle - which is recommended as best practices and workloads evolve.</p><h4>What are the five pillars?</h4><ul><li><strong>Operational Excellence</strong><br>Focusing on running and monitoring systems to deliver business value, and continually improving processes and procedures. Key topics include automating changes, responding to events, and defining standards to manage daily operations.</li><li><strong>Security</strong><br>Focusing on protecting information and systems. Key topics include confidentiality and integrity of data, identifying and managing who can do what with privilege management, protecting systems, and establishing controls to detect security events.</li><li><strong>Reliability</strong><br>Focusing on ensuring a workload performs its intended function correctly and consistently when it’s expected to. A resilient workload quickly recovers from failures to meet business and customer demand. Key topics include distributed system design, recovery planning, and how to handle change.</li><li><strong>Performance Efficiency</strong><br>Focusing on using IT and computing resources efficiently. Key topics include selecting the right resource types and sizes based on workload requirements, monitoring performance, and making informed decisions to maintain efficiency as business needs evolve.</li><li><strong>Cost Optimisation</strong><br>Focusing on avoiding unnecessary costs. Key topics include understanding and controlling where money is being spent, selecting the most appropriate and right number of resource types, analysing spend over time, and scaling to meet business needs without overspending.</li></ul><h4>Examples</h4><p>Here are some findings from our last few reviews:</p><ul><li>We helped a cost-conscious customer, who has built a reliable, operationally excellent and performance efficient workload, identify and prioritise 17 high risk items in the Security and Cost Optimisation pillars, and a couple of medium risk items in the rest of the pillars.</li><li>We helped a customer designing an application, with security as top priority, identify 11 high risk items in Security to focus on and address in the early stages of development.</li><li>We helped a customer, whose main requirement is the high availability of their applications, identify 5 high risk items in Reliability, 5 in Operational Excellence and 4 in Performance Efficiency that could all contribute to improving the availability and reliability of their applications.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*ns1hjM05XDfbABTgl2AEZg.png" /><figcaption>Summary of a Well Architected Review output — usually followed by an Improvement Plan and Focus Items</figcaption></figure><p>You would be surprised how common the above scenarios are. These customers were focusing on certain requirements but overlooked a few aspects that contribute back to their requirements. Having another pair of eyes, especially an experienced one, was just what they needed. So, reach out to learn more about the Well Architected Framework and how Tigerspike can help you set up for success.</p><p><em>This post has also been </em><a href="https://tigerspike.com/well-architected-framework/"><em>published on Tigerspike’s website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d004f7bbf7ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EC2 Image Builder: makes server builds easy!]]></title>
            <link>https://malsouli.medium.com/ec2-image-builder-makes-server-builds-easy-96de87db0917?source=rss-61575db35d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/96de87db0917</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ec2-image-builder]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Moha Alsouli]]></dc:creator>
            <pubDate>Thu, 08 Oct 2020 03:35:42 GMT</pubDate>
            <atom:updated>2020-10-08T03:35:42.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*p8z7RG1KwpJG0oyzKXCY1A.png" /><figcaption>Build and maintain secure images</figcaption></figure><p><strong><em>Back in March, I wrote a post on </em></strong><a href="https://medium.com/@malsouli/ci-cd-automate-server-builds-with-packer-and-codebuild-6cfa97fa1e79"><strong><em>how to build Golden Images using Packer on AWS CodeBuild</em></strong></a><strong><em>. Today, let me show you how to do even better builds with AWS </em></strong><a href="https://aws.amazon.com/image-builder/"><strong><em>EC2 Image Builder</em></strong></a><strong><em>!</em></strong></p><p>We’ve been using Packer at <a href="https://tigerspike.com/">Tigerspike</a> for quite a while now to build servers (if we’re not deploying serverless applications!) so we’re comfortable with it. It works great and does the job perfectly. But I couldn’t stop there, I had to try the recently introduced <a href="https://aws.amazon.com/about-aws/whats-new/2019/12/introducing-ec2-image-builder/">EC2 Image Builder</a>. So, I tried it the other day, loved it, and now using it to deploy a service to production, <em>and I think we’ll be using it from now on!</em></p><h4>TL;DR</h4><p>EC2 Image Builder is faster, cheaper and more secure and reliable than Packer. That is not to say Packer is slow nor expensive at all, but it’s the -er suffix that we’re after in Tech! Find a link to CloudFormation templates examples at the bottom of this post to try EC2 Image Builder yourself.</p><h4>What is EC2 Image Builder?</h4><p>As AWS puts it, EC2 Image Builder is a service that makes it easier and faster to build and maintain secure images. Image Builder simplifies the creation, patching, testing, distribution, and sharing of Linux or Windows Server images.</p><h4>Why is it faster?</h4><p>Well, it’s serverless. When using EC2 Image Builder, you are not relying on another server to orchestrate your builds. The EC2 Image Builder service <a href="https://aws.amazon.com/image-builder/#How_it_works">orchestrates the builds and tests</a> for you directly on EC2 instances. It also takes care of distributing the image for you across accounts.</p><h4>Why is it cheaper?</h4><p>For the same reason above, you don’t need an extra server to orchestrate the builds. So, <a href="https://docs.aws.amazon.com/imagebuilder/latest/userguide/how-image-builder-works.html#image-builder-resources">you’re only paying for the resources</a> you use to build, test and store the AMIs, not the overhead.</p><h4>Why is it more secure?</h4><p>Since it’s an AWS service, it works well with IAM Roles and Permissions. For example, you do not need to open your security groups so the orchestrator server can reach the build instances (<a href="https://github.com/hashicorp/packer/issues/6735">like you need for Packer</a>). Instead, you only need <a href="https://docs.aws.amazon.com/imagebuilder/latest/userguide/image-builder-setting-up.html">IAM Roles with the right Policies</a>. Nothing need to traverse the internet anymore - everything stays within your VPC!</p><h4>Why is it more reliable?</h4><p>Well, where do I start?!</p><ul><li>As with all <strong>AWS</strong> managed services, you will always get the latest updates and features.</li><li>Besides image <strong>recipes</strong>, you can automate image builds though <strong>Pipelines</strong>, <a href="https://aws.amazon.com/blogs/aws/automate-os-image-build-pipelines-with-ec2-image-builder/">as explained in this blog</a>.</li><li>Access to <strong>AWS-provided</strong> <strong>components</strong> (templates), e.g. update-windows, update-linux, php-7–2-ubuntu, dotnet-core-hosting-bundle-windows, amazon-cloudwatch-agent-linux, etc.</li><li>You can <strong>develop and test</strong> your <a href="https://docs.aws.amazon.com/imagebuilder/latest/userguide/image-builder-component-manager-local.html">own components locally</a>.</li><li>Components are <strong>managed centrally</strong> and can be <strong>versioned</strong>, e.g. 1.0.3, so you can reuse them across different image pipelines.</li><li>Each component can include <a href="https://docs.aws.amazon.com/imagebuilder/latest/userguide/how-image-builder-works.html#image-builder-component-management"><strong>Build, Validate and Test phases</strong></a>. These are used to install applications and modify the OS, then validate the build before the AMI creation, then test the AMI after it’s created.</li><li>Components, recipes and images <a href="https://docs.aws.amazon.com/imagebuilder/latest/userguide/how-image-builder-works.html#image-builder-distribution">can be <strong>shared</strong> across AWS regions, Accounts or Organizations</a>.</li><li><a href="https://docs.aws.amazon.com/imagebuilder/latest/userguide/how-image-builder-works.html#image-builder-compliance"><strong>Compliance</strong> assessment and <strong>Hardening</strong></a> validation offering.</li></ul><p>That’s probably enough reasons for now!</p><h4>EC2 Image Builder is Golden!</h4><p><strong>Try EC2 Image Builder yourself.</strong> I’ve uploaded example CloudFormation templates for both <a href="https://github.com/mohaalsouli/blog-examples/tree/master/ImageBuilderLinux">Linux</a> and <a href="https://github.com/mohaalsouli/blog-examples/tree/master/ImageBuilderWindows">Windows</a> AMI builders <a href="https://github.com/mohaalsouli/blog-examples">to my GitHub</a>. Both take simple parameters and are ready to deploy. Otherwise, see the official <a href="https://docs.aws.amazon.com/imagebuilder/latest/userguide/what-is-image-builder.html">EC2 Image Builder User Guide</a> for more.</p><p><em>That’s it folks! Till the next time..</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96de87db0917" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does your CloudFormation Stack Update require cleaning up resources before the update?]]></title>
            <link>https://malsouli.medium.com/does-your-cloudformation-stack-update-require-cleaning-up-resources-before-the-update-70fd772cb288?source=rss-61575db35d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/70fd772cb288</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cloudformation]]></category>
            <dc:creator><![CDATA[Moha Alsouli]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 03:04:25 GMT</pubDate>
            <atom:updated>2020-09-11T03:04:25.662Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*SxxTdFhu9JCS-dmZnWvymA.png" /><figcaption><strong><em>Circular dependency!</em></strong></figcaption></figure><p><strong><em>Does your CloudFormation Stack Update require a Clean Up of existing resources first to be able to create new ones, but the Clean Up cannot happen before the creation of the new resources is complete? Circular dependency? Catch-22? Here’s how to solve it.</em></strong></p><h4>I admit, this is quite rare; but surely a few others ran into it like me. So, here is my scenario:</h4><p>We have a <a href="https://aws.amazon.com/cloudformation/resources/templates/">CloudFormation template</a> which has an <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html">Auto Scaling Group</a> that launches an EC2 instance from a <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html">Launch Template</a>. The Launch Template, besides defining essential properties, attaches a specific <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html">Elastic Network Interface</a> to the launched instance. We do this because this specific ENI is referenced somewhere else so we want to keep it even if the instance attached to it was updated or replaced. So, a few days later, we updated the AMI ID in the Launch Template in CloudFormation, which generated a new version of the Launch Template so now CloudFormation wants to update the Auto Scaling Group to launch a new instance from the new version</p><h4>Do you see the problem?</h4><p>In a normal workflow, CloudFormation will create the new resources then clean up the obsolete ones. However, in this case, it cannot launch a new instance because the Elastic Network Interface is still in use (by the old instance); and it cannot terminate the old instance (which will free the Elastic Network Interface) because the stack update is not complete yet!</p><p><strong><em>While my problem was with an Auto Scaling Group and EC2, yours could be with other AWS services. Nevertheless, the circular dependency will be the same and, the good news is, you can solve it the same way.</em></strong></p><h4><strong>The Solution:</strong></h4><p>Use a <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources-lambda.html">Lambda-Backed Custom Resource</a> to clean up and delete the old resources then signal back to CloudFormation to continue the updates.<br>In my case, I wrote the Custom Resource to take in the Launch Template’s ID and Version as parameters, look up the old Auto Scaling Group and set its capacity to 0 (to start terminating any old instances), then send a success to CloudFormation so it starts updating the Auto Scaling Group.</p><p>Confused? Don’t worry, <a href="https://github.com/mohaalsouli/blog-examples/tree/master/CFCustomCleanup">see this YAML template example on GitHub</a>, which has inline comments to explain it.</p><p>In summary, here is what happens now - when we push updates:<br>● The Launch Template is updated, CloudFormation generates new Version;<br>● CloudFormation sends a <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-requests.html">request</a> to the Custom Resource Lambda containing the Request Type (e.g. Update), a Response URL, the Launch Template ID and the new Version;<br>● The Custom Resource Lambda looks up the Auto Scaling Group with the old Version of the Launch Template;<br>● The Custom Resource Lambda sets the capacity of the ASG to 0, and returns success <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-responses.html">response</a> to CloudFormation;<br>● The ASG starts terminating the old instance to meet the desired 0 capacity;<br>● CloudFormation receives the success response and continues;<br>● CloudFormation updates the ASG with the new Launch Template Version resetting the desired capacity as defined in the template;<br>● The ASG starts launching a new instance to meet the desired capacity.</p><p><em>Hope that was helpful. Feel free to comment or ask below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70fd772cb288" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 smart ways to use AWS CodeBuild]]></title>
            <link>https://malsouli.medium.com/10-smart-ways-to-use-aws-codebuild-22a8ee0d9302?source=rss-61575db35d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/22a8ee0d9302</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[codebuild]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[tigerspike]]></category>
            <dc:creator><![CDATA[Moha Alsouli]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 05:49:50 GMT</pubDate>
            <atom:updated>2020-07-12T05:49:50.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*gV8xI2EFZJiW8zRszRSgqQ.png" /></figure><p><em>I cannot emphasise enough how useful </em><a href="https://aws.amazon.com/codebuild/"><em>AWS CodeBuild</em></a><em> is, but I thought I would list “some” of its powerful and smart uses we have adopted in our pipelines; because at </em><a href="https://tigerspike.com/"><strong><em>Tigerspike, our inquisitive nature brings insight and innovation</em></strong></a><strong><em>.</em></strong></p><p>Back in the day, and I’m talking a few years ago, like many companies, our CI was limited to Jenkins and a few build agents on EC2 instances. This was so limiting that, after a short time, maintaining the build agents with updates and different tools became a time consuming task so our development teams started creating their own AMIs and build agents. Of course, maintaining Jenkins and the shared executors across dozens of projects was getting out of hand too. This was troublesome and often a blocker that we had to ensure there is enough people around at all times with knowledge to maintain it.</p><p>But that’s not the case anymore. Hold my coffee, let me count…. I, myself, have built over 40 custom pipelines for different projects and different workstreams for different teams in just the last 2 years! Too many? No, not at all. Every workstream in every project has their own requirements.<br><strong>Thanks to </strong><a href="https://aws.amazon.com/products/developer-tools/"><strong>AWS Developer tools</strong></a>, my team and I can swiftly build CI/CD pipelines just as required for each project then handover to the delivery teams to update and maintain by themselves through IaC templates and scripts. Only complex updates get escalated to us, occasionally. And come future soon, the development teams will be <em>building</em> their own pipelines and <em>maintaining</em> them thanks to the professional development incentives at <a href="https://tigerspike.com/"><strong>Tigerspike</strong></a><strong> </strong>and the <strong>DevOps</strong> mentality program our senior Engineers are pushing through.</p><h4>Anyway, enough with the backstory, let me jump straight into CodeBuild’s awesomeness.</h4><p>As AWS puts it, CodeBuild is a fully managed CI tool that lets you compile source code, run tests, and produce packages that are ready to deploy.</p><p>So, how do we use CodeBuild at <a href="https://tigerspike.com/"><strong>Tigerspike</strong></a><strong>?</strong> Here’s my top 10 uses:<strong><br>1. Builds, ad-hoc.<br>2. Builds, part of a CodePipeline.<br>3. Builds, docker.<br>4. Unit testing.<br>5. Automation testing.<br>6. Database migrations.<br>7. Database operations.<br>8. </strong><a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/package.html"><strong>CloudFormation Packaging</strong></a><strong> (e.g. Nested Stacks)<br>9. Source Code repository tagging<br>10. </strong><a href="https://docs.newrelic.com/docs/apm/new-relic-apm/maintenance/record-monitor-deployments"><strong>Deployment marking (e.g. NewRelic)</strong></a></p><p><em>I won’t get into how to setup CodeBuild Projects. Check </em><a href="https://docs.aws.amazon.com/codebuild/latest/userguide/getting-started-overview.html"><em>Getting Started</em></a><em> or </em><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_CodeBuild.html"><em>CloudFormation</em></a><em> documentation for that, but it’s worth mentioning that CodeBuild can be integrated with </em><a href="https://aws.amazon.com/codepipeline/"><em>CodePipeline</em></a><em>, </em><a href="https://aws.amazon.com/codecommit/"><em>CodeCommit</em></a><em>, </em><a href="https://aws.amazon.com/s3/"><em>S3</em></a><em>, </em><a href="https://github.com/"><em>GitHub</em></a><em>, and/or </em><a href="https://bitbucket.org/"><em>Bitbucket </em></a><em>as source code providers or can be set up without a source.</em></p><h4>Now let’s dive a little into each of these uses.</h4><h4>1. Builds, ad-hoc.</h4><p>It’s called CodeBuild for a reason. Its main purpose is to build.<br>So, let’s assume we want to build a .Net Core package and simply put it in S3. First, to set up our CodeBuild Project, we have to choose one of the CodeBuild images that support our .Net Core version. See <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-available.html">the list here</a>. Then, we have to set up the source provider, CodeCommit for example.<br>Finally, add a <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html"><strong>buildspec.yml</strong> (the build script file)</a> to your source code. The buildspec.yml for this job should simply look something like this:</p><pre>version: 0.2<br>env:<br>  variables:<br>    S3_BUCKET: my-packages-bucket<br>phases:<br>  install:<br>    runtime-versions:<br>      dotnet: 3.1<br>  build:<br>    commands:<br>      - echo &quot;CD into source folder, because my source code is tidy&quot;<br>      - cd src<br>      - echo &quot;Restore, Build, then Publish..&quot;<br>      - dotnet restore<br>      - dotnet build --no-restore<br>      - dotnet publish --no-restore --output outputDirectory<br>  post_build:<br>    commands:<br>      - echo &quot;Compressing the package..&quot;<br>      - cd ../outputDirectory<br>      - zip -r myBuild.zip .<br>      - echo &quot;Uploading to S3..&quot;<br>      - aws s3 cp myBuild.zip s3://${S3_BUCKET}/myBuild.zip<br>      - echo &quot;Done.&quot;</pre><p>Pretty straight forward, isn’t it?!<br>First, we defined the buildspec version (0.2 is recommended), then we defined the environment variable S3_BUCKET. Then, in the install phase, we specify the runtime we want CodeBuild to initialise. And luckily our image and runtime comes with zip and AWS CLI installed so we don’t need to run any other install commands.<br>In the build phase, we simply go into the source code folder, restore .Net, build then publish. I like running these commands separately in that order to give our teams space to explicitly call different options and configurations throughout the process and if they want, they can remove the explicit restore or do other things. It’s up to them, that’s the point ;)<br>Post build, we go into the output folder, zip the files then upload into S3.</p><blockquote>As you might have imagined, this CodeBuild project will need an IAM Role with the right permissions to pull code from CodeCommit and put objects in S3.</blockquote><h4>2. <strong>Builds, part of a CodePipeline.</strong></h4><p>Let’s assume the same scenario as before. We want to build a .Net Core package but instead of uploading it to S3, we want to pass the artifacts to the next Action, or Stage, in CodePipeline. Our buildspec.yml will look like this:</p><pre>version: 0.2</pre><pre>phases:<br>  install:<br>    runtime-versions:<br>      dotnet: 3.1<br>  build:<br>    commands:<br>      - echo &quot;CD into source folder, because my source code is tidy&quot;<br>      - cd src<br>      - echo &quot;Restore, Build, then Publish..&quot;<br>      - dotnet restore<br>      - dotnet build --no-restore<br>      - dotnet publish --no-restore --output outputDirectory<br>artifacts:<br>  base-directory: outputDirectory<br>  files:<br>    - &#39;**/*&#39;</pre><p>You might have noticed the buildspec above looks pretty similar to the previous one, except that there is no post build stage, nor environment variables declaring the S3 bucket. Instead, CodePipeline will pass the code to CodeBuild, and we declare what artifacts we want to pass back to CodePipeline when the job is done.<br>So, in the Artifacts section in this example, we specified the base directory of the artifacts, outputDirectory, and all files in the directory using &#39;**/*&#39; which represents all files recursively for CodeBuild.<br>If you want to select specific files, or files in multiple locations, you can skip the base-directory declaration and list your files instead with their relative paths to the working directory.</p><blockquote>This CodeBuild project only needs an IAM Role with permissions to interact with CodePipeline.</blockquote><h4><strong>3. Builds, docker</strong></h4><p>For this example, we will assume a different scenario: we want to build a Docker image and register it in Amazon <a href="https://aws.amazon.com/ecr/">Elastic Container Registry “ECR”</a>. You can use these images then to deploy containers to AWS <a href="https://aws.amazon.com/ecs/">Elastic Container Service</a> manually or through CodePipeline. Assuming we have a <a href="https://docs.docker.com/engine/reference/builder/">Dockerfile</a> already in our repository, our buildspec.yml should look like this:</p><blockquote><em>Note, you must enable </em><strong><em>Privileged Mode</em></strong><em> in your </em><a href="https://docs.aws.amazon.com/codebuild/latest/userguide/create-project.html"><em>CodeBuild’s configurations</em></a><em> to be able to use it to build docker images.</em></blockquote><pre>version: 0.2<br>env:<br>  variables:<br>    ECR_REPO: 123456789012.dkr.ecr.us-east-1.amazonaws.com/myapi<br>phases:<br>  install:<br>    runtime-versions:<br>      docker: 18<br>  build:<br>    commands:<br>      - echo &quot;Building a Docker image..&quot;<br>      - docker build -t myImage . --file Dockerfile<br>      - echo &quot;Tagging Docker image for ECR..&quot;<br>      - docker tag myImage ${ECR_REPO}:${CODEBUILD_SOURCE_VERSION}<br>      - echo &quot;Logging into ECR..&quot;<br>      - $(aws ecr get-login --no-include-email)<br>      - echo &quot;Pushing Docker image to ECR..&quot;<br>      - docker push ${ECR_REPO}:${CODEBUILD_SOURCE_VERSION}<br>      - echo &quot;Done.&quot;</pre><p>In this scenario, we defined our environment variable ECR_REPO which is the ECR repository we want to register our images with. After that, we specify docker 18 runtime in the install phase then enter the build steps.<br>The build steps are standard docker build, docker tag and docker push commands, however, we need to log in to ECR before being able to push. The <a href="https://docs.aws.amazon.com/cli/latest/reference/ecr/get-login.html">CLI command</a> $(aws ecr get-login --no-include-email) does the trick.<br>Also, did you notice that we tagged our image with CODEBUILD_SOURCE_VERSION variable? This is one of the many variables <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html">available by default to your build environment</a>. I like using the commit ID as a tag rather than latest for better management of deployments and rollbacks.</p><blockquote>For this CodeBuild project, make sure it has an IAM Role with permissions to authenticate and upload images to ECR; and interact with your source provider.</blockquote><h4><strong>4. Unit testing.</strong></h4><p>This one is simple.<br>Let’s assume we are building a Node.js package using npm, but before building and publishing the artifacts, we want to run unit tests.<br>Here’s what our buildspec.yml should look like:</p><pre>version: 0.2</pre><pre>phases:<br>  install:<br>    runtime-versions:<br>      nodejs: 12<br>  build:<br>    commands:<br>      - echo &quot;Installing dependencies..&quot;<br>      - npm install<br>      - echo &quot;Unit testing..&quot;<br>      - npm test<br>      - echo &quot;Building..&quot;<br>      - npm build<br>artifacts:<br>  base-directory: build<br>  files:<br>    - &#39;**/*&#39;</pre><p>Did you notice the npm test command? CodeBuild will run the tests in your code and if the tests fail, CodeBuild will stop at this step. It won’t continue. But if it succeeded, it will pass the build artifacts to the next action or stage in CodePipeline, same as in example 2 previously.</p><blockquote>This CodeBuild project only needs permissions to interact with CodePipeline.<br>Tip: consider setting up <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/sample-build-notifications.html">build notifications using CloudWatch and SNS</a> with this job if you want to be notified on success or failure.</blockquote><h4>5. Automation testing.</h4><p>For automation testing, our teams prefer to maintain the automation testing scripts in separate repositories than their applications repositories. So, just like what we do with ad-hoc builds, we trigger our automation test jobs on demand after successfully deploying to QA and/or UAT. The generated reports are sent to the team then.<br>For simplicity, let’s say our test scripts are written in Node.js which run automation tests and write reports to a local reports folder. After that, we want to upload these reports to S3 and notify the team through <a href="https://aws.amazon.com/sns/">SNS</a>. Of course, <strong>we do not want to hard code any secrets or endpoints</strong> in our scripts. We will store these in json format in <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">AWS Secrets Manager</a> and retrieve them before starting the tests into environment variables that our scripts can find.<br>This automated job saved one of our engineering teams 15 minutes for each run compared to when they were running it locally on their machines. <em>Imagine, if we need to run tests 4 times a week, we’re saving an hour a week by running it on CodeBuild</em>!</p><p>Here’s a simplified sample of a buildspec.yml for this job:</p><pre>version: 0.2<br>env:<br>  variables:<br>    S3_BUCKET: my-reports-bucket<br>    TOPIC_ARN: arn:aws:sns:us-east-1:123456789012:mySNSTopic<br>  secrets-manager:<br>    SECRET: automation-testing-secret<em><br></em>phases:<br>  install:<br>    runtime-versions:<br>      nodejs: 12<br>  pre_build:<br>    commands:<br>      - echo &quot;Get current timestamp for reports naming..&quot;<br>      - TIME=$(date +&quot;%Y%m%d_%H%M%S&quot;)<br>  build:<br>    commands:<br>      - echo &quot;Installing dependencies..&quot;<br>      - npm install<br>      - echo &quot;Testing..&quot;<br>      - npm test<br>  post_build:<br>    commands:<br>      - echo &quot;Zipping reports..&quot;<br>      - cd reports<br>      - zip -r ${TIME}.zip .<br>      - echo &quot;Uploading zipped reports to S3..&quot;<br>      - aws s3 cp ${TIME}.zip s3://${S3_BUCKET}/${TIME}.zip<br>      - echo &quot;Notifying of the new reports..&quot;<br>      - aws sns publish --topic-arn ${TOPIC_ARN} --message &quot;You can Download the new Automation Test reports from here: <a href="https://ermias-videos.s3-ap-southeast-2.amazonaws.com/Tech+Session+with+Ermias+Part+2.mp4">https://</a><a href="https://s3.console.aws.amazon.com/s3/object/$%7BS3_BUCKET%7D/$%7BTIMESTAMP%7D.zip?region=${AWS_REGION}&amp;tab=overview">${S3_BUCKET}</a><a href="https://ermias-videos.s3-ap-southeast-2.amazonaws.com/Tech+Session+with+Ermias+Part+2.mp4">.s3-</a>us-east-1<a href="https://ermias-videos.s3-ap-southeast-2.amazonaws.com/Tech+Session+with+Ermias+Part+2.mp4">.amazonaws.com/</a><a href="https://s3.console.aws.amazon.com/s3/object/$%7BS3_BUCKET%7D/$%7BTIMESTAMP%7D.zip?region=${AWS_REGION}&amp;tab=overview">${</a>TIME<a href="https://s3.console.aws.amazon.com/s3/object/$%7BS3_BUCKET%7D/$%7BTIMESTAMP%7D.zip?region=${AWS_REGION}&amp;tab=overview">}.zip</a>&quot;<br>      - echo &quot;Done.&quot;</pre><p>In this buildspec, our environment variables have both plain text variables as well as a reference to a secret stored in AWS Secrets Manager. For more info on how to reference variables in a buildspec file, <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec.env">see here</a>.<br>The buildspec phases then are simple. In the install phase, we specify the Node.js version we want CodeBuild to run. In the pre build phase, we get the timestamp so we can use it to name our compressed reports folder. In the build phase, we install the dependencies then run the tests. Post build, we zip the reports, push them to S3 then notify the team by a SNS message. It’s a very straight forward process actually.</p><blockquote>For this CodeBuild project, you will need an IAM Role that has permissions to retrieve secrets from Secrets Manager, put objects in S3 and publish to SNS.</blockquote><h4><strong>6. Database migrations.</strong></h4><p>During development of new applications, our software engineers often need to migrate or update the databases schemas and tables. This is a job often forgotten in CI/CD pipelines, but the DevOps principles and best practices should be applied on all pieces of the puzzle. This is one of the critical tasks!<br>So, let’s assume we have a .Net Core build that runs as part of a CodePipeline, as in example 2 above. However, after the build, we also want CodeBuild to generate the SQL migrations script, connect to the database then run the script. And to do this, we’ll need 2 useful tools:<br>- Jq: a json parser (to parse the database connection details from json)<br>- MySQL client (to connect to our MySQL database e.g. <a href="https://aws.amazon.com/rds/aurora/mysql-features/">Aurora</a>).</p><p>Here’s what the buildspec.yml should look like:</p><pre>version: 0.2<br>env:<br>  secrets-manager:<br>    SECRET: db-connection-secret<br>phases:<br>  install:<br>    runtime-versions:<br>      dotnet: 3.1<br>    commands:<br>      - apt-get update<br>      - apt-get install -y jq mysql-client<br>  pre_build:<br>    commands:<br>      - echo &quot;Getting Database details..&quot;<br>      - DBSERVER=$(echo $SECRET | jq -r &#39;.DBendpoint&#39;)<br>      - DBUser=$(echo $SECRET | jq -r &#39;.DBuser&#39;)<br>      - DBPassword=$(echo $SECRET | jq -r &#39;.DBpassword&#39;)<br>  build:<br>    commands:<br>      - echo &quot;CD into source folder..&quot;<br>      - cd src<br>      - echo &quot;Restore, Build, then Publish..&quot;<br>      - dotnet restore<br>      - dotnet build --no-restore<br>      - dotnet publish --no-restore --output outputDirectory<br>      - echo &quot;Generate migrations script..&quot;<br>      - dotnet ef migrations script -o migration.sql --idempotent<br>  post_build:<br>    commands:<br>      - echo &quot;Connecting to ${DBSERVER} &amp; running MySQL query..&quot;<br>      - mysql -h ${DBSERVER} -P 3306 -u ${DBUser} -p${DBPassword} mydatabase1 &lt; migration.sql<br>      - echo &quot;Done.&quot;<br>artifacts:<br>  base-directory: outputDirectory<br>  files:<br>    - &#39;**/*&#39;</pre><p>In the buildspec above, we retrieve our database connection secret from AWS Secrets Manager to our environment variables. This secret should have the connection details in json format. After that, we told CodeBuild to run .Net Core 3.1 and install jq and MySQL client. Once installed, we parse the connection details from our json secret in the environment variables. Then, we will restore, build, and publish .Net then generate the SQL migrations script. Post build, we will connect to the database using the parsed details and pass on the migration script to the database to run. When finished, like before, we will pass the build artifacts to CodePipeline.</p><blockquote>This CodeBuild project will need an IAM Role that has permissions to interact with Secrets Manager and CodePipeline. Also, this CodeBuild project will need to be able to connect to the database instance e.g. <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/vpc-support.html">connect within the VPC</a>.</blockquote><h4>7. Database operations.</h4><p>Same as in the previous example, we want to perform database operations somewhere in our CI/CD pipeline. Let’s say for example we have one development database instance, but we want our big engineering team to share it. We don’t want everyone to login to the database to create new schemas (databases) and forget deleting them when their work is done. We want to automate this process. We want a new schema to be created for each feature branch and dropped when the branch is merged.</p><p>This is not complicated, it saves time and ensures proper clean ups. We’ve done this for one of our big projects which had a distributed team across multiple offices and it was amazing. All what we had to do was setup our version control to trigger a job when a new branch is created or when a branch is merged. And when triggering, we pass the branch name and either “create” or “drop” as environment variables. Any modern version control with pipeline capabilities can <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/start-build.html">trigger CodeBuild through AWS CLI</a>.<br>For reference, here is what the trigger CLI command looks like, including the branch name and the action required, if we trigger from Bitbucket:</p><pre>aws codebuild start-build --project-name myProject --environment-variables-override &quot;[{\&quot;name\&quot;:\&quot;ACTION\&quot;,\&quot;value\&quot;:\&quot;create\&quot;},{\&quot;name\&quot;:\&quot;BRANCH\&quot;,\&quot;value\&quot;:\&quot;${BITBUCKET_BRANCH}\&quot;}]&quot;</pre><p>And, here’s what the buildspec.yml should look like:</p><pre>version: 0.2<br>env:<br>  secrets-manager:<br>    SECRET: db-connection-secret<br>phases:<br>  install:<br>    runtime-versions:<br>      dotnet: 3.1<br>    commands:<br>      - apt-get update<br>      - apt-get install -y jq mysql-client<br>  post_build:<br>    commands:<br>      - echo &quot;Getting Database details..&quot;<br>      - DBSERVER=$(echo $SECRET | jq -r &#39;.DBendpoint&#39;)<br>      - DBUser=$(echo $SECRET | jq -r &#39;.DBuser&#39;)<br>      - DBPassword=$(echo $SECRET | jq -r &#39;.DBpassword&#39;)<br>      - echo &quot;Define the action required..&quot;<br>      - |<br>        if [ ${ACTION} = &quot;create&quot; ]; then<br>          SQL_QUERY=&quot;CREATE DATABASE IF NOT EXISTS \`${BRANCH}\`;&quot;;<br>        elif [ ${ACTION} = &quot;drop&quot; ]; then<br>          SQL_QUERY=&quot;DROP DATABASE \`${BRANCH}\`;&quot;;<br>        else<br>          echo &quot;Action ${ACTION} is not allowed!&quot; &amp;&amp; exit 1;<br>        fi<br>  build:<br>    commands:<br>      - echo &quot;Connecting to ${DBSERVER} &amp; running MySQL Action..&quot;<br>      - mysql -h ${DBSERVER} -P 3306 -u ${DBUser} -p${DBPassword} -e &quot;${SQL_QUERY}&quot;<br>      - echo &quot;Done.&quot;</pre><p>Same as in the previous example, we parse our database connection details from Secrets Manager through the environment variables. After parsing the secret, we define the SQL command we want to run based on the incoming $ACTION environment variable whether create or drop. We also include the $BRANCH name in the command to match the schema name with. Once the SQL command is defined, we connect to the database and run the command.<br>As mentioned, this job can run to create and to drop schemas. The schema name will match your feature branch name, so make sure branch naming is limited to characters that are supported by your database engine. Otherwise, you can add logic in your script to check the branch name and convert the unsupported characters.</p><blockquote>This CodeBuild project only needs permissions to retrieve secrets from Secrets Manager, and network access to the database e.g. <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/vpc-support.html">through the VPC</a>.</blockquote><h4><strong>8. CloudFormation Packaging (e.g. Nested Stacks)</strong></h4><p>We often, if not always, use <a href="https://docs.aws.amazon.com/codepipeline/latest/userguide/tutorials-cloudformation.html">CodePipeline integration with CloudFormation</a> to deploy or update our stacks. This might be tricky if your CloudFormation stacks are organised in <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html">Nested Stacks</a>. What you would usually do to deploy manually is use <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/package.html">AWS CLI to package</a> the templates into one which you can deploy. Fear not, this is easy to replicate in a CI/CD pipeline too.</p><p>Here’s a buildspec.yml example:</p><pre>version: 0.2<br>env:<br>  variables:<br>    S3_BUCKET: myCloudformationBucket<br>    REGION: us-east-1<br>phases:<br>  build:<br>    commands:<br>      - echo &quot;Packaging CloudFormation nested stacks..&quot;<br>      - aws cloudformation package --region $REGION --template-file mainTemplate.yaml --s3-bucket $S3_BUCKET --output-template-file packaged.yml<br>      - echo &quot;Done.&quot;<br>artifacts:<br>  files:<br>    - packaged.yml<br>    - parameters/*.json</pre><p>Very straight forward, in the buildspec above, we defined the bucket and region we want to upload the nested templates to so we can package CloudFormation. Then, we ran the package command. As you can tell, this CodeBuild job passes the packaged.yml template along with json type parameter files as artifacts to the next deployment action in CodePipeline. You do not have to <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html">use parameters</a> or parameter files with CloudFormation, but it is a good practice so do it when it makes sense.</p><blockquote>This CodeBuild project will need permissions to write to the specified S3 bucket (for CloudFormation) as well as permissions to interact with CodePipeline.</blockquote><h4><strong>9. Source Code repository tagging</strong></h4><p>In some workflows, we’re required to tag the commit, in source control, which we have just deployed successfully to an environment. For example, after successfully deploying to Production, we want to tag the deployed commit back in source control with a prod tag.<br>To do this, CodeBuild will need a Git SSH key, which we will store in AWS Secrets Manager, and pass in through the environment variables.</p><p>Here’s what our buildspec.yml should look like:</p><pre>version: 0.2<br>env:<br>  variables:<br>    REPO: myReactProject<br>  secrets-manager:<br>    GITSSH: git-ssh-key<br>phases:<br>  pre_build:<br>    commands:<br>      - echo &quot;Parsing the SSH key..&quot;<br>      - echo $GITSSH &gt; ~/.ssh/id_rsa<br>      - chmod 400 ~/.ssh/id_rsa<br>      - echo &quot;Connecting to GitHub and cloning..&quot;<br>      - ssh -T git@github.com<br>      - git clone git@github.com:myWorkspace/${REPO}.git<br>      - cd ${REPO}<br>  build:<br>    commands:<br>      - echo &quot;Deleting old tag if exists..&quot;<br>      - git tag --delete prod<br>      - git push origin --delete prod<br>      - echo &quot;Tagging and pushing the tag..&quot;<br>      - git tag -a -f prod $CODEBUILD_SOURCE_VERSION<br>      - git push origin prod<br>      - echo &quot;Done.&quot;</pre><p>Above, we defined our environment variables, i.e. the GitHub repository name and a reference to the Git SSH key stored in AWS Secrets Manager. CodeBuild then will write the SSH key to the SSH folder, connect to GitHub, then clone the repository. Once cloned, we will remove the tag if it already exists, tag the commit we deployed then push to GitHub. In this scenario, we used the available environment variable CODEBUILD_SOURCE_VERSION which is the commit ID passed by CodePipeline <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html">as explained here</a>. If you don’t have the commit ID in the available variables, you can pass it with your build in a file.</p><blockquote>This CodeBuild project needs permissions to retrieve secrets from Secrets Manager and to interact with CodePipeline.</blockquote><p><strong>10. Deployment marking (e.g. NewRelic)</strong></p><p>One of the good practices to do post deployments is to mark the timeline of your monitoring system with the deployment time and version. This is a record that’ll help you see changes in your application’s performance and usage and correlate them with deployments. NewRelic, for example, allows you to record <a href="https://docs.newrelic.com/docs/apm/new-relic-apm/maintenance/record-monitor-deployments">deployments through the REST API</a>.</p><p>Below is an example buildspec.yml for this job:</p><pre>version: 0.2<br>env:<br>  secrets-manager:<br>    APP_ID: newrelic-app-id<br>    APIKey: newrelic-api-key<br>phases:<br>  build:<br>    commands:<br>      - echo &quot;Sending deployment mark to NewRelic..&quot;<br>      - curl -X POST &#39;https://api.newrelic.com/v2/applications/${APP_ID}/deployments.json&#39; -H &#39;X-Api-Key:${API_KEY}&#39; -i -H &#39;Content-Type:application/json&#39; -d &#39;{&quot;deployment&quot;:{&quot;revision&quot;:${CODEBUILD_SOURCE_VERSION},&quot;description&quot;:&quot;New deployment.&quot;}}&#39;<br>      - echo &quot;Done.&quot;</pre><p>This job simply sends a POST request to NewRelic using the APP ID and API Key retrieved from Secrets Manager. The POST request includes the required parameters including a revision and a description. We used CODEBUILD_SOURCE_VERSION or the commit ID as a revision in this example.</p><blockquote>Again, this CodeBuild project needs permissions to retrieve secrets from Secrets Manager and to interact with CodePipeline.</blockquote><h3>Let’s recap.</h3><p>In this post, we have listed the top 10 ways we utilise AWS CodeBuild, at <a href="https://tigerspike.com/"><strong>Tigerspike</strong></a>:<br><strong>1. Builds, ad-hoc.<br>2. Builds, part of a CodePipeline.<br>3. Builds, docker.<br>4. Unit testing.<br>5. Automation testing.<br>6. Database migrations.<br>7. Database operations.<br>8. CloudFormation Packaging (e.g. Nested Stacks)<br>9. Source Code repository tagging<br>10. Deployment marking (e.g. NewRelic)</strong></p><p>We all agree that every project has its own requirements and every CI/CD is unique. But when you have such a great and easy to use tool available for you, you might as well make smarter use of it. <strong><em>Protect your secrets, automate jobs, reduce chances of error, and save time and effort.</em></strong></p><p>Have you used CodeBuild in other smart ways?<br>If you have, share your use in the responses below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22a8ee0d9302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD: Automate server builds with Packer and CodeBuild]]></title>
            <link>https://malsouli.medium.com/ci-cd-automate-server-builds-with-packer-and-codebuild-6cfa97fa1e79?source=rss-61575db35d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cfa97fa1e79</guid>
            <category><![CDATA[codebuild]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[packers]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Moha Alsouli]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 07:29:52 GMT</pubDate>
            <atom:updated>2020-03-27T07:29:52.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*Oyg0R-NYkLJOWZ4ohxCGCg.png" /></figure><p><strong><em>Ever wondered how to guarantee consistency between multiple environments and servers? Here is how.</em></strong></p><p>At Tigerspike, we thrive on innovation.<br>#our_inquisitive_nature_brings_insight_and_innovation</p><p>One of the tricks our teams have started using a couple of years ago now is what is commonly known as the <strong>Golden Image</strong>.</p><h3>What is a Golden Image?</h3><p>The concept is simple. Launch a server, patch and configure it, deploy your application on it, then take a snapshot or image of it. Once tested and approved, this image becomes the <strong><em>Golden Image</em></strong> which you can use to launch servers, one or hundreds of them if you want, in multiple environments, and they’ll always be the same. Do the same for each release, and you will be able to deploy and rollback to whichever image you prefer.<br><strong><em>Reliability and DR ticked!</em></strong></p><h3>So, how do you create Golden Images?</h3><p>There are many ways to actually achieve this, but my favourite is using <a href="https://packer.io/">Hashi Corp’s Packer</a>.</p><p>Packer is an open source build tool. It can create images from JSON templates. In a template, you’d define the base OS image and define the deployment scripts and configuration files. yes, that simple!</p><p>Packer can be installed on the fly, e.g. on managed build services such as <a href="https://aws.amazon.com/codebuild/">AWS CodeBuild</a>, or permanently, e.g. on on-prem build servers such as Jenkins. Check Packer’s download and install guide <a href="https://packer.io/downloads.html"><em>here</em></a>.</p><p><strong><em>So, let’s see an example:</em></strong></p><p>Let’s assume you have a website with a single index.html page. Every time you push an update to the page, you want to build a new image of your web server with Ubuntu 18.04 LTS image and the latest version of Apache.</p><p>In summary, besides your website file(s), you’ll need:<br>1. a Packer server template<br>2. a CodeBuild build script</p><p>Here is a simple Packer template, let’s call it <strong>webserver.json</strong>:</p><pre>{<br>    &quot;builders&quot;: [<br>        {<br>            &quot;type&quot;: &quot;amazon-ebs&quot;,<br>            &quot;region&quot;: &quot;ap-southeast-2&quot;,<br>            &quot;source_ami&quot;: &quot;ami-02a599eb01e3b3c5b&quot;,<br>            &quot;instance_type&quot;: &quot;t3.large&quot;,<br>            &quot;communicator&quot;: &quot;ssh&quot;,<br>            &quot;ssh_username&quot;: &quot;ubuntu&quot;,<br>            &quot;ami_name&quot;: &quot;Medium_Example_Linux_{{timestamp}}&quot;<br>        }<br>    ],<br>    &quot;provisioners&quot;: [<br>        {<br>            &quot;type&quot;: &quot;shell&quot;,<br>            &quot;inline&quot;: [&quot;sudo apt update&quot;,<br>            &quot;sudo apt install -y apache2&quot;,<br>            &quot;sudo rm -r /var/www/html/*&quot;,<br>            &quot;sudo echo &#39;ServerName example.com&#39; &gt;&gt; /etc/apache2/sites-available/000-default.conf&quot;]<br>        },<br>        {<br>            &quot;type&quot;: &quot;file&quot;,<br>            &quot;source&quot;: &quot;index.html&quot;,<br>            &quot;destination&quot;: &quot;/var/www/html/index.html&quot;<br>        }<br>    ]<br>}</pre><p>In the template above, we first defined <a href="https://packer.io/docs/builders/index.html">the Builder</a> then <a href="https://packer.io/docs/provisioners/index.html">the Provisioner</a>.</p><p>For the Builder, we defined <a href="https://packer.io/docs/builders/amazon-ebs.html">Amazon-EBS</a> type in Sydney region with t3.large instance type. Then, we specified the source AMI, which is the latest Ubuntu 18.04 LTS image provided by Canonical Ltd, and specified how to connect to it and how to name the created image afterwards.</p><p>Note, if you wish to always use the latest base AMI, you can use <a href="https://packer.io/docs/builders/amazon-ebs.html#source_ami_filter">source_ami_filter</a> directive instead of source_ami. Also, if you wish to give your AMIs cleaner names, use <a href="https://packer.io/docs/templates/engine.html#isotime-format-">isotime [FORMAT]</a>instead of timestamp.</p><p>For the Provisioner, first, we execute inline shell commands, then copy a file. The shell Provisioner installs latest Apache2, removes the default site files then adds a server name to the site’s configurations file. The file Provisioner simply copies a file, provided with the artifacts in our scenario, to a destination on the Builder.</p><p>The template above doesn’t include <a href="https://packer.io/docs/post-processors/index.html">Post-Processors</a> but check it out if you want to run processes after the image is created, e.g. produce Manifest for automated deployments, push to Docker registry, etc.</p><p>And, here is a simple CodeBuild script, by default it’s <strong>buildspec.yml</strong>:</p><pre>version: 0.2<br>phases:<br>  install:<br>    commands:<br>      - curl -qL -o packer.zip <a href="https://releases.hashicorp.com/packer/1.5.5/packer_1.5.5_linux_amd64.zip">https://releases.hashicorp.com/packer/1.5.5/packer_1.5.5_linux_amd64.zip</a><br>      - unzip packer.zip<br>  build:<br>    commands:<br>      - ./packer build webserver.json</pre><p>The above build script simply instructs CodeBuild to download Packer (v. 1.5.5 is the latest at the time of writing) and unzip Packer package then run packer build command using the template we provided earlier.</p><p><strong>You now have an index.html page, a Packer template, and a build script for CodeBuild. </strong>Next, push these files to a code repository (or upload to an S3 bucket) and configure a CodeBuild project to read from this source and run a build. Voila, when the build is done, you will see a new AMI created by Packer.</p><p>If you’re not familiar with setting up CodeBuild, check <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/getting-started.html">this simple tutorial</a>. Also, make sure CodeBuild has enough IAM permissions for EC2.</p><p>That’s it folks!</p><p>The Golden Image is very useful for launching any number of servers, 1 or 100s. We used this to deploy a huge stack of 60 servers for a big client once as well as stacks of 2 servers only for much smaller clients.</p><p>Tip: think of the power you would have using Packer and <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html">Auto Scaling Groups</a> were you could define a standard Launch Configuration and let the Auto Scaling Group do the work for you healing instances and scaling up and down when needed.</p><p>Tip2: you can extend this magic by automating your deployments. For example, after creating an AMI, CodeBuild can update your CloudFormation Stacks or Auto Scaling Groups and replace your running instances with new ones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cfa97fa1e79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Secrets Manager: Create and Rotate secrets automatically]]></title>
            <link>https://malsouli.medium.com/aws-secrets-manager-create-and-rotate-secrets-automatically-36719faa7e4f?source=rss-61575db35d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/36719faa7e4f</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-secrets-manager]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Moha Alsouli]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 01:15:08 GMT</pubDate>
            <atom:updated>2019-11-25T01:18:03.105Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Do you want to automate creating secrets to fully secure them away from humans? Or do you have a requirement to rotate database passwords regularly and wonder if you can automate it? It’s all possible with Secrets Manager. Let me take you through it step by step.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*s768RjN1t4XZ_pY4evOEng.png" /></figure><p>As mentioned in my previous article, Security is a top priority at <strong>Tigerspike</strong> alongside Improving People’s Lives Through Technology.</p><p>One of the cool tricks our DevOps team is using to secure and simplify management of our databases credentials on AWS is using <a href="https://aws.amazon.com/secrets-manager/">AWS Secrets Manager</a> to <strong>auto-create</strong> and <strong>auto-rotate</strong> credentials.</p><p><em>Let’s see </em><strong><em>how easy is using AWS Secrets Manager</em></strong><em>.<br></em>The below examples are snippets of <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-formats.html">YAML formatted CloudFormation templates</a>.</p><h4>Create an encrypted username and password</h4><pre>MyRDSSecret:<br>    Type: AWS::SecretsManager::Secret<br>    Properties:<br>        Name: &#39;ProdDBSecret&#39;<br>        Description: &#39;Secret with dynamically generated password.&#39;<br>        GenerateSecretString:<br>            RequireEachIncludedType: True<br>            SecretStringTemplate: &#39;{&quot;username&quot;: &quot;MyDBAdmin&quot;}&#39;<br>            GenerateStringKey: &#39;password&#39;<br>            PasswordLength: 25<br>            ExcludePunctuation: True</pre><p><em>Voila! </em>The above CloudFormation snippet creates a secret containing a username and password. The username is provided in the template, while the password is auto generated with the properties defined, i.e. 25 characters long, excludes all punctuation marks and must include a mix of lowercase letters, uppercase letters and numbers. Easy.</p><p>You can also be more creative with the created secret following your application requirement. For example, you can include punctuation marks and instead exclude certain characters that your database or application do not support such as &quot; quote marks, / slashes or \ backslashes. See Secrets Manager Secret <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-secretsmanager-secret.html">syntax documentation for more</a>.</p><p>The created secret will be available for you in Secrets Manager console (if you have the right IAM permissions) but can also be referenced dynamically within your CloudFormation template to create and configure an RDS instance or cluster with it. <em>Read on.</em></p><h4>Dynamically configure a database with the created secret</h4><pre>MyRDSInstance:<br>    Type: AWS::RDS::DBInstance<br>    Properties:<br>        AllocatedStorage: 20<br>        DBInstanceClass: db.m5.large<br>        Engine: mysql<br>        MasterUsername: !Join [&#39;&#39;, [&#39;{{resolve:secretsmanager:&#39;, !Ref MyRDSSecret, &#39;:SecretString:username}}&#39; ]]<br>        MasterUserPassword: !Join [&#39;&#39;, [&#39;{{resolve:secretsmanager:&#39;, !Ref MyRDSSecret, &#39;:SecretString:password}}&#39; ]]<br>        BackupRetentionPeriod: 14<br>        DBInstanceIdentifier: &#39;prod-db-with-rotation&#39;</pre><pre>SecretRDSInstanceAttachment:<br>    Type: AWS::SecretsManager::SecretTargetAttachment<br>    Properties:<br>        SecretId: !Ref MyRDSSecret<br>        TargetId: !Ref MyRDSInstance<br>        TargetType: AWS::RDS::DBInstance</pre><p>The above CloudFormation snippet shows how to create a simple RDS MySQL instance and configure it with the master username and password credentials created by Secrets Manager. The !Join function appends the values to into a single value while the !Ref function is used assuming all resources are in the same template. If the database resource is not in the same template as the secret earlier, you can reference the friendly name of the secret instead such as &#39;{{resolve:secretsmanager:ProdDBSecret:SecretString:password}}&#39;. And once created, the Target Attachment will ensure the final link between the secret and the database is complete. See <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#dynamic-references-secretsmanager">this doc to learn more on using dynamic references </a>to Secrets Manager Secrets. And see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-secretsmanager-secrettargetattachment.html">this doc to read more about Secrets Manager Secret Attachment</a>.</p><p><em>At this stage, if you don’t need to rotate your secrets and just wonder how to pass the automated secrets to your apps, jump the next section. Otherwise, continue reading to learn how to rotate secrets and improve the security of your apps.</em></p><h4>Regularly rotate the created secret</h4><p>As password rotation strategies differ between databases, AWS offers multiple rotation Lambda function templates that you can use out of the box or tweak to fit your needs. Take a look <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_available-rotation-templates.html">at this doc to see the available templates</a>.</p><p>For our example, we will use the RDS MySQL Master User rotation function. Here’s how to simply deploy it as a Serverless app:</p><pre>AWSTemplateFormatVersion: 2010-09-09<br>Transform: AWS::Serverless-2016-10-31<br>Description: &quot;This is an AWS Serverless Application Model template for Secret Rotation Lambda&quot;<br>Resources:<br>    MyRotationServerlessApp:<br>        Type: AWS::Serverless::Application<br>        Properties:<br>            Location:<br>                ApplicationId: &#39;arn:aws:serverlessrepo:us-east-1:297356227824:applications/SecretsManagerRDSMySQLRotationMultiUser&#39;<br>                SemanticVersion: 1.1.0<br>            Parameters:<br>                endpoint: !Sub &#39;<a href="https://secretsmanager.${AWS::Region}.amazonaws.com&#39;">https://secretsmanager.${AWS::Region}.amazonaws.com&#39;</a><br>                functionName: SecretsManagerMySQLRotationFunction</pre><p>The above Serverless Application Model “SAM” template will simply deploy the rotation Lambda function in your account with the IAM role it needs using the AWS application referenced in ApplicationId. See <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-deploying.html">here if you’re not familiar with using or deploying AWS SAM templates</a>.</p><p>Once the function is created, you can then use it to rotate your supported secrets. For example, to do so, take a note of the created Lambda function’s ARN and add the below to the CloudFormation template where your secret and secret attachment are:</p><pre>MySecretRotationSchedule:<br>    Type: AWS::SecretsManager::RotationSchedule<br>    DependsOn: SecretRDSInstanceAttachment<br>    Properties:<br>        SecretId: !Ref MyRDSSecret<br>        RotationLambdaARN: !Sub &#39;arn:aws:lambda:<a href="https://secretsmanager.${AWS::Region}.amazonaws.com&#39;">${AWS::Region}</a>:${AWS::AccountId}:function:SecretsManagerMySQLRotationFunction&#39;<br>        RotationRules:<br>            AutomaticallyAfterDays: 30</pre><p><em>Voila!</em> The above snippet will schedule a 30 days rotation for your secret using the rotation function created earlier. See <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-secretsmanager-rotationschedule.html">here to learn more about the Rotation Schedule syntax</a> or <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html">read here for more about Secrets Rotation</a>.</p><p>And just like that, with a few lines of code, we have:</p><ul><li>Created a Secret consisting of a Username and Password</li><li>Configured an RDS database instance with the secret</li><li>Attached the secret to the database to complete the link</li><li>Created a Secret Rotation Lambda function</li><li>Used the Secret Rotation Lambda function to schedule a rotation</li></ul><h3>What’s next?</h3><p>You should be satisfied by now how we’ve automated the entire process of managing a secret, but you might be wondering <strong><em>how would you configure your app or service to use this secret?!</em></strong></p><p>Well, it’s not that complicated. There are many ways to automate the configuration of your app. The easiest are:</p><ul><li>Make use of AWS CLI or SDK in your code to retrieve the secrets.<br>This is explained <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_retrieve-secret.html">in this AWS doc</a>, but you can also see Sample Code in Secrets Manager console when you browse your secrets, which looks like this in the console:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*R5FXNgk_fu0vGPejCY_xvQ.png" /></figure><ul><li>Use Environment Variables to pass these secrets to your application.<br>Take a <a href="https://medium.com/@malsouli/securing-your-credentials-and-environment-variables-with-aws-46297f83aed8">look at my earlier blog post</a> which highlights how to pass Environment Variables to an app, otherwise <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#dynamic-references-secretsmanager">see this AWS doc</a> which explains it in details.</li></ul><h4>That’s it folks!</h4><p>Easy and Secure secret management with no human or manual handling needed. <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">See here to learn more about Secrets Manager</a>, or <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html">see here to read more on Secrets Rotation</a> and supported services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36719faa7e4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing your credentials and environment variables with AWS]]></title>
            <link>https://malsouli.medium.com/securing-your-credentials-and-environment-variables-with-aws-46297f83aed8?source=rss-61575db35d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/46297f83aed8</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[appsettings]]></category>
            <category><![CDATA[aws-system-manager]]></category>
            <category><![CDATA[parameter-store]]></category>
            <dc:creator><![CDATA[Moha Alsouli]]></dc:creator>
            <pubDate>Wed, 23 Oct 2019 05:29:06 GMT</pubDate>
            <atom:updated>2019-11-25T00:44:10.243Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Access management, secure storage, key rotation and managed encryption are as easy as ticking boxes since we migrated our hosting and workloads to AWS!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*hKOmSRZIQY377o-zFuE8QA.jpeg" /></figure><p>At Tigerspike, Security is a top priority alongside Improving People’s Lives Through Technology. And when we say “People”, we mean people who are benefiting from the digital solutions we bring as well as our people who put these solutions together.</p><p><strong>One of</strong> the security best practices we enforce is using <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html">AWS Systems Manager Parameter Store</a> to store any sensitive app configurations. We can then either use AWS SDK to retrieve these secure strings, pass them directly as environment variables for the app or compile them with AWS CLI on boot depending on the application. Let’s dig deeper into those three methods and see how easy it is to secure your app’s credentials.</p><p><strong>First and foremost</strong>, check out how to <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-su-organize.html">create and organise your Parameter Store into hierarchies</a>. Once you’re familiar with that, let’s assume you have two secure parameters one is /coolapp/dev/database/password and the other is /coolapp/prod/database/password. This hierarchy is just an example and of course you can organise whichever way makes sense to you. Sorting by app then environment then service makes it easier for me to find parameters in accounts that host multiple apps.</p><h4><strong><em>Now, let’s look at using AWS SDK to retrieve these secrets</em></strong></h4><p>AWS SDK is available for most, arguably all, the commonly used programming languages out there. Find the list here.<br>So, with the SDK, you can make calls from your app to get any secret from the Parameter Store whenever needed. For example, for Python:</p><pre>import os<br>import boto3<br>ENV_NAME = os.environ[&#39;ENV&#39;]<br>client <strong>=</strong> boto3<strong>.</strong>client(&#39;ssm&#39;)<br>DB_PASS=client.get_parameters_by_path(Path=&#39;/coolapp/&#39;+ENV_NAME+&#39;/database/password&#39;,WithDecryption=True)[&#39;Parameters&#39;][0][&#39;Value]</pre><p>This script above reads the environment name from the environment variables available for the runtime (so we can read for dev as well as prod dynamically) then calls Systems Manager to get the DB Password parameter by its path. Simple!<br>More on this <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm.html#SSM.Client.get_parameters_by_path">here for Python</a>, <a href="https://docs.aws.amazon.com/sdkfornet/v3/apidocs/index.html?page=SSM/MSSMGetParameterGetParameterRequest.html">here for .Net</a>, and <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SSM.html#getParametersByPath-property">here for JavaScript</a>.</p><h4><strong><em>Next, let’s look at passing these secrets as environment variables directly</em></strong></h4><p>Most of the commonly used programming languages support the OS (or runtime)’s environment variables as configurations provider. <a href="https://docs.python.org/3/library/os.html#os.environ">Python</a> or <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.0#environment-variables-configuration-provider">.Net Core</a> for example. So, to utilise this feature properly, configure your AWS resources to feed environment variables directly from SSM. The environment variables configuration is available to many AWS services including ECS Tasks, Lambda Functions, CodeBuild Projects, and some more. And if it’s not available through the console, it’s almost certainly available through smarts and the use of CloudFormation intrinsic functions. For ECS Tasks for example, you can define the following which will make the secret available in the container as an environment variable:</p><pre>Task:<br>  Type: AWS::ECS::TaskDefinition<br>  Properties:<br>    …<br>    ContainerDefinitions:<br>      …<br>      Environment:<br>        -Name: ASPNETCORE_ENVIRONMENT<br>        Value: !Ref pEnvName<br>      Secrets:<br>        -Name: DatabaseSettings__Password<br>        ValueFrom: !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/coolapp/${pEnvName}/database/password</pre><p>How easy was that?!<br>Check here <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html">how to specify sensitive data</a> for your ECS containers.<br>And check here <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html">how to use dynamic references</a> in CloudFormation in general.</p><p>Now, what can you do if your application is written in a language that doesn’t support environment variables as a configuration provider or if the host you’re running your application on can’t take environment variables dynamically like the above?</p><h4><strong><em>Let’s look at using AWS CLI</em></strong></h4><p>With AWS CLI, you can write a custom script that runs first thing when your instance initialise. This script should simply get the required parameters then either write them to the app configurations file or export them into environment variables if the app supports. Here’s an example for a Bash script that we can use to get an entire secrets file from the Parameter Store and write it to a local file before starting the application:</p><pre>aws ssm get-parameter -name /coolapp/dev/secret -with-decryption &gt; response<br>cat response | jq ‘.Parameter.Value’ | jq ‘.|fromjson’ &gt; secret.json</pre><p>Using this concept, we were able to write a Powershell script for one of our recent builds that has to run on .Net Framework which rewrites the entire web.env.config XML file before running the infamous XML transformation with the wb.config. You get the gist. We didn’t have to store the secrets in the codebase anymore.<br>Here is more on <a href="https://aws.amazon.com/cli/">AWS CLI</a> and <a href="https://aws.amazon.com/powershell/">AWS Tools for Powershell</a>.<br>And here is <a href="https://docs.aws.amazon.com/cli/latest/reference/ssm/get-parameter.html">the Get-Parameter</a> CLI command and <a href="https://docs.aws.amazon.com/cli/latest/reference/ssm/get-parameters-by-path.html">Get-Parameters-By-Path</a> if you want to compile values from different parameters.</p><h4><strong>What else to consider?</strong></h4><p>When working with Systems Manager Parameter Store, consider restricting your IAM policies to parameters by path, or part of the path. E.g. give access to arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/coolapp/dev/* only to your Dev instances and resources. This will guarantee keeping your production parameters secure from the your Dev and will also ensure your Dev apps will not have access to your production database, for example, by accident due to wrong use of the CLI or SDK or mistyping of a parameter path. <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-access.html">More on this here</a>.</p><h4>That’s it folks!</h4><p>It’s never been this easy and fun to hide your secrets. Pick and tweak for your application.</p><p><em>Edit: </em><a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html"><em>this User Guide</em></a><em> has pretty good links to Learn More about Parameter Store, Getting Started, Walkthroughs, and Use with AWS KMS.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46297f83aed8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying via AWS OpsWorks and Octopus]]></title>
            <link>https://malsouli.medium.com/deploying-via-aws-opsworks-and-octopus-767c3fd2fa14?source=rss-61575db35d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/767c3fd2fa14</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[opsworks]]></category>
            <category><![CDATA[octopus]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Moha Alsouli]]></dc:creator>
            <pubDate>Fri, 04 Oct 2019 06:29:21 GMT</pubDate>
            <atom:updated>2019-10-04T10:49:00.328Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I found this post in my old notes.. that I was planning to publish… 3 years ago! Still relevant though, so here it is slightly edited if anyone is looking for tips in this topic:</em></p><p>At Tigerspike, We Solve Problems in Remarkable Ways.</p><p>One of our goals, as a global digital products company, is to bring the best user experience and that includes bringing the best experience to our engineers.</p><p>So, for one of our builds a few years ago, the client wanted to host and manage a set of Windows servers, running a .Net API, on AWS OpsWorks.</p><p><a href="https://aws.amazon.com/opsworks/stacks/">AWS OpsWorks Stacks</a> is a great service that takes care of servers configuration management and automates various tasks you would traditionally need an entire support team to do, such as auto healing, provisioning new resources and application deployments.</p><p>Of course, we sketched an HLD, proposed to the client, got approvals and in no time we provisioned the bespoke hosting environment. The usual stuff.</p><p>What was tricky though was the requirement to:<br>- use <a href="https://jenkins.io/">Jenkins</a> for CI, and<br>- use <a href="https://octopus.com/">Octopus</a> for CD.<br>I won’t get into what was the business requirement, but we all know Jenkins is pretty solid (and popular) automation server and Octopus Deploy makes lifecycles and release management a breeze with its neat UI so why not?!</p><p>Anyway, how did we link it all together?</p><p>Well, it’s easy! The repo triggers a Jenkins job, Jenkins builds and pushes to Octopus, then Octopus pushes to AWS according to the parameters.<br>Something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*qBwMWB55rVfWPuBawsRYEg.jpeg" /></figure><p>Getting the code repository to trigger a Jenkins job isn’t magic nor getting Jenkins to build and test on an EC2 Spot Instance then triggering an Octopus project. There are plugins, docs and whitepapers for that.</p><p>What’s custom though is automating Octopus to deploy via AWS OpsWorks.<br>It’s not tricky, it just took a couple of hours to create a custom Octopus step template with a Powershell script utilising AWS CLI to do the work. And before I show you the code snippet, let me highlight this workflow again:<br>- Developer pushes code to code repository (e.g. Bitbucket/Gitlab);<br>- Code repo triggers a Jenkins job;<br>- Jenkins test the .Net project then build, package and push to Octopus Deploy;<br>- Octopus unpacks in a temporary directory then zips the raw files in a .zip folder (using your custom scripts, default step template or templates from the <a href="https://library.octopus.com/listing">community library</a>);<br>- Octopus then uploads the zipped package to an S3 bucket (again using your custom scripts or templates from the <a href="https://library.octopus.com/listing">community library</a>);<br>- Finally, Octopus triggers OpsWorks deployment using AWS CLI, and check until a result is returned (using the custom script below).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f8227c3df7e5de420acd2ccc0c01ff3/href">https://medium.com/media/2f8227c3df7e5de420acd2ccc0c01ff3/href</a></iframe><p>Of course, it’d be better to create a custom Step Template in your Octopus server with this script and the required parameters so you can reuse for multiple stacks and projects, especially if you have multiple environments, e.g. Dev, UAT and Prod, and you want to use the project’s variables to dynamically get the parameters and deploy.</p><p>And as you may have guessed, you will need an IAM user for Octopus, with permissions to write to the S3 bucket and permissions to create and check deployments in the OpsWorks stacks you’re deploying to.</p><p>Hope that helped you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=767c3fd2fa14" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>