<?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[Pablo Perez - Medium]]></title>
        <description><![CDATA[DevOps - Medium]]></description>
        <link>https://medium.com/pablo-perez?source=rss----e6f453ad5d9d---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Pablo Perez - Medium</title>
            <link>https://medium.com/pablo-perez?source=rss----e6f453ad5d9d---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:45:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/pablo-perez" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Multi Account EKS with ArgoCD in Terraform &bash.]]></title>
            <link>https://medium.com/pablo-perez/multi-account-eks-with-argoscd-in-terraform-bash-99ad229ae73c?source=rss----e6f453ad5d9d---4</link>
            <guid isPermaLink="false">https://medium.com/p/99ad229ae73c</guid>
            <dc:creator><![CDATA[Pablo Perez]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 19:19:14 GMT</pubDate>
            <atom:updated>2025-07-24T19:19:35.725Z</atom:updated>
            <content:encoded><![CDATA[<h4>Multi Account setup in Terraform</h4><p>Having our terraform files in a Remote Git repo (You can find a proper .<a href="https://github.com/hashicorp/learn-terraform-provision-eks-cluster/blob/main/.gitignore">gitignore </a>file in order to not push things like .tfstate files) and the tfstate file in our <a href="https://developer.hashicorp.com/terraform/language/settings/backends/s3">S3 bucket along dynamodb state locking</a>, while working with vscode connected to an EC2 instance in the tool account made the experience of working with different AWS accounts quite enjoyable.</p><p>By creating a role with the required permissions on each AWS target account, let’s say dev, stg and prod, where it allows our Terraform EC2 instance profile role to execute required actions, we can just use the Terraform providers set for each target.</p><p>{&quot;Version&quot;: &quot;2012-10-17&quot;,&quot;Statement&quot;: [{&quot;Effect&quot;: &quot;Allow&quot;,&quot;Principal&quot;: {&quot;AWS&quot;: &quot;arn:aws:iam::&lt;ToolAccountID&gt;:role/terraformip&quot;},&quot;Action&quot;: &quot;sts:AssumeRole&quot;}]}</p><p>So once all the above is setup we proceed to create Terraform workspaces as it’s the best practice when working with multi account AWS environments and we set the proper roles to be assumed as outlined by the official documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*vR3byJR0u6TfjRjY.png" /></figure><h4>Deploying base resources on dev and stg accounts</h4><p>Terraform workspaces allow to deploy the same resources for several AWS accounts , you don’t need to repeat the block of code for every provider if you use a single workspace. By having the same terraform templates we will apply them on each selected workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*Ro4uUKyNzUSNXmnc.png" /></figure><p>At the beginning I was reluctant to use Terraform registry modules for the VPC and other resources, as it’s something I have no control under the hood, however, the same happens with Python libraries or AWS SAM transformations.</p><p>We need to take care of the module version and what terraform versions <a href="https://github.com/terraform-aws-modules/terraform-aws-vpc/blob/master/versions.tf">does it requires</a>, furthermore we need to be familiar to <a href="https://developer.hashicorp.com/terraform/cli/commands/force-unlock">force unlock</a> the terraform state when plan requires.</p><p>Creating a VPC module from scratch is quite laborious, you need to define the NAT gateways, routes and routing tables, match values with count function for subnets etc… and implement things fast is important, however, I tried to do it in that way to get more familiar of how the registry modules are built and why do they need the variables they ask, like the EKS cluster tags for the subnets, etc.</p><p>We just do interpolation for the workspace where we plan and apply, the rest it’s basically at the hashicorp docs provide in their <a href="https://github.com/hashicorp/learn-terraform-provision-eks-cluster/blob/main/vpc.tf">example</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*FCTWuaHT3QQIAA0f.png" /></figure><p>We apply in parallel both accounts terraform plans with &amp; launching subshell background jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WK_aCyDNWzzJfj9u.png" /></figure><p>And once everything is deployed on both workspaces/AWS accounts we register argocd on both EKS clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tJFXr1PMM3OJJPmp.png" /></figure><p>In the automation bear in mind it has to sleep 120 more or less to ensure the argocd-server login success, enough time for load balancer and the service to be ready.</p><p>There’s one caveat to make the classic load balancer to register with the EKS managed node group, otherwise it won’t expose argocd-server.</p><p>The Terraform registry module eks-cluster for some reason add an extra tag to the security group of the managed eks node group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TF5xqVfNxqly7SoF.png" /></figure><p>We have to specify within the module that we don’t want any tags on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*0EKenMRjAg83Mpd_.png" /></figure><p>so by assuming role credentials for each account, after register argocd we login on each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*pQTySwDV85_STutL.png" /></figure><p>Load balancer is public exposed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZUQnW_LKUis4z5K_.png" /></figure><p>we script the destruction in parallel , we need to delete the k8s service before invoke the terraform destroy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*ZfImwfT4UDkaAC3k.png" /></figure><p>You just need to leave the roles to be assumed on the target accounts on variables.tf and pass account number for each in the argoscd.sh and destroy.sh scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*Ra2HpN53fH3JBLNy.png" /></figure><p><a href="https://github.com/pabloperfer/EKSCICDTerraform.git">Git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99ad229ae73c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pablo-perez/multi-account-eks-with-argoscd-in-terraform-bash-99ad229ae73c">Multi Account EKS with ArgoCD in Terraform &amp;bash.</a> was originally published in <a href="https://medium.com/pablo-perez">Pablo Perez</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚙️ JENKINS CONTROLLER PERFORMANCE: THREADS & HEAP MEMORY ⚙️]]></title>
            <link>https://medium.com/pablo-perez/%EF%B8%8F-jenkins-controller-performance-threads-heap-memory-%EF%B8%8F-798c39929731?source=rss----e6f453ad5d9d---4</link>
            <guid isPermaLink="false">https://medium.com/p/798c39929731</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[heap-memory]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Pablo Perez]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 19:04:01 GMT</pubDate>
            <atom:updated>2025-06-09T20:55:11.990Z</atom:updated>
            <content:encoded><![CDATA[<p>1. Threads and heap memory drive performance</p><p>Threads schedule builds, power the web UI, and execute plugin logic.<br>The heap is the memory space where Jenkins stores the data those threads need.<br>If either resource is exhausted, the controller slows dramatically — users see UI freezes, time-outs, etc..</p><p>2. Garbage Collection (GC) is automatic, but not free</p><p>When the heap stays above 80 % for five minutes, GC has almost no free space; pauses grow longer.<br>When Full GC pauses add up to more than 5 % of total uptime, Jenkins is frozen one second out of every twenty.<br>The fix is usually a larger heap or fewer memory-hungry plugins, not just more CPU.</p><p>3. Adding threads is not a shortcut to speed</p><p>Threads consume memory and CPU.<br>Increasing thread pools without understanding the workload can raise contention and make performance worse.<br>First identify what blocks existing threads (slow plugins, disk I/O, external calls). Add threads only when profiling shows genuine starvation and spare CPU capacity.</p><p>EARLY WARNING SIGNS</p><p>UI clicks freeze, then respond in bursts → thread-pool saturation <br>Heap usage stays &gt; 85 % for several minutes → memory leak or heap too small<br>GC pauses &gt; 200 ms or frequent Full GCs → fragmented heap; GC struggling to free space</p><p>MEASURE RISK BEFORE FIRES START</p><p>Heap used &gt; 80 % for 5 min — GC has too little room, pauses lengthen.<br>Full-GC time &gt; 5 % of runtime — Jenkins is frozen long enough for users to notice stalls and time-outs.</p><p>VERIFY HEADROOM WITH CONTROLLED LOAD TESTS</p><p>Replay realistic traffic (UI + API) at 1×, 2×, and 4× current peak using any modern load-testing tool.<br>Observe heap usage, GC time, live thread count, and CPU utilization while the test runs.<br>Your safe capacity is the highest load that keeps heap &lt; 80 % and Full-GC &lt; 5 %. Re-run after every major Jenkins or plugin upgrade.</p><p>FIXES THAT WORK</p><p>Right-size the heap (-Xmx 16–24 GB for large environments) and enable G1GC → shorter, less frequent GC pauses.<br>Update or remove blocking plugins → fewer stuck threads and lower memory use.<br>Rotate and compress old build logs → smaller heap footprint, less GC pressure.<br>Run a quick load test after every Jenkins or plugin upgrade → catch thread/heap regressions before they reach production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=798c39929731" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pablo-perez/%EF%B8%8F-jenkins-controller-performance-threads-heap-memory-%EF%B8%8F-798c39929731">⚙️ JENKINS CONTROLLER PERFORMANCE: THREADS &amp; HEAP MEMORY ⚙️</a> was originally published in <a href="https://medium.com/pablo-perez">Pablo Perez</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Helm Charts: A Typical Helm Chart for a Microservice]]></title>
            <link>https://medium.com/pablo-perez/writing-helm-charts-a-typical-helm-chart-for-a-microservice-ac065197bd44?source=rss----e6f453ad5d9d---4</link>
            <guid isPermaLink="false">https://medium.com/p/ac065197bd44</guid>
            <category><![CDATA[helm]]></category>
            <dc:creator><![CDATA[Pablo Perez]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 20:35:58 GMT</pubDate>
            <atom:updated>2025-06-22T20:46:22.045Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Writing Helm Charts: A Typical Helm Chart for a Microservice</strong></p><p>Most microservice Helm charts include:</p><p>* Chart.yaml: Chart name and version (metadata).</p><p>* values.yaml: Default configuration for things you want to customize (container image, environment variables, ports, replicacount, etc).</p><p>* deployment.tpl: The main workload (usually a Deployment or StatefulSet).</p><p>* service.tpl: To expose your app within the cluster or to the outside.</p><p>* ingress.tpl: For HTTP(S) routing from outside.</p><p>* configmap.tpl: For non-sensitive configuration data.</p><p>* secret.tpl: For sensitive data.</p><p>* \_helpers.tpl: Template helpers (see below).</p><p><strong>Templates and Variables</strong></p><p>Helm templates are regular Kubernetes YAMLs, but you can inject variables from values.yaml. For example, in the deployment template:</p><p>` image: “{{ .Values.image.repository }}:{{ .Values.image.tag }}”</p><p>replicas: {{ .Values.replicaCount }} `</p><p>You can override anything in values.yaml at deploy time:</p><p>` helm install myapp ./helm-chart — set image.tag=prod `</p><p><strong>Don’t Store Secrets in Plaintext</strong></p><p>Never put real passwords or API keys in values.yaml or commit them to your repository.</p><p>Helm treats everything in values.yaml as plain text, and anyone with access to your repo or release history can see it.</p><p>Best practices:</p><p>* Use external secrets management tools like Sealed Secrets, External Secrets Operator, or your cloud provider’s secretmanager.</p><p>* Alternatively, inject secrets at deployment time with your CI/CD system, using encrypted variables or files that are not checked into source control.</p><p><strong>What Is \_helpers.tpl and Why Use It?</strong></p><p>The \_helpers.tpl file defines reusable template snippets(“helpers”), mainly for generating names and labels consistently across your resources.</p><p>For example</p><p>` {{- define “sample-node-app.fullname” -}}</p><p>{{- printf “%s-%s” .Release.Name .Chart.Name | trunc 63 | trimSuffix “-” -}}</p><p>{{- end }} `</p><p>You call this helper from any template like:</p><p>` metadata: name: {{ include “sample-node-app.fullname” . }} `</p><p>Why is this important?</p><p>* It enforces a naming pattern, which helps with upgrades,monitoring, and cleanup.</p><p><strong>Conditional Resources</strong></p><p>Use conditionals to only create resources when needed. Forexample, only deploy an Ingress if enabled:</p><p>{{- if .Values.ingress.enabled }} # ingress spec here {{- end }} `</p><p><strong>Upgrading and Releasing</strong></p><p>Make changes in values.yaml or templates, then run:</p><p>helm upgrade myapp ./helm-chart -f custom-values.yaml — atomic</p><h4>Why use — atomic?</h4><p>The — atomic flag ensures that if the upgrade fails for anyreason, Helm will automatically roll back to the previous release.This helps you avoid leaving your application in a broken or partialstate. It’s recommended for production upgrades.</p><p><a href="https://lnkd.in/eDpHWubB">https://lnkd.in/eDpHWubB</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac065197bd44" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pablo-perez/writing-helm-charts-a-typical-helm-chart-for-a-microservice-ac065197bd44">Writing Helm Charts: A Typical Helm Chart for a Microservice</a> was originally published in <a href="https://medium.com/pablo-perez">Pablo Perez</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Config custom rule for enabling in multiple accounts EKS Logging.]]></title>
            <link>https://medium.com/pablo-perez/aws-config-custom-rule-for-enabling-in-multiple-accounts-eks-logging-c3508c120218?source=rss----e6f453ad5d9d---4</link>
            <guid isPermaLink="false">https://medium.com/p/c3508c120218</guid>
            <category><![CDATA[config]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[eventbridge]]></category>
            <dc:creator><![CDATA[Pablo Perez]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 23:05:15 GMT</pubDate>
            <atom:updated>2022-12-23T23:05:15.608Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using AWS SSM, Eventbridge, CloudFormation StackSets, Lambdas and bash.</h3><p>Currently AWS Config only provides two AWS Managed rules for AWS EKS, these are eks-endpoint-no-public-access and eks-secrets-encrypted, so it’s a good opportunity to create custom config rule that checks if control plane logging is enabled for our EKS clusters and if not it will enable it.</p><p>We’ll use the <a href="https://github.com/awslabs/aws-config-rdk#getting-started">RDK</a>, the AWS Config Rules Development Kit for the custom rule .</p><p>rdk create eks-no-logging --runtime python3.9 --resource-types AWS::EKS::Cluster</p><p>The above will create the boilerplate for a lambda function where we will add a logic and that will be triggered whenever a configuration changes happens on an EKS cluster.</p><p>After initialize it the boilerplate code will be created for us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*Cpq5JATSRSsYAdqH.png" /></figure><p>it cares about credentials etc so we only need to add code in the evaluate_compliance function code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cl73uW3K9G6r1qXK.png" /></figure><p>We can see the lambda event in parameters and an EKS configuration item, as the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/0*EV8qN7a2j6dN5Uy5.png" /></figure><p>But, surprise surprise, there’s no logging property in the configuration item which we could have used to evaluate the compliance in a straightforward manner within the lambda.</p><p>So we describe each cluster using the name in the describe call to get the logging property value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/0*_lFXW5bNW2tzJDRa.png" /></figure><p>We execute rdk deploy and this creates a CloudFormation stack with an AWS Config Rule resource along a lambda function with the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*n9ADNu5O7WIDCv_1.png" /></figure><p>And finally we see our cluster with no logging is not compliant</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6gpR1uGeXWQqGZin.png" /></figure><p>When setting up the rule over the organization accounts, rdk has an option to do it, however, before you go ahead ensure you follow <a href="https://aws.amazon.com/premiumsupport/knowledge-center/config-organizations-admin/">this</a> for a correct delegation of master organization account permissions if you are not using the master itself.</p><p>In order to make this work within an organization, it deploys a rule on each account, so for the lambda in the master account to execute successfully, you need to create a custom role for the AWS Config recorder on every single account thus it allows to be assumed by the management account (the lambda) of the org in the trust relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/0*TkcF_aQkSTPksn_L.png" /></figure><p>so we can see a non compliant EKS cluster in the other account too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LgDulEtoGnDABedL.png" /></figure><p>Summing up so far:</p><p>1.- deploy AWS Config recorders along S3 bucket, SNS Topic, in all the accounts with a custom AWS Config role that allows master account of each org to assume it and a custom resource that empties the recorder S3 bucket when we delete the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*o6oJsqFcvHH7DGcL.png" /></figure><p>Custom Resource lambda backed to empty the S3 bucket when stack gets deleted</p><p>2.- deploy the organization config rule on every org account.</p><h4>Remediation</h4><p>We’ll remediate in <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/running-automations-multiple-accounts-regions.html">different accounts within organizations</a>, the target accounts will already have a specific Execution role with the permissions needed for SSM to perform the actions on the resources and a trust relationship allowing the central account SSM administrator role to assume the execution role.</p><p>We deploy a CFN stack in the management account with the <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-documents.html">SSM automation document</a> created for this specific use case , along a CFN custom resource to list accounts within the organization unit and share the document with these accounts. A custom resource lambda backed is required no other way allowed.</p><p>This is because we are using CloudFormation instead of Terraform, so we create a custom resource to modify the permissions of the SSM document and share it, another custom resource to empty s3 bucket when deleting the recorder stack was done previously…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/0*gLDAKUo8V-r9_xjk.png" /></figure><p>Custom resource lambda backed to share the SSM Automation document within org unit accounts.</p><p>Then, another issue to overcome, organization AWS Config rule doesn’t support remediation actions, so we need to use AWS EventBridge.</p><p>AWS EventBridge gets generated events from AWS Config whenever we get a non compliant status in any account within the organization, an EventBridge rule will capture and send the specific event to the corresponding target.</p><p>EventBridge bus can’t have a SSM automation as a target if it’s in another account.</p><p>Best option then is to centralize eventbridge bus events in the management account which are captured from the Config rule that registers change events in EKS in other accounts, for this we will create the same rule on each target account using stackset that forwards the event to the central eventbridge bus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B5TmSDfmudsbLg32.png" /></figure><p>Forwarding rule to central Eventbridge bus on target accounts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*zKgk8Pj4OM1NnIck.png" /></figure><p>Central Eventbridge bus rule definition</p><p>Hence the management Eventbridge invokes a lambda with the account id and cluster name that generated the event to execute the automation document specifying the account target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/0*1SKvONHUvubhpXOQ.png" /></figure><p>One challenge to face is that AWS Config sends the event to EventBridge while the cluster is still creating, so we have to wait for it to be active which increases the number of steps in the SSM automation document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YoZG2g2cfJ8P-jRh.png" /></figure><p>A handy SSM action for polling an AWS resource status avoiding any custom stuff that would cause throttling is aws:waitForAwsResourceProperty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*cb_EOHpAzOUoPVnu.png" /></figure><p>SSM Automation Document</p><p>Caveat centralizing Eventbridge events in a single bus</p><p>It’s only possible to use a Custom Eventbridge event bus, this is, not the default one on the management account that will receive the events from other accounts.</p><p>On the other accounts we are limited to use the “default” Eventbus provided by the service, this is because only the “default” bus can receive events from AWS Services and it’s not possible to forward twice.</p><p>For example, you can forward from default to custom bus in the same account, but not to forward again to another bus in the management account.</p><p>Solution, each account has a default bus and this forwards to a custom bus in the management account, there’s no other way.</p><p>Finally, we test it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DTA7AcFShF-tbEem.png" /></figure><p>after ten minutes…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kn4T_hb_yTmwe0uB.png" /></figure><p>and at last:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XUX_Wnp9NMYtyYsB.png" /></figure><p><a href="https://github.com/pabloperfer/eks-no-logging">The Code in Git</a>, creation and deletion scripts in bash with custom waiters for the CloudFormation stacksets, so it’s 4 minutes to test it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PHs6wBr1X1gZ2Ku7.png" /></figure><p><strong>Thoughts</strong></p><p>I’ve observed some inconvenient doing this little automation that are very time consuming and oblige to overengineer:</p><ul><li>CloudFormation lacks a lot features and has bugs not fixed for a long time along sometimes wrong documentation like AWS::Events::EventBusPolicy reference, etc …</li><li>Organizations are not integrated as they should be, often we need to enumerate the accounts ids instead of just specifying the organization unit id. It’s a bit cumbersome.</li><li>SSM it’s a must, works very well and allows configuration management which maintenance you don’t have to care about.</li></ul><p>Could we make something more simple? Sure, but I thought on a case where there are hundreds of clusters and accounts, you can’t poll and remediate easily at big scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3508c120218" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pablo-perez/aws-config-custom-rule-for-enabling-in-multiple-accounts-eks-logging-c3508c120218">AWS Config custom rule for enabling in multiple accounts EKS Logging.</a> was originally published in <a href="https://medium.com/pablo-perez">Pablo Perez</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POC of zero downtime blue/green deployment with AWS CodePipeline, ECS and CloudFormation.]]></title>
            <link>https://medium.com/pablo-perez/poc-of-zero-downtime-blue-green-deployment-with-aws-codepipeline-and-cloudformation-2f6deaa9cd36?source=rss----e6f453ad5d9d---4</link>
            <guid isPermaLink="false">https://medium.com/p/2f6deaa9cd36</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[codepipeline]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[cloudformation]]></category>
            <dc:creator><![CDATA[Pablo Perez]]></dc:creator>
            <pubDate>Mon, 14 Nov 2022 18:51:06 GMT</pubDate>
            <atom:updated>2025-07-24T19:14:44.121Z</atom:updated>
            <content:encoded><![CDATA[<p>Zero downtime deployment means that our website will never become impaired or unavailable during an update. In order to incorporate this feature to our solution, the application load balancer won’t serve the new code until all the tests and reviews have been taken in environments like development and staging, and finally a manual approval being confirmed before going to production.</p><p>The new code will be served immediately, and an instant rollback is possible by swapping back the traffic from the blue (production) service to the green service (non-production).</p><p>This approach can be shared and customized across different teams based on their needs, because we use infrastructure as a code, which allows to save the whole mode in few templates than can be reproduced in other environments within minutes to set a CI/CD pipeline for a microservice.</p><p>Security it’s implemented at the highest level, using encryption at rest and in transit, and the permissions are hardened based on principle of least privilege.</p><p>On the other hand, encryption in transit avoids an attacker to sniff sensitive data in our operations by means of SSL protocol, and encryption at rest means that when our data is encrypted, only the user who have accessed it, will be able to read or write if this user has the correspondent decryption key.</p><p>Apart of aiming speed of releasing software, we implement prevention of non-desired releases by adding a manual approval step with an automatic email notification to the email of the person designed.</p><p>By leveraging various accounts in the cloud where each corresponds to a specific application environment, we isolate the workloads avoiding any interference or security gap.</p><p>A blue/green deployment consists of keeping current running version (blue) in service while new version (green) is provisioned, then the load balancer changes the routing of requests to the newer version, in our case, we will do this with a python script triggered during the pipeline execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*5ufndwrEyysMJIBnXmbBcQ.png" /><figcaption>Multi account approach</figcaption></figure><p>First you can see that in the tool account that we have AWS CodePipeline which is a workflow management tool where your code can built, tested and deployed in different stages into different environments.</p><p>If any problems occur with any step during the process, the pipeline is halted, and a notification is sent via email.</p><p>It’s a good practice to have different environments, different workloads isolated on each different account where different permissions are granted or limited. Also, Integration and Functional tests must be automatically performed in development and staging environments separately. Each account has its own set of resources to do the tests and also permissions are different between test and production.</p><p>Another important point is that changes in a development pipeline should not block production pipelines. The pipeline deployed in the tool account reacts to any updates in the AWS CodeCommit repo development branch.</p><p>Workflow steps are:</p><p>1.- Developer pushes a change in the CodeCommit repository development branch which triggers CodePipeline pipeline execution.</p><p>2.- Next during the build stage the public docker image is pulled and image is built, tagged using the unique CodeBuild job execution id and pushed to ECR tool repository.</p><p>3.- A script in AWS CodeBuild will execute and by using CodePipeline environment variables identifies which target group of the load balancer is linked to listener 443 or 8443 and which are production and non-production, also for each target group gets the value of another tag that contains the docker image tag that is currently running on each.</p><p>4.- CodeBuild sends the tags values containing the image id for the blue and green service to the next deploy stage which uses CloudFormation as parameter values. The green AWS Fargate service receives the new image tag, which will cause the Fargate service to update the new task definition.</p><p>5.- A lambda function is executed, it assumes a role on each account and swaps each listener rule to point to the other target group , also it modifies the tag Boolean value to indicate which target group is in production after the swap.</p><p>On production environments ,there’s a manual approval action associated with an AWS SNS topic and the subscriber will receive and email with a link to the pipeline console to approve.</p><p>Steps 3, 4 and 5 are repeated on each environment.</p><p>With regard to security, the CodePipeline service itself will assume a role that has been created previously on every account to allow CodePipeline service to perform, AWS CodeBuild, CloudFormation and AWS Lambda actions along other services involved like Elastic container service, load balancer service, S3 and CloudWatch actions.</p><p>Moreover, for the pipeline to work securely, a customer master key will be created to encrypt at rest and in transit the data shared on the S3 artifact and scripts bucket, and the Docker images on central ECR repository. The accounts’ role will have permissions to use the CMK to decrypt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*RxkNQJWeudQWgnmGLYLLAQ.png" /><figcaption>Target account</figcaption></figure><p>In the above diagram above we can see the infrastructure is within a virtual private network where we define a private IP CIDR block. The VPC has an internet gateway which is the component that allows communication between your VPC and the internet. By default, it is highly available and scales automatically as per the AWS documentation.</p><p>Also, It has different availability zones for fault tolerance purposes, on them you can create different subnets to isolate different workloads, either public or private.</p><p>By default, the application load balancer will distribute requests evenly across the registered containers in all the enabled Availability Zones. One benefit of Application Load Balancers is that they support path-based routing and rules, this means that multiple services can run in our Fargate cluster, and we can adjust listener port and traffic to each specific service.</p><p>We will configure Fargate autoscaling which can increase or decrease the number of tasks, this is the number of containers running by using ECS scheduler on Fargate with CloudWatch alarms and Application Auto Scaling. When a CloudWatch alarm triggers an Auto Scaling policy we have defined, it increases or decreases the count.</p><p>EFS storage will allow us to mount the same file system on our containers. It supports encryption at rest of course by specifying our customer master key and encrypting data in transit with TLS.</p><p>Furthermore, we will use Privatelink, which is a service that lets you add VPC endpoints which basically allow you to privately connect your VPC to supported AWS services. Fargate Clusters will be in private subnets. They can communicate to other AWS Services through VPC endpoints, traffic will be within the Amazon network instead of using the internet. Also, to allow your tasks to pull private images from AWS ECR.</p><p>Finally, in order to communicate with CloudWatch, we configure the awslogs driver in the containers in your tasks to send log information to CloudWatch Logs. This allows you to view the logs from the containers in your Fargate tasks.</p><p>In order to benefit from the advantages described earlier about having different environments for better testing, security and management, we will create different accounts by means of AWS Organizations. AWS Organizations facilitates the sharing of resources across different accounts reducing permission management effort and resource duplication, allows to separate workloads in different accounts with all benefits this provides regarding security and auditing.</p><p>The final structure is as below, where we will have aside of our management account, we create an Organization Unit where four new accounts have been created, the tool account, where we will deploy the pipeline, and the development, staging and production accounts where we will have the web application and needed resources deployed on them.</p><p>Organization units allow us to organize our different accounts by hierarchy and environment type, so we can apply specific permissions and controls to each.</p><p>Furthermore, not only we can organize accounts by infrastructure resources deployed on them, but by the software development life cycle is achieved by having development staging and production accounts with different workloads thus hosting all stages required for the SDLC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*wF2VEnzA3af5PGpHaWf_oA.png" /><figcaption>Example’s organization layout</figcaption></figure><p>Moreover, we will enable CloudFormation StackSets trusted access on our AWS organization accounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*3rlD9yGf-MzBNCv335YkHw.png" /></figure><h3>Defining and deploying the resources and logic required for the solution.</h3><h3>Deploying Network resources stack on Dev , Stg and Prod accounts.</h3><p>For this, we will use a single template and leverage Stack Sets CloudFormation feature to deploy them from the management account.</p><p>Stack Sets allow you to create, update, or delete stacks across multiple accounts and regions with a single operation. A stack set ensures consistent deployment of the same resources, with the same settings, to all specified target accounts.</p><p>First, it should be outlined that we are creating a whole virtual network logically isolated from other virtual networks within the account and of course in the cloud .</p><p>Network physical isolation has been implemented traditionally on on-premises environments, so in order to implement better security, ability to escalate further in the future and better management of resources, routing and security rules I have decided to deploy a new VPC per environment which allows me to deploy my resources in logically isolated virtual networks entirely defined by me where I can set all requirements to secure outgoing and incoming traffic.</p><p>Below we can see the first section of the template is the Parameters one, this section allows to input strings, comma delimited list among other values, into the template in order to setup resource property values dynamically. For further insight and accuracy regarding the parameters section in CloudFormation we have referenced to the CloudFormation User Guide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*FywG9jY9KpZV3bVkKVq-BQ.png" /><figcaption>StackSet Parameters Section</figcaption></figure><p>We are using on each parameter of the whole project, the constraint attribute AllowedPattern, here I define a Regex expression to accept only a valid CIDR block.</p><p>The default attribute I’m defining allows me to not have to input anything when launching the template from the CloudFormation user graphical interface or by just executing a script in a terminal.</p><p>We are defining the whole CIDR for the network, and then different subnets , without internet access the ones intended for the databases and the containers. The public ones will host the load balancer and the NAT Gateways, a Network Address Translation (NAT) service to access internet from private subnets.</p><p>Next, within the section Resources we are defining what we are going to deploy, the main things are the network itself along an internet Gateway to have access to internet in the public subnets. It can be observed as well that we are using intrinsic function !Ref to refer to the parameter input values.</p><p>We will apply tags to all the resources of the solution to further work with them in future automations.</p><p>It’s paramount to refer to the CloudFormation resources reference in the user guide to understand what resources can be defined and what properties and values are allowed on each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*D3iqoYZIR9aST_0Ise-fPw.png" /><figcaption>CloudFormation StackSet Resources foundational components</figcaption></figure><p>For the databases we will create two different private subnets along a route table for each which will allow connectivity within the whole VPC. We create two because we want to have a database with fault tolerance, in case one datacenter goes down.</p><p>Each will be in a different Availability zone, this is, a separate datacenter, and for this we will use the intrinsic function select, which returns a specific value from an existing list by passing the index. Along with select, we are using the intrinsic function Fn::GetAZs , which retrieves the list of availability zones.</p><p>For a list of all available intrinsic functions in CloudFormation we have referred to the intrinsic function reference in the CloudFormation user guide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*MiLcfzH_PkNlfhgEkgEB6g.png" /><figcaption>Db Network Resources</figcaption></figure><p>The serverless container cluster network will have the same approach as the previous databases subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*aZFbPzQt93dZ0RPYfFmBag.png" /><figcaption>Fargate Network Resources</figcaption></figure><p>Next we will define the NAT Gateways resources, each NAT Gateway needs to be allocated with an Elastic IP as per the AWS documentation for this topic, this is a reserved public IP address that we will own until we release it when we don’t need it anymore. This public ip is needed because the traffic from the private subnets will be translated to this specific IP when going outside.</p><p>We are using the intrinsic function !sub below in the AllocationID property to link the NAT Gateway with the Elastic IP, this function accesses the attribute the AWS::EC2::EIP resource type has.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*iYzj3KtPdQh9fvxAY-aBZQ.png" /><figcaption>StackSet Elastic IPs and NAT Gateways</figcaption></figure><p>Next we have defined the application load balancer network components, the necessary public subnets ( the load balancer is exposed to internet) and the corresponding route tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*lPOiyxc15IEew8qoVvRIcg.png" /><figcaption>StackSet Routing and subnets resources</figcaption></figure><p>Next we define the security groups for the network, security groups are like Linux Iptables firewalls where we filter by protocol and port ingress and egress traffic as described by AWS.</p><p>We are allowing 80 and 443, former will be redirected to the latter. And we are allowing 8080 and 8843, same as the previous, each will accept either production or developer version of the web site served by a docker container.</p><p>We can see specific port to allow access to PostgreSQL, and 2049 port which will be used as the shared storage for the container, in this case AWS Elastic File system which works similar to a NFS file system that grows as per demand and can be shared among different Docker containers.</p><p>Moreover, we should take into account when defining these rules that security groups are stateful meaning that traffic responses are allowed when traffic is sent through specific port no matter the ingress rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*x2YoINCFQkuMt_tozXK96A.png" /><figcaption>Sgs I</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*nhmmpbySgUWzHzFaqKttDQ.png" /><figcaption>Sgs II</figcaption></figure><p>The, the last group of resources we are defining in this template are the VPCEndpoints along their own security groups. VPC endpoint are virtual network devices that allow our connections to other services in AWS, like S3 objects storage or AWS Secret Manager to connect internally within the virtual private cloud and not requiring to reach the public endpoints of those services through internet.</p><p>The advantages of them are basically two:</p><p>- Internal traffic has not cost, unlike NAT Gateway which has cost.</p><p>- Higher security as traffic is not exposed in Internet.</p><p>We are using several ones like Elastic File System (NFS like), Secret Manager to store secrets, and monitoring metrics and logs managed and stored by AWS CloudWatch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*DlEJYilJI0OUDxgKHyP0bw.png" /><figcaption>VPC Endpoints I</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*-Kl5iqdwZad5Uy5gyvF8-Q.png" /><figcaption>VPC Endpoints II</figcaption></figure><p>Finally, we define an Outputs section, where we declare output values from the previously defined resources attributes, that you we will import into other stacks.</p><p>We use a CloudFormation pseudo parameter AWS::StackName being fetched by intrinsic function !Sub as each output has to have a unique value in the region of our account which is required in order to create an output resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*tB4wHOycGV9Dr2hxvUrq4g.png" /><figcaption>Defining Output Section Resources</figcaption></figure><h3>Deploying Sources stack in the tool account</h3><p>The template below deploys the following:</p><p>- A S3 bucket to store the Python scripts that will be executed by a build type stage in the pipeline, so we will identify which load balancer listener is acting as production or not in order to perform the listener swap properly to serve the new version of the Docker Image.</p><p>- Another S3 bucket used by the pipeline to store its artifacts.</p><p>- An AWS CodeCommit Repository that is deployed as part of this stack. This is a Git repository solution available in AWS.</p><p>- An AWS IAM group with permissions restricted to the project CodeCommit repository.</p><p>- An AWS KMS (Key Management Service) keys to encrypt all the artifacts.</p><p>- An AWS SNS (simple notification service) topic to notify the CodePipeline approval actions.</p><p>- AWS IAM roles and policies needed by the pipeline to execute actions across the accounts of the organization leveraging other services.</p><p>I’ll describe in detail each excerpt composing the template that will create a Stack in CloudFormation thus deploying the resources.</p><p>Below, I have defined an AWS::CloudFormation::Interface resource type, this is the grouping and ordering of input parameters when they are displayed in the CloudFormation console.</p><p>It’s convenient because, by default, the console alphabetically sorts parameters.</p><p>Within the interface, there’s a single parameter group defined, and each label creates a subgroup where we specify which parameters from the parameters section is shown as part of this layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*voveNW-yejgc7fB7Z62mBw.png" /><figcaption>Parameter Metadata</figcaption></figure><p>In the next step we will define the parameters section.</p><p>Parameters section allows to pass values into the template in order to setup resource property values dynamically.</p><p>We are using on each parameter of the whole project, the constraint attribute AllowedPattern, here I define a Regex expression so only matching input values, can be passed in the input, like for example, a string representing an email address.</p><p>In this template all are of type “String” and have the attribute Default , which allows to set a predefined value instead of requiring a new input when the Stack is launched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*Sa48QuqOOFJdQla62zTWjA.png" /></figure><p>The following are a series of excerpts containing the resources defined along an explanation for each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*azYGzTHNdRkISxs1NU2ixQ.png" /><figcaption>Source Stack CodeCommit resources</figcaption></figure><p>Above we create an AWS CodeCommit Git Repository.</p><p>!Ref function points to the value in the parameter provided, in this case pCodeCommitRepoName.</p><p>Also, we create an IAM Group named “devs”, all the users added to this group will we applied the policy document defined where they only can perform the API calls needed to operate Git branches and do push and pull Git actions.</p><p>We can see there’s an intrinsic function called !Sub. In this case !Sub function will get the value from the resource attribute “arn”, this is the unique identifier of the resource, thus these actions will only be valid when working with this repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*YyNbz-mduWkcVQM_eQ5HdQ.png" /><figcaption>Sources stack ECR repository</figcaption></figure><p>Above we define a managed container registry to store Docker images and artifacts for containers.</p><p>We enable encryption at rest on the registry in the property EncryptionType, for this we will use a Key that we will define later in the template and refer to it in the property KmsKey.</p><p>We define a policy as well for the registry where only the tool account and a specific role in the dev , stg and prod accounts can upload and download docker images from this registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*4iTZtCC-qEBhFiiYTOt-8A.png" /><figcaption>Sources Stack artifact S3 bucket</figcaption></figure><p>Above with define an object storage type container, this is an S3 bucket to store the CodePipeline artifacts.</p><p>We setup encryption at rest using the same Key as we specified in the previous excerpt, and that we define later in the template.</p><p>To specify a unique name for the S3 bucket we are using a CloudFormation pseudo parameter, this fetches the actual account number and compose a unique name for the bucket after adding a suffix.</p><p>We block all public access to the bucket, basically, the S3 bucket will reject calls although the bucket has public access enabled therefor restricting access to it only to AWS services and authorized users.</p><p>VersioningConfiguration property enables different variants of the same object uploaded, each has a version id every time an object is uploaded, so we can go back to the previous version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*Ypetz0xYcfvRtj6GqnYNew.png" /><figcaption>Sources Stack S3 bucket policy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*2qLjjFUKQgj6z0F5ofePuw.png" /><figcaption>Sources Stack S3 bucket policy II</figcaption></figure><p>Above I define a permissions policy for the S3 bucket, so I specify which API calls can be invoked against it and by who.</p><p>In order to understand what API, call on each service does we can refer to the BOTO3 SDK API reference where we will find all the services and available actions, we use this guide to create any script with python.</p><p>It denies unencrypted object uploads, non-TLS/HTTPS connections, and allows only the required AWS S3 API actions from specific roles.</p><p>The tool account will be able to invoke gets and putobject api calls along a CloudFormation service role created in the dev, stg and prod accounts, as I will store in this bucket other templates known as nested stacks that I’ll go into detail later.</p><p>I’m using intrinsic functions !Sub and !Ref, along a pseudo parameter AWS::Partition, which for standard geographical regions, (China would be a non-standard) is “aws”.</p><p>Moreover , aside of this pseudo parameter, in order to compose dynamically a string to specify who is allowed to invoke the api calls, I do string substitution by just doing ${parameter} specifying the parameter where I want to fetch its value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*ao2Bz5FyX-KA5rIMa1a7pw.png" /><figcaption>Pipeline KMS Key</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*J0LF1nehC6n2m1tIykCqoQ.png" /><figcaption>Pipeline KMS Key II</figcaption></figure><p>Above we define the AWS Key managed service key that we will be using to encrypt the pipeline artifacts, the S3 bucket and the container registry.</p><p>We add dev, stg and prod account roles in the policy, we are defining roles to allow them to use the key, the pipeline actions will require that these roles have permissions to encrypt and decrypt using this key to perform the operations that the pipeline will have on each stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*OLYnRYGolO02ejHqMsGx7A.png" /><figcaption>SNS Resources</figcaption></figure><p>Above we define two AWS Simple notification service resources, a topic and a subscription to the topic of type email. This is required to add a manual approval step before the application is deployed to production. An email is sent to the address provided above in the parameter pEmail.</p><p>Next we will create a Service Role for the AWS CodePipeline itself. This is like giving a role to an entity which is the mechanism itself under the hood to process the pipeline, that will perform operations on our resources, and although we confirm the permissions to this entity the pipeline won’t work.</p><p>The permissions are defined in the form of an AWS IAM (Identity and Access Management) policy that link the service role created by using an intrinsic function !Ref in the corresponding property of the policy definition in CloudFormation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*Kg-1CWBhf35PVz_wPM8iwQ.png" /><figcaption>Pipeline Role I</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*a5UHAn51W8eWFId5cMOfqQ.png" /><figcaption>Pipeline Role II</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*83HGnIq4T84MaGRBPE4ZaA.png" /><figcaption>Pipeline Role III</figcaption></figure><p>Above we can see that for every service that is related to the pipeline, minimum permissions required are granted following the least privilege strategy. We select the API calls required whenever is possible instead of granting all permissions.</p><p>This role is assumed as well by the dev ,stg and prod account, so we need to grant permissions even for this action as well.</p><p>Above, at the beginning of the definition of the policy we have added a DependsOn attribute, where we add in specific order some resources. We need this in this specific case, to avoid any dependency error when deploying the policy, CloudFormation it’s supposed to take care of dependencies but in some resources like defined policies in a property it doesn’t manage the order correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*ZtTUY391rGoz7ghP2IcSTQ.png" /><figcaption>CodeBuild Policy I</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*zp_rXlD39m69FF4X9HX-Gw.png" /><figcaption>CodeBuild Policy II</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*CVS507QT7JzOhpNJ78guVA.png" /><figcaption>CodeBuild Policy III</figcaption></figure><p>Above I define the AWS IAM Role for AWS CodeBuild, this service will execute the scripts to build the Docker image, push it to the registry and afterwards check load balancer listener to find out which one is in production along executing the logic that allows this.</p><p>Among other permissions that we have already discussed, we can find permissions to publish logs to AWS CloudWatch logs to keep logs so we can troubleshoot any issue with scripts execution.</p><p>Furthermore, permissions to work with the registry, the S3 buckets, encryption and decryption with the key defined, EC2 permissions to apply tags in the load balancer target groups in order to achieve a logic that identifies which is production or not.</p><p>Roles in dev ,stg and prod account will be given permissions as well to allow AWS CodeBuild to execute the logic on each account.</p><p>Next, we can see a role and its policy definition that will be used by each dev, stg and prod account role, this will swap the listeners and mark the pipeline task as success or failure when lambda function is executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*j6zOw0ZPZW73kioVPV3YBw.png" /><figcaption>IAM Role for Lambda</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*0funH4AO2nlo5gju_SuTuw.png" /><figcaption>Policy for Lambda Role</figcaption></figure><p>Once the AWS CloudFormation stack is created, resources values that we will use in other stacks can be accessed after specifying them in the Outputs section. Outputs section declares output values that you want to return for cross stack referencing where you can export and import values, or just only use it to provide descriptions.</p><p>When we define other resources that are needed, like the pipeline itself and its stages for example, all the attributes’ values of resources already deployed will be imported, like the Key identifier or a role identifier, etc…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*H4603-CTMU8uoWWYfkWiCQ.png" /><figcaption>Sources stack Outputs section I</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*PiebihctWJ9OnOg20DfBtw.png" /><figcaption>Sources stack Outputs section II</figcaption></figure><p>They have to have unique identifiers, that’s why again we use !Sub intrinsic function with CloudFormation Pseudo parameters .</p><p>There is one caveat here, in order to create the role policies, which refer to entities from the target accounts that don’t exist yet, such the roles in those accounts the CodePipeline Role will assume to execute actions in those accounts, and like the KMS Key policy which will allow the target account roles to decrypt artifacts in order for the pipeline operations to succeed, because we haven’t created them yet, we will in the next step, we are commenting out these principals on the policy roles. For this we save the template file with a name that indicates these principals are commented, and after the next step is completed, we will update this same stack with the uncommented template.</p><h3>Deploying Application Load balancer and IAM Roles stack in the target accounts</h3><p>We start deploying resources on the dev, stg and prod accounts. First we will define a template where we define the application load balancer and different roles needed to use the services and tools that compose the solution and are integrated into the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*z9DcMtscnQ7xhJRm2rLaJQ.png" /><figcaption>ALB-Roles stack parameters, mappings, and conditions</figcaption></figure><p>Above we can see that we are suing some parameters with values that we need for our stack, these values cannot be imported from other stack as the tool account Key identifier can’t be imported because imports and exports don’t work between different accounts.</p><p>We are defining two new sections, which are Mappings and Conditions, combining both we will assign a private subnet for the load balancer from the development environment and public subnets for the staging and production ones.</p><p>A mappings object declares different levels of name value pairs to provide the resource property with the correct value by means of the fn:findinmap intrinsic function. This allows you to implement some conditional logic, and Conditions define when a resource is created or when a property is defined. They are evaluated based on input parameter values that you specify when you create or update a stack. At stack creation or update, CloudFormation evaluates all the conditions in your template before creating any resources.</p><p>An example can be seen below where , after previously defined the mappings and conditions we define an application load balancer, and we use the !If function to refer to a condition met or not to assign a value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*yc8SvQxUXb-7rMwZxZQEwg.png" /><figcaption>Application Load Balancer definition with conditions</figcaption></figure><p>Above it can be noticed that we are using the intrinsic function Fn::ImportValue which allows us to import from the network stack the values of the subnets and security groups that we will provide to the load balancer configuration. That’s the reason why we were asking for the network stack name in the parameters section which was created previously by the StackSet functionality which generates a random name with a specific prefix which we ensure is present with a regex rule.</p><p>The rest of the template contains definitions of roles that will be used by the Pipeline:</p><ul><li>A CloudFormation service role to deploy stacks that will be passed to the pipeline for each target account to be assumed in order to deploy the defined resources.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*n7wTsmcokkaU_zzoNJObAg.png" /><figcaption>CloudFormation Service Role for the target accounts</figcaption></figure><ul><li>A Cross account role that will allow the tool account to access resources and services from the target accounts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*4DnhmyRXE5mMZYDmWqBuLg.png" /><figcaption>Role to grant the tool account permissions on target accounts</figcaption></figure><ul><li>Both task and execution role for the Elastic Container Service, in this case we are using Fargate serverless service to launch and maintain the containers. As per the documentation of AWS, the execution role executes actions related to the cloud service that manages the containers while the task role allows the container to invoke other AWS services when needed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*lPhq3BLRMmJtXWI6kdJScw.png" /><figcaption>ECS Task Role</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*ClBzsl1Qdwb4dOM1z3K1qg.png" /><figcaption>ECS Execution Role</figcaption></figure><ul><li>An AWS Lambda role that allows the tool account to execute the AWS lambda function in each target account with permissions to invoke API calls related to the load balancer service and EC2 tags as well as notifying the status to the pipeline, all of this allows the logic in the function to be executed correctly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*KSmwTInOd213rCCuaqEzvA.png" /><figcaption>Lambda Role and Policy</figcaption></figure><p>Finally, we define another KMS Key, so each account will use it to encrypt its own resources. Within the policy we will grant permissions to the tool account to decrypt the data from each target account as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*GT7LoqPAXNfMuDGUxXGicA.png" /><figcaption>Target accounts KMS key definition</figcaption></figure><h3>Defining and deploying the pipeline along scripts in the tool account.</h3><p>First I’m going to show how the pipeline looks once is deployed. In the picture below we can see the pipeline is working smoothly on every step, however, in this step we will not release any code to our Git repo yet as another stack will be needed in the target accounts.</p><p>An then we will go thoroughly through the stack where we define all the Pipeline stages and steps that results in a CI/CD cross account pipeline with different isolated environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*KUWeyt_zZh1lwaaVCkKV3g.png" /><figcaption>Deployed Pipeline I</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*Rd_15SrWqLg2Lv6txajkzQ.png" /><figcaption>Deployed Pipeline II</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*kSqT2xV4kScAwVhNjAUZlA.png" /><figcaption>Deployed Pipeline III</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*d_G0L0bJkW1kKjdzZfycTg.png" /><figcaption>Deployed Pipeline 4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*M0SM6BbmG9GJQPb_1Y5uIA.png" /><figcaption>Deployed Pipeline V</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*gjDukczerlgMIWY-gBMLkQ.png" /><figcaption>Deployed Pipeline VI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*9pdwp47LpXCd_0bj1VDSaw.png" /><figcaption>Deployed Pipeline VII</figcaption></figure><p>As it can be seen above in summary there’s a stage named Source in the tool account which triggers the pipeline execution whenever any asset of the three “roots” is updated, these are, the AWS CodeCommit repository where the developers push their Dockerfile along files it needs, the AWS S3 Object Storages bucket, where other CloudFormation templates needed, and scripts are fetched, and a logic is executed to achieve the blue/green deployment, all of these are in the tool count.</p><p>From here, there will be a Build stage that will use AWS CodeBuild to connect to Docker, build a new docker image and push it to our AWS elastic container repository, while generating an output artifact with the tag id set to the new image. We are using the build unique id for this.</p><p>Then in the next stage we will perform the following steps in the dev account that are executed later on staging and production if anything fails, and we approve:</p><p>- Discovery. AWS CodeBuild executes a script that verifies the application load balancer used for our solution exists and which target group, by checking the tags, is forwarding the traffic to the Docker container in production and what image it’s this using.</p><p>As per the AWS documentation a target group is a logical entity that acts as a router by distributing income requests from the load balancer listener to the specified targets, based on a defined rule and its conditions.</p><p>- Deploy. AWS CloudFormation updates the AWS Fargate Cluster stack, (we will deploy it later), and will pass the proper parameter with the new Docket tag to the cluster service that is not in production, which is running an old Docker image. For this to succeed we use input artifact resulting from the previous step containing the new Docker image tag on the specific parameter that corresponds to the specific service to be updated.</p><p>- Swap Target Group AWS Lambda function. We have created an AWS Lambda function that executes a Python script on the environment or account specified, which will swap the target group by modifying the load balancer listening rule. This will forward the traffic to the new AWS Fargate Service running the container with the new Docket image.</p><p>And finally , only in the Staging and Production accounts, the pipeline will have a manual approval step. This manual approval will send an email to the address we have defined in the previous “sources” stack, and which will have the pipeline stopped for 7 days, giving us time to review carefully our new released before approving it and executing the lambda function that will swap the load balancer target group.</p><p>We receive and email with a notice regarding the approval of the blue green deployment , this is a load balancer target group swap to the container that runs the newer version of the docker image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*3OtTXtf2krBEe1wXrrJsjg.png" /><figcaption>Manual Approval notification</figcaption></figure><p>We review the manual approval and approve it for the workflow to go ahead , which will trigger a lambda function that performs the target group swap in the load balancer using the AWS SDK to build the logic.</p><p>In the picture below we can see the target group is correctly swapped to the AWS Fargate Service that contains the task with the docker container that has the new version of the website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-SgLl1AEAqPcSWvAneczWQ.png" /><figcaption>Lambda function execution log</figcaption></figure><p>We will discuss now the most relevant parts of the pipeline template.</p><p>Source Stage</p><p>In the property ArtifactStore we specify that the input and output artifacts used by our pipeline will be storage in an AWS S3 object storage bucket, which is encrypted with a specific key being both created previously in our Sources CloudFormation stack in the tool account, so we can import these values with the intrinsic function ImportValue and do variable substitution with the function !Sub “{x}”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*GnKuNMDgKTKCV87eLzF2Jg.png" /><figcaption>Pipeline Source Stage I</figcaption></figure><p>Then we define the steps, as we have explained some paragraphs above in this document. We start by specifying the category source, and our CodeCommit repository and branch that will trigger the pipeline. We have enabled the option for the pipeline to poll for any changes in the repo, and we specify the name of the output artifact as we will used later in another step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*tUWSbr6hfrpbqHNz02Gzzg.png" /><figcaption>Pipeline Source Stage II</figcaption></figure><p>With the same stage , there are other two sources, where we store the CloudFormation templates needed to update our AWS container cluster, and the scripts for the logics involved in the blue green deployment regarding the load balancer traffic rule. Because RunOrder attribute is “1” for the three sources, they will be polled in parallel.</p><p>Build Stage</p><p>Next the build stage will point to the CodeBuild project defined in the same template for this purpose. Again, we define the input and output artifacts naming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*qcdEHtYqi7csOPIR41W8aA.png" /><figcaption>Build Stage</figcaption></figure><p>Below, we can find the project definition to build the Docker image, which we are linking to in the previous screenshot definition of the first build stage, it is executed only once in the tool account because the Elastic Container Repository is centralized in the tool account and shared to the rest of the accounts and environments from there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*SNX9EOtwEGMUgkbEq-ahqw.png" /><figcaption>CodeBuild Docker Image project</figcaption></figure><p>As in all the resources defined, the project is encrypted with our custom key, this applies to encryption at rest and in transit. We use a small Linux container type where we pass the variables needed, like the one pointing to the AWS Secret vault object that contains my DockerHub personal account, needed to build the image by downloading Apache Docker, we are using the CloudFormation resolve syntax specific for AWS Secret objects in this case.</p><p>The Service Role with the proper permissions is imported from the sources stack we deployed previously, and then in BuildSpec we define different phases of execution of our script, where we first update the operating system and the awscli, we create from the CodeBuild logs and the repo path the final tag for the build id which we will use as the Docker image tag, and in the next pipeline stage to discover the tag that was set in the last image pushed to our Docker private repo.</p><p>Docker login we use variable substitution to use our Docker credentials, and then we log to our AWS ECR Repository and with those temporary credentials in the session we push the image.</p><p>The output artifact will be inspected as described in the previous paragraph.</p><p>Build Discovery Stage</p><p>And the same happens with the logic that checks the load balancer target group tags, we specify the CodeBuild project which in this case fetches the scripts.zip object and produces and output artifact with the parameter values to update the Docker image in the specific service which is not in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*zi4EOWCaO37911QjR-puVA.png" /><figcaption>Build Discovery stage</figcaption></figure><p>Now, we will go through the AWS CodeBuild project definition to discover the actual status of the traffic forwarding in the application load balancer. For each environment we define one CodeBuild project like the one below because each uses a specific account role to execute the script on each account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*ghrdHKa_sbor3YQ0dR5YTg.png" /><figcaption>CodeBuild project definition for build discovery stage</figcaption></figure><p>In the environment section we specify the image of the instance that will run, in this case a Linux instance with python 3.6, we specify variables, like the role of the account that we had created previously and that allows the tool account to assume this role which grants the permissions required to invoke the required API calls on the target account by the script.</p><p>The BuildSpec property defines the logic we need to get jq package installed which is needed to export new environment variables for the current session with the keys and session token that the script will assume. The rest of the environment variables are used by the script which runs in CodeBuild.</p><p>Once we have upgraded boto3 ,the former being the AWS SDK for python we execute the script which was passed as an input artifact in the CodePipeline stage definition that links to each project.</p><p>Defining the Discovery Build Stage AWS Boto3 script</p><p>The following script produces an output json artifact (cf_inputs) with the unique tags that we will pass to the CloudFormation stack that contains the Fargate services to perform an update on the non-production service that launches a new container that pulls the new image from the repository specifying this tag.</p><p>First it gets the build id from the last execution id of the build stage where the docker image is built and then it gets the tag from the artifact produced in that execution /tmp/build.json. This tag will be passed to the target group to the target group that is associated with the port 443 production and 8443 non production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*Kk_w26-Y78RIWW-HhXQMXA.png" /><figcaption>Discovery script I</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*ydO2YvEgURCuDZzI0nh97Q.png" /><figcaption>Discovery Script II</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*_FXd7FuAuEhtqkVCc6VI9A.png" /><figcaption>Discovery Script III</figcaption></figure><p>For the above to work we need a project that builds the image previously. This is embedded CodeBuild Project definition in the pipeline template too that we will describe hereafter.</p><p>Let me add more insight, above we have the Python script that is executed in the second build stage, right after the docker image is build and pushed to the registry, which will use the AWS SDK for Python, which is Boto3, and by invoking the proper API calls on each defined function we have made a logic that sets the proper tags on each application load balancer target group , the ones holding the green and the blue service. We get the Docker image tag pushed in the previous step, by getting the previous execution id and inspecting the output artifact produced previously, and then we get the actual tags on the target groups to pass the newest tag to the proper target, the one that is not running the image in production and the current tag that was already set in the production target group thus not causing any update on the “blue” service but on the “green” service by terminating and launching a new container with the new image.</p><p>This script will get session variables for each account, dev, stg or prod and gather the right tags to pass to the deploy step, as parameters of the CloudFormation stack that updates the target group tags and the AWS Fargate service.</p><h4>Updating the green service in the AWS Fargate Cluster</h4><p>The step of updating the CloudFormation stack in the dev, stg or prod account is very interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*bTyM0zuqdh9KMQwXizAJTQ.png" /><figcaption>Pipeline Deploy Stage</figcaption></figure><p>We specify CloudFormation as the provider, the action mode is CREATE_UPDATE , this means if the stack doesn’t exist will be created and if it does, updated. We provide the capabilities needed by CloudFormation to work AWS IAM identities resources and also CAPABILITY_AUTO_EXPAND which refers to the ability of the CloudFormation stack to create substacks, as we defined them as any other resource.</p><p>The ParameterOverrides property allows CodePipeline to update the value passed in the parameters to the stack, which in this case is the correspondent Docker image tags for the blue and green services as per the logic executed before, the Docker repository name that we passed in the parameters and the S3 bucket containing the CloudFormation templates for the operation. Moreover, we pass the stack name with the network resources that was created in that account previously with a StackSet .</p><p>In order for the pipeline to know where to deploy this, we specify the role created on the specific account that allows the tool account CodePipeline role to assume the target account role with permission to deploy CloudFormation stacks.</p><p>Defining the Manual Approval step before a Lambda function swaps the Application Load Balancer traffic.</p><p>This excerpt above shows the Approval action, we specify the AWS Simple Notification Service Topic that we defined previously in the Sources stack by importing its Arn or unique identifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*2EgvAuBi-DTuey0ygSRASg.png" /><figcaption>Approve Step</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*1zirbUCZC2b3pG7QbvM3hg.png" /><figcaption>Step where lambda performs the swap</figcaption></figure><p>We can see the step to forward the traffic to the new AWS Fargate service container that runs the new Docker image.</p><p>We specify AWS Lambda as the provider, being the Lambda function defined in this template and passing the name of the application load balancer for the AWS SDK Python script and the specific account role that allows the pipeline to execute the lambda function in a cross-account manner.</p><p>One of the scripts that we have uploaded to our source AWS S3 object storage bucket is the one that an AWS Lambda will execute once the approval has been given when the workflow requests it when after executed the deploy stage.</p><p>AWS Lambda executes this Python script by passing it the handler method, the handler gets some information from the AWS Lambda event, the event object argument is a Json dictionary that contains info we are going to use in our logic. Information about the pipeline job and inputs like the application load balancer name and role to assume in order to start a new AWS session within the lambda.</p><p>Then, when invoking the method to swap the target groups, by using the AWS Boto3 SDK we will invoke the proper API calls to describe the application load balancer listeners and each rule for each target group, where we modify the traffic destination, this is the target group for each one of the rules.</p><p>Finally, we set a Boolean value for the tag that tells us if the target group is in production or not and we send a failure or success signal back to the AWS CodePipeline pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*nyToySeeJc-ZLsRFgQGCKg.png" /><figcaption>Lambda Function Code I</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*b_zOf7fuk_2OQPbQwOoP6g.png" /><figcaption>Lambda Function Code II</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*fG1XHS7zjHjr0l_lVcnjwg.png" /><figcaption>Lambda Function Code III</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*DLSpaoNG25mG0ddssbV96Q.png" /><figcaption>Lambda Function Code IV</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*bvxx1wqM67vTXCJ35hiopA.png" /><figcaption>Lambda Function Code V</figcaption></figure><h4>Defining and deploying the AWS Elastic Container Fargate Cluster</h4><p>It’s needed to say, that when we deploy the solution, we won’t run the Pipeline until the container cluster is up and running.</p><p>For this we will need to first of all , clone the AWS CodeCommit Git repo with a user that belongs to the devs group in order to be allowed to push one version of our Docker image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*E5E1w62y5FSI-d3mGimUoQ.png" /><figcaption>Images in ECR</figcaption></figure><p>Once we have pushed our Dockerfile to the repo we will create the CloudFormation stack that creates an AWS Fargate cluster and at the same time launches two separated nested stacks with two Fargate services running on each.</p><p>Nested stacks allow you link a template within another template by defining resources of stack type on the parent one. Nested templates are uploaded to S3, and you need to specify the resource type AWS::CloudFormation::stack specifying the S3 URL of the nested template in the property TemplateURL.</p><p>How do they work? As per the CloudFormation documentation CloudFormation treats the nested stack as a resource of the main stack. If you update/delete the main stack CloudFormation update/deletes the nested stack. Also, If for example you create two main stacks that both include a nested stack, each nested stack is independent, you can customize each one with input parameters.</p><p>Below we can find the definition of each nested stack in the parent template, in this case both the green and the blue services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*dqqBwu_FSRWd54p_ECT7jw.png" /><figcaption>Green Service Nested Stack definition</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*R3O-xo6KWbDdj57jMry0Xg.png" /><figcaption>Blue Service Nested stack</figcaption></figure><p>You can notice the difference is in the ports, being 443 production and 8443 nonproduction, so the non-production traffic is forwarded to 8443, which is what happens every time the lambda function swaps the target group rules. And the property pTag, acts as a parameter for the nested stack , like all the properties defined in the nested stack resource. This parameter contains the tag that was set in the image during the build and will cause only the non-production service to be updated launching a container with the new image and terminating the old one.</p><p>We are defining too an encrypted log group to keep track of all on going events in the cluster, and two Elastic Filesystem mount points, so the Docker containers can read and write to the same file system which at the same time has high availability. The file systems are also encrypted we the key we defined at the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*41EDQOVk2-zupS8zGjhMfg.png" /><figcaption>Fargate Log Group definition</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*Di0kCY7MS12rX7dYm22xbA.png" /><figcaption>EFS Definition</figcaption></figure><p>In the nested stacks we have the following resources:</p><p>Two listeners for HTTP which redirects to HTTPS by default, and the HTTPS one uses FindInMap intrinsic function to get the Certificates identifiers that correspond to each domain, these are part of my own registered domains and are stg.pabloperfer.net and prod.pabloperfer.net.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*uhZ7NWn9mL5JAMY-Pw_gVQ.png" /><figcaption>Listener definition</figcaption></figure><p>We also define a rule to forward traffic to each target group</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*q9qtjzrQk8WhUSQrsbjJQA.png" /><figcaption>Listener rule definition</figcaption></figure><p>The target group itself of the application load balancer previously deployed by other Stacks.</p><p>Health check protocol is HTTP because the containers are exposed on port 80 and , because the redirection to 443 is implemented by default, the description of the connection is carried on by the load balancer itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*fY5qu7-P2BjhpmDSYH1DwA.png" /><figcaption>Target Group Definition</figcaption></figure><p>The we define the Elastic Container service, with LaunchType property Fargate because we want it serverless, we specify the target group with which the service is registered, and the private subnets we defined in the first stack.</p><p>The service guarantees we will always have a number of tasks running and will implement health checks, to launch a new task if needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*QN1m5JlCQ1pAlZglaTAXlQ.png" /><figcaption>Elastic Container Service definition</figcaption></figure><p>Where do we define the container? In an Elastic Container Task. Each AWS Fargate service can have different tasks, where we define the volume to mount on the container, the port exposed on the container, role used by the container itself, log driver and resources like CPU and memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*eqB08KHp3I5NYoJ-X9uS5A.png" /><figcaption>Elastic Container Task definition</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*G_iiDSXP2ePPMmeHtJiAAg.png" /><figcaption>Fargate cluster stack deployed resources</figcaption></figure><p>To minimize any management of the infrastructure we will setup a simple autoscaling based on the Elastic Container Service CPU usage, in this case whenever the containers use more than 50 percent of CPU, a new container will be started until a maximum of 10. We will set one for the blue and another for the green service. Whenever the number of visits increase to our website , the load balancer increases automatically and the number of containers too because of the CPU usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*ZMHwrAR4epu6ktqaqUUugw.png" /><figcaption>Autoscaling</figcaption></figure><p>Testing</p><p>Once Docker image has been modified and pushed to the Git repo, the pipeline is triggered and in the first stage, Code build logs show how it’s automated the building, tagging and pushing of the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Ex02oqOMz4LCmprvvDja1g.png" /><figcaption>CodeBuild Image logs</figcaption></figure><p>Then in the second build phase where we check the target groups tags to see what the image id is, and which one is in production in order to update only that target group and the AWS Fargate service that is linked to it with CloudFormation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gmiQmhxmKWvebAiH_m2JkQ.png" /><figcaption>CodeBuild Target Group Tags logs</figcaption></figure><p>During the deploy stage, each account has deployed AWS Fargate cluster stacks with two nested stack resources that contain an AWS Fargate service with the Docker container task that is not in production at the moment, based on the current tag of the load balancer target group, the non-production service, will get the new Docker image running as it will receive a different parameter to perform the update on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*W5itreMceQXiJi3_QN-Jeg.png" /><figcaption>Nested Stacks with a service each</figcaption></figure><p>Before approving the swap of the load balancer target groups, We can see an example of the load balancer and the rules to redirect the traffic to HTTPS port, as well as the two ports, 8443 and 443 used, one for blue and the other for green service. And the most important part, the target groups associated to the ports the containers are exposing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*nU_wLy30VO79i7ksG4Ma6g.png" /><figcaption>Application Load Balancer Listeners</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*kmJuXfbH4SAprKNbA2OvGA.png" /><figcaption>Application load balancer target groups</figcaption></figure><p>When we approved the notification sent to our email, the lambda function swaps the target group, the ALB 443 port redirects traffic to the target group Fargate Service Task Container that has the last version of the Docker image.</p><p>The screenshot below illustrates the tags we use to implement the logic that indicates which target group connected to a specific Fargate Service Task Container is currently acting as production and with which image tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*DLuycsUSndKACODeyX8Zgw.png" /></figure><p>The target group swap is achieved by modifying the ALB listener rule</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*vJ72iG5IO-5SoYGR2MKb_A.png" /><figcaption>Listener Rule</figcaption></figure><p>Therefore, the rule for the application load balancer has changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*aLKZUIOV378l5Q1aEY84Pw.png" /><figcaption>Listener Rule after Swap</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f6deaa9cd36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pablo-perez/poc-of-zero-downtime-blue-green-deployment-with-aws-codepipeline-and-cloudformation-2f6deaa9cd36">POC of zero downtime blue/green deployment with AWS CodePipeline, ECS and CloudFormation.</a> was originally published in <a href="https://medium.com/pablo-perez">Pablo Perez</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to remediate drifted resources that require to be replaced when conciliating the drift through…]]></title>
            <link>https://medium.com/pablo-perez/how-to-remediate-drifted-resources-that-require-to-be-replaced-when-conciliating-the-drift-through-b66327cf8233?source=rss----e6f453ad5d9d---4</link>
            <guid isPermaLink="false">https://medium.com/p/b66327cf8233</guid>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[drift]]></category>
            <dc:creator><![CDATA[Pablo Perez]]></dc:creator>
            <pubDate>Thu, 10 Sep 2020 09:42:04 GMT</pubDate>
            <atom:updated>2020-08-31T09:55:16.911Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to remediate drifted resources that require to be replaced when conciliating the drift through a CloudFormation Update.</h3><p>The following describes a scenario a EC2 CloudFormation stack is in “drifted” status because of the root volume size does not match the actual one.</p><blockquote><strong>Note: — For a list of resources that support import operation please refer to this </strong><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import-supported-resources.html"><strong>link</strong></a></blockquote><blockquote>Hint: — Save any modification in the template in a new and different file in case you need to come back to it to repeat the process.</blockquote><p><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import-supported-resources.html"><strong>Steps to sync the instance back:</strong></a></p><p>We will remove the drifted resource from the stack taking care no other resources are dependent on it to import it later and have it synced. If there are other resources depending on it we will hardcode the values being referred or take the resources out of the stack as well.</p><p>In this scenario we are remediating a stack with a single EC2 instance.</p><ol><li>- Download the current stack template and add a DeletionPolicy attribute set to Retain to the instance. For more info click <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html">here</a> .</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*N-3ZEAt4uKLIo0GHa7xsSA.png" /></figure><p>Then update the stack with the new version of the template.</p><p>2.- In a new file, copy the current template and remove the instance definition from the template and any reference to it by looking for other matches to the logical id of the instance definition.</p><p>In case all resources are drifted and require replacement we need to remove all resources within the resources section and add a dummy resource to keep the stack there during the update.</p><p>We will remove the Outputs section as well which most likely will have dependencies on the resources removed.</p><p>We can keep conditions and parameters section.</p><p>If there are other resources not drifted, like a security group for example, we will just remove the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*Hdj-rGqDqHi8_3sx1IUjHw.png" /></figure><p>Note: Before updating stack ,<strong> take note of the previous drift results</strong>, and save them in a file.</p><p>When updating the stack again, this will cause the instance to be removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*J32aPwqtNrD7ZDlH87p6RQ.png" /></figure><p>3. — We update the stack uploading the new template and we can see the instance deletion is skipped</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*X_gV9WVO2Bnruk3bCF9cqw.png" /></figure><p>4.- We’ll take back the original template resource section and add it along the dummy resource of the new version of the template.</p><p>We will keep for now out of the template, the Outputs section as it’s not allowed for imports, and add in all the parameters the updated value for the drifted property specifying the current values for the instance, subnets, security groups, ami-id , root volume size, a new volume in the blockdevicemappings section…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*Vcm_CxtAzO13vxdY11UELA.png" /></figure><p>5. — We click on import resources into stack</p><p>Note:<strong> Don’t click in “Update”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*lHgrRbUd6ARYhNKeqldWaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*NBIq1wG99nXPVunmLUO0Ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*H4s5VEnM0Ny3EdW99H4V-g.png" /></figure><p>And then the import will be completed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*ptnIH9eL-rfHeQlyxUdsRg.png" /></figure><p>6. — Now trigger the drift again and the drift details, if you missed any property value you need to start the process again.</p><p><strong>Note</strong>: In order to start the process again you need to update the stack with excluding the drifted resource as in step 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*LLFErEX7hcO3G8_cxEvFWw.png" /></figure><p>7. — If the process was correct, copy the Outputs Section from the original template , add it back to the current one and perform a new update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*6WZ57aYcXEqSG3GVMSxUYg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b66327cf8233" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pablo-perez/how-to-remediate-drifted-resources-that-require-to-be-replaced-when-conciliating-the-drift-through-b66327cf8233">How to remediate drifted resources that require to be replaced when conciliating the drift through…</a> was originally published in <a href="https://medium.com/pablo-perez">Pablo Perez</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Gateway, DynamoDB and Discogs.com API]]></title>
            <link>https://medium.com/pablo-perez/api-gateway-dynamodb-and-discogs-com-api-7da892b5fec6?source=rss----e6f453ad5d9d---4</link>
            <guid isPermaLink="false">https://medium.com/p/7da892b5fec6</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[discogs]]></category>
            <dc:creator><![CDATA[Pablo Perez]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 20:19:32 GMT</pubDate>
            <atom:updated>2019-12-23T20:54:57.442Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have a big collection of records and you enjoy buying, selling and exploring records in Discogs.com you might have invested a lot of your time building your record collection to be available in the Discogs.com site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyLcGdTjA7j-EhX9RGSaDQ.png" /></figure><p>Discogs.com has an <a href="https://www.discogs.com/developers">API</a> , that you can leverage to have some high availability, or to operate it in a more automated way.</p><p>What if Discogs.com had some kind of internal issue and your collection were lost or let’s say they just stop providing their fantastic database.</p><p>I thought I could operate simultaneously both APIS by using AWS API Gateway along some lambdas and DynamoDB replicating the data on both AWS and Discos.com</p><p>From there more features can be added and even a frontend like ReactJS in S3 static hosting.</p><p>I’m providing a CloudFormation template that contains the necessary to build an API that allows you to sync your Discogs.com collection to DynamoDB as well as search, add and delete records on both your Discogs.com collection and DynamoDB table.</p><p>In order to launch this solution which is defined in the CloudFormation template found in <a href="https://github.com/pabloperfer/discogs2dynamodb/blob/master/dynadiscv3.yaml">Git</a> and inserted at the bottom of the article you will need to get a Discogs.com <a href="https://blog.discogs.com/en/api-update-discogs-auth/">Token</a>, and provide it along your Discogs.com user and the code files names uploaded to S3 for each lambda , which will respond performing a function for each API Gateway method.</p><p>The CloudFormation template has <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html">SAM</a> parts so you can launch it from the command line doing the transformation required by SAM, you would execute the command below (or create and execute a change set using the console):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af5faa02552352aeaf241470f5eeaa89/href">https://medium.com/media/af5faa02552352aeaf241470f5eeaa89/href</a></iframe><p>Below, you have the only CloudFormation template where we define all the API Gateway components needed (resources, methods, models, lambda functions and permissions).</p><p>You will enter in the parameters section the name of the S3 bucket where you have uploaded the lambda functions code you can find in my <a href="https://github.com/pabloperfer/discogs2dynamodb">Git repo</a> as well .</p><p>Due to the amount of code of some functions is required to store them in S3 instead of defining them directly in the template.</p><p>On the other hand you will need to pass in the parameter section your Discogs.com username and T<a href="https://www.discogs.com/settings/developers">oken</a> used by the lambdas to perform interact with Discogs.com API. You can get the Token for your user in the Discogs.com developer section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*98lYmiiw_jn6-rvg-fWE-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*EBRVvAnQ-krjBG5zmv7y2Q.png" /></figure><p>First step would be to invoke the <em>sync</em> method to populate your current Discogs.com records into your DDB table. No parameter is needed just go ahead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2KQzr16fyPWhAhq0lkH_2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuhKf4qDwAjXFdrUdXlFvA.png" /></figure><p>Now you can add records passing the release id like passing the Discogs.com release id of the record in the request headers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgFOegKESBK-gznL_FWk4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Up8h2mNrrgub64TooSeYUQ.png" /></figure><p>In order to search a record we will pass the band_name:Artist</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkPbK4NwMjSO9qyzeUKp2w.png" /></figure><p>To delete a record will pass the instance id, there’s one generated for each record we add from discogs, in this case 423749971 to the proper method in our API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_gNE4tyz6u4jTnnlmT6dg.png" /></figure><p>Another cool thing is that each time we add or delete a record through API gateway it gets added or deleted on both Dynamodb and our Discogs.com collection</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBrzQWWr-VqVWvnqyOCuJQ.png" /></figure><p>Finally there’s a scan method to retrieve all your records for a later pagination with ReactJS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qRkFo7rmfphrHyZVAQfiA.png" /></figure><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Transform: &#39;AWS::Serverless-2016-10-31&#39;<br>Description: Api that allows to sync you discogs.com collection to DynamoDB, and also allows to search, add, delete a record being this operation performed on both discogs.com and dynamoDB databases in a Serverless way.</pre><pre>Parameters:<br>  BucketName:<br>    Type: String<br>    Default: yours3bucketwhereyouuploadthecodeoflambdas<br>  CodeKeySync:<br>    Type: String<br>    Default: sync.zip<br>  CodeKeyRecordAdd:<br>    Type: String<br>    Default: addrecord.zip<br>  CodeKeyDelInstance:<br>    Type: String<br>    Default: delinstance.zip<br>  CodeKeyRecordSearch:<br>    Type: String<br>    Default: searchrecord.zip<br>  CodeKeyScanTable:<br>    Type: String<br>    Default: scantable.zip<br>  DDBName:<br>    Type: String<br>    Default: Records<br>  Token:<br>    Type: String<br>    Default: yourowntokennnnnnnnnnnnnnncDqypbeNPyHHYJMHQvn<br>    NoEcho: True<br>  User:<br>    Type: String<br>    Default: yourdiscogssuserrname</pre><pre>Resources:<br>  DDBTable:<br>    Type: AWS::DynamoDB::Table<br>    Properties:<br>      TableName: !Ref DDBName  <br>      AttributeDefinitions:<br>        -<br>          AttributeName: &quot;instance_id&quot;<br>          AttributeType: &quot;N&quot;<br>        -<br>          AttributeName: &quot;band&quot;<br>          AttributeType: &quot;S&quot;</pre><pre>KeySchema:<br>        -<br>          AttributeName: &quot;instance_id&quot;<br>          KeyType: &quot;HASH&quot;<br>   <br>      ProvisionedThroughput:<br>        ReadCapacityUnits: 2<br>        WriteCapacityUnits: 2</pre><pre>GlobalSecondaryIndexes: <br>        - <br>          IndexName: &quot;bandGSI&quot;<br>          KeySchema: <br>            - <br>              AttributeName: &quot;band&quot;<br>              KeyType: &quot;HASH&quot;<br>          <br>          Projection: <br>            ProjectionType: &quot;ALL&quot;<br>          ProvisionedThroughput: <br>            ReadCapacityUnits: &quot;1&quot;<br>            WriteCapacityUnits: &quot;1&quot;</pre><pre>CloudWatchRole: <br>    Type: AWS::IAM::Role<br>    Properties: <br>      AssumeRolePolicyDocument: <br>        Version: &quot;2012-10-17&quot;<br>        Statement: <br>          - Effect: Allow<br>            Principal: <br>              Service: <br>                - &quot;apigateway.amazonaws.com&quot;<br>            Action: &quot;sts:AssumeRole&quot;<br>      Path: &quot;/&quot;<br>      ManagedPolicyArns: <br>        - &quot;arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs&quot;</pre><pre>Account: <br>    Type: AWS::ApiGateway::Account<br>    Properties: <br>      CloudWatchRoleArn: <br>        &quot;Fn::GetAtt&quot;: <br>          - CloudWatchRole<br>          - Arn</pre><pre>MyRestApi:<br>    DependsOn: <br>      - Account<br>      - DDBTable<br>    Type: AWS::ApiGateway::RestApi<br>    Properties:<br>      EndpointConfiguration:<br>        Types:<br>          - REGIONAL<br>      Name: discsapi</pre><pre>Deployment:<br>    DependsOn: SyncMethod<br>    Type: AWS::ApiGateway::Deployment<br>    Properties: <br>      RestApiId: !Ref MyRestApi <br>      Description: &quot;My deployment&quot;<br>      StageName: Prod</pre><pre>SyncResource: <br>    Type: AWS::ApiGateway::Resource<br>    Properties: <br>      RestApiId: !Ref MyRestApi<br>      ParentId: <br>        Fn::GetAtt: <br>          - MyRestApi<br>          - RootResourceId<br>      PathPart: &quot;SyncResource&quot;</pre><pre>RecordAddResource: <br>    Type: AWS::ApiGateway::Resource<br>    Properties: <br>      RestApiId: !Ref MyRestApi<br>      ParentId: <br>        Fn::GetAtt: <br>          - MyRestApi<br>          - RootResourceId<br>      PathPart: &quot;RecordAddResource&quot;</pre><pre>DelInstanceResource: <br>    Type: AWS::ApiGateway::Resource<br>    Properties: <br>      RestApiId: !Ref MyRestApi<br>      ParentId: <br>        Fn::GetAtt: <br>          - MyRestApi<br>          - RootResourceId<br>      PathPart: &quot;DelInstanceResource&quot;</pre><pre>RecordSearchResource: <br>    Type: AWS::ApiGateway::Resource<br>    Properties: <br>      RestApiId: !Ref MyRestApi<br>      ParentId: <br>        Fn::GetAtt: <br>          - MyRestApi<br>          - RootResourceId<br>      PathPart: &quot;RecordSearchResource&quot;</pre><pre>ScanTableResource: <br>    Type: AWS::ApiGateway::Resource<br>    Properties: <br>      RestApiId: !Ref MyRestApi<br>      ParentId: <br>        Fn::GetAtt: <br>          - MyRestApi<br>          - RootResourceId<br>      PathPart: &quot;ScanTableResource&quot;<br>     <br>  SyncMethod:<br>    Type: &quot;AWS::ApiGateway::Method&quot;<br>    Properties:<br>      AuthorizationType: NONE<br>      HttpMethod: POST<br>      Integration:<br>        IntegrationHttpMethod: POST<br>        Type: AWS_PROXY<br>        Uri: !Sub<br>          - &quot;arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations&quot;<br>          - lambdaArn: !GetAtt SyncLambda.Arn<br>      ResourceId: !Ref SyncResource<br>      RestApiId: !Ref MyRestApi</pre><pre>ScanTableMethod:<br>    Type: &quot;AWS::ApiGateway::Method&quot;<br>    Properties:<br>      AuthorizationType: NONE<br>      HttpMethod: POST<br>      Integration:<br>        IntegrationHttpMethod: POST<br>        Type: AWS_PROXY<br>        Uri: !Sub<br>          - &quot;arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations&quot;<br>          - lambdaArn: !GetAtt ScanTableLambda.Arn<br>      ResourceId: !Ref ScanTableResource<br>      RestApiId: !Ref MyRestApi<br>    <br>  AddRecordMethod:<br>    Type: &quot;AWS::ApiGateway::Method&quot;<br>    Properties:<br>      AuthorizationType: NONE<br>      HttpMethod: POST<br>      Integration:<br>        IntegrationHttpMethod: POST<br>        Type: AWS_PROXY<br>        Uri: !Sub<br>          - &quot;arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations&quot;<br>          - lambdaArn: !GetAtt AddRecordLambda.Arn<br>      ResourceId: !Ref RecordAddResource<br>      RestApiId: !Ref MyRestApi<br>      RequestModels:<br>        application/json: !Ref ModelRecordAdd</pre><pre>DelInstanceMethod:<br>    Type: &quot;AWS::ApiGateway::Method&quot;<br>    Properties:<br>      AuthorizationType: NONE<br>      HttpMethod: POST<br>      Integration:<br>        IntegrationHttpMethod: POST<br>        Type: AWS_PROXY<br>        Uri: !Sub<br>          - &quot;arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations&quot;<br>          - lambdaArn: !GetAtt DelInstanceLambda.Arn<br>      ResourceId: !Ref DelInstanceResource<br>      RestApiId: !Ref MyRestApi<br>      RequestModels:<br>        application/json: !Ref ModelDelInstance</pre><pre>RecordSearchMethod:<br>    Type: &quot;AWS::ApiGateway::Method&quot;<br>    Properties:<br>      AuthorizationType: NONE<br>      HttpMethod: POST<br>      Integration:<br>        IntegrationHttpMethod: POST<br>        Type: AWS_PROXY<br>        Uri: !Sub<br>          - &quot;arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations&quot;<br>          - lambdaArn: !GetAtt SearchRecordLambda.Arn<br>      ResourceId: !Ref RecordSearchResource<br>      RestApiId: !Ref MyRestApi<br>      RequestModels:<br>        application/json: !Ref ModelRecordSearch</pre><pre>ModelRecordAdd:<br>    Type: AWS::ApiGateway::Model<br>    Properties:<br>      ContentType: &#39;application/json&#39;<br>      Description: RecordAdd  <br>      Name: RecordAdd<br>      RestApiId: !Ref MyRestApi<br>      Schema:<br>        type: object<br>        properties:<br>          release_id:<br>            type: string<br>        title: RecordAddModel</pre><pre>ModelDelInstance:<br>    Type: AWS::ApiGateway::Model<br>    Properties:<br>      ContentType: &#39;application/json&#39;<br>      Description: DelInstance  <br>      Name: DelInstance<br>      RestApiId: !Ref MyRestApi<br>      Schema:<br>        type: object<br>        properties:<br>          instance_id:<br>            type: string<br>        title: DelInstanceModel</pre><pre>ModelRecordSearch:<br>    Type: AWS::ApiGateway::Model<br>    Properties:<br>      ContentType: &#39;application/json&#39;<br>      Description: RecordSearch<br>      Name: RecordSearch<br>      RestApiId: !Ref MyRestApi<br>      Schema:<br>        type: object<br>        properties:<br>          band_name:<br>            type: string<br>        title: RecordSearchModel</pre><pre>SyncLambda:<br>    Type: &#39;AWS::Serverless::Function&#39;<br>    Properties:<br>      Handler: sync.lambda_handler<br>      Runtime: python3.7<br>      CodeUri: <br>        Bucket: !Ref BucketName<br>        Key: !Ref CodeKeySync<br>      MemorySize: 128<br>      Timeout: 100<br>      Policies:<br>        - AmazonDynamoDBFullAccess<br>      Environment:<br>        Variables:<br>          table: !Ref DDBTable<br>          my_token: !Ref Token<br>          user: !Ref User<br>          curr_region: !Ref &quot;AWS::Region&quot;</pre><pre>ScanTableLambda:<br>    Type: &#39;AWS::Serverless::Function&#39;<br>    Properties:<br>      Handler: scantable.lambda_handler<br>      Runtime: python3.7<br>      CodeUri: <br>        Bucket: !Ref BucketName<br>        Key: !Ref CodeKeyScanTable<br>      MemorySize: 128<br>      Timeout: 100<br>      Policies:<br>        - AmazonDynamoDBFullAccess<br>      Environment:<br>        Variables:<br>          table: !Ref DDBTable<br>          curr_region: !Ref &quot;AWS::Region&quot;</pre><pre>AddRecordLambda:<br>    Type: &#39;AWS::Serverless::Function&#39;<br>    Properties:<br>      Handler: addrecord.lambda_handler<br>      Runtime: python3.7<br>      CodeUri: <br>        Bucket: !Ref BucketName<br>        Key: !Ref CodeKeyRecordAdd<br>      MemorySize: 128<br>      Timeout: 100<br>      Policies:<br>        - AmazonDynamoDBFullAccess<br>      Environment:<br>        Variables:<br>          table: !Ref DDBTable<br>          token: !Ref Token<br>          user: !Ref User<br>          curr_region: !Ref &quot;AWS::Region&quot;</pre><pre>DelInstanceLambda:<br>    Type: &#39;AWS::Serverless::Function&#39;<br>    Properties:<br>      Handler: delinstance.lambda_handler<br>      Runtime: python3.7<br>      CodeUri: <br>        Bucket: !Ref BucketName<br>        Key: !Ref CodeKeyDelInstance<br>      MemorySize: 128<br>      Timeout: 100<br>      Policies:<br>        - AmazonDynamoDBFullAccess<br>      Environment:<br>        Variables:<br>          table: !Ref DDBTable<br>          token: !Ref Token<br>          user: !Ref User<br>          curr_region: !Ref &quot;AWS::Region&quot;</pre><pre>SearchRecordLambda:<br>    Type: &#39;AWS::Serverless::Function&#39;<br>    Properties:<br>      Handler: searchrecord.lambda_handler<br>      Runtime: python3.7<br>      CodeUri: <br>        Bucket: !Ref BucketName<br>        Key: !Ref CodeKeyRecordSearch<br>      MemorySize: 128<br>      Timeout: 100<br>      Policies:<br>        - AmazonDynamoDBFullAccess<br>      Environment:<br>        Variables:<br>          table: !Ref DDBTable<br>          curr_region: !Ref &quot;AWS::Region&quot;</pre><pre>lambdaApiGatewayInvokeSync:<br>    Type: &quot;AWS::Lambda::Permission&quot;<br>    Properties:<br>      Action: &quot;lambda:InvokeFunction&quot;<br>      FunctionName: !GetAtt &quot;SyncLambda.Arn&quot;<br>      Principal: apigateway.amazonaws.com<br>      SourceArn: !Sub &quot;arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyRestApi}/*/POST/*&quot;</pre><pre>lambdaApiGatewayScanTable:<br>    Type: &quot;AWS::Lambda::Permission&quot;<br>    Properties:<br>      Action: &quot;lambda:InvokeFunction&quot;<br>      FunctionName: !GetAtt &quot;ScanTableLambda.Arn&quot;<br>      Principal: apigateway.amazonaws.com<br>      SourceArn: !Sub &quot;arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyRestApi}/*/POST/*&quot;</pre><pre>lambdaApiGatewayInvokeRecordAdd:<br>    Type: &quot;AWS::Lambda::Permission&quot;<br>    Properties:<br>      Action: &quot;lambda:InvokeFunction&quot;<br>      FunctionName: !GetAtt &quot;AddRecordLambda.Arn&quot;<br>      Principal: apigateway.amazonaws.com<br>      SourceArn: !Sub &quot;arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyRestApi}/*/POST/*&quot;</pre><pre>lambdaApiGatewayInvokeDelInstance:<br>    Type: &quot;AWS::Lambda::Permission&quot;<br>    Properties:<br>      Action: &quot;lambda:InvokeFunction&quot;<br>      FunctionName: !GetAtt &quot;DelInstanceLambda.Arn&quot;<br>      Principal: apigateway.amazonaws.com<br>      SourceArn: !Sub &quot;arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyRestApi}/*/POST/*&quot;</pre><pre>lambdaApiGatewayRecordSearch:<br>    Type: &quot;AWS::Lambda::Permission&quot;<br>    Properties:<br>      Action: &quot;lambda:InvokeFunction&quot;<br>      FunctionName: !GetAtt &quot;SearchRecordLambda.Arn&quot;<br>      Principal: apigateway.amazonaws.com<br>      SourceArn: !Sub &quot;arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyRestApi}/*/POST/*&quot;</pre><p><a href="https://github.com/pabloperfer/discogs2dynamodb">https://github.com/pabloperfer/discogs2dynamodb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7da892b5fec6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pablo-perez/api-gateway-dynamodb-and-discogs-com-api-7da892b5fec6">API Gateway, DynamoDB and Discogs.com API</a> was originally published in <a href="https://medium.com/pablo-perez">Pablo Perez</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fastly launch an EKS cluster with eksctl deploying a docker Flask web app with cluster autoscaler…]]></title>
            <link>https://medium.com/pablo-perez/fastly-launch-an-eks-cluster-with-eksctl-deploying-a-docker-flask-web-app-with-cluster-autoscaler-218419d22cf7?source=rss----e6f453ad5d9d---4</link>
            <guid isPermaLink="false">https://medium.com/p/218419d22cf7</guid>
            <category><![CDATA[cluster-autoscaler]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Pablo Perez]]></dc:creator>
            <pubDate>Sat, 22 Jun 2019 22:08:35 GMT</pubDate>
            <atom:updated>2019-06-23T14:59:25.766Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Fastly launch an EKS cluster with eksctl deploying a docker Flask web app with cluster autoscaler and Prometheus metrics from scratch</strong></h3><p>This Web app shows Donald duck picture stored in S3 when accessing <em>/donalduck</em> and the time in the moment of request in Cohimbra City (Portugal) when accessing <em>/cohimbra</em>.</p><p>The App has built-in prometheus exporter providing metrics of the total number of requests to <em>/donalduck</em> uri and total number of requests to <em>/cohimbra</em> uri</p><p><strong>PART I : Launch an EKS with cluster scaler spread in two nodegroups in different AZs</strong></p><p>I use eksctl to create first the K8s control plane with the proper tags for cluster autoscaler.</p><pre><em>eksctl create cluster --config-file=cluster-1.yaml</em></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ba5c42b24db38ea9dbbef07488238e4/href">https://medium.com/media/0ba5c42b24db38ea9dbbef07488238e4/href</a></iframe><p>I ensure kubectl is well configured</p><pre><em>aws eks --region eu-west-1 update-kubeconfig --name cluster-1</em></pre><p>Then I create two nodegroups, each on a specific AZ as cluster autoscaler does not support Auto Scaling Groups which span multiple AZs.</p><p>I add the necessary tags and Iam permissions for the cluster autoscaler as well.</p><pre><em>eksctl create nodegroup --config-file=nodegroups.yaml</em></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23c4a98bf5a555a39a940bfdfe64fea0/href">https://medium.com/media/23c4a98bf5a555a39a940bfdfe64fea0/href</a></iframe><p>I create a Service Account for tiller to interact with the K8s cluster API.</p><pre><em>kubectl create -f rbac.yaml</em></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce2a373eec952a45bc6cd94618664a36/href">https://medium.com/media/ce2a373eec952a45bc6cd94618664a36/href</a></iframe><pre><em>kubectl apply -f rbac.yaml</em></pre><p>Then , I install helm and initialize it to install tiller in the EKS cluster</p><pre><em>helm init</em></pre><pre><em>helm repo update</em></pre><pre><em>helm fetch stable/cluster-autoscaler</em></pre><pre><em>tar -zxf cluster-autoscaler-0.13.2.tgz</em></pre><p>But before installing autoscaler we need to take into account that Tiller runs inside your Kubernetes cluster, and manages releases (installations) of our charts needing access to the Kubernetes API. By default, RBAC policies will not allow Tiller to carry out these operations, so we need to :</p><p>- Create a Service Account tiller for the Tiller server (in the kube-system namespace). Service Accounts are meant for intra-cluster processes running in Pods.</p><pre><em>kubectl create serviceaccount namespace kube-system tiller</em></pre><p>- Bind the cluster-admin ClusterRole to this Service Account in order for Tiller to manage resources in all namespaces.</p><p>The cluster-admin ClusterRole exists by default in the Kubernetes cluster, and allows superuser operations in all of the cluster resources. The reason for binding this role is because with Helm charts, we can have deployments consisting of a wide variety of Kubernetes resources.</p><pre><em>kubectl create clusterrolebinding tiller-cluster-rule  <br>--clusterrole=cluster-admin --serviceaccount=kube-system:tiller</em></pre><pre><em>kubectl patch deploy --namespace kube-system tiller-deploy -p ‘{“spec”:{“template”:{“spec”:{“serviceAccount”:”tiller”}}}}’</em></pre><p>Finally we install the autoscaler</p><pre><em>helm install stable/cluster-autoscaler -f values.yaml --name my-release</em></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a98e49cacc9d71119d2aa4499c3eb9d6/href">https://medium.com/media/a98e49cacc9d71119d2aa4499c3eb9d6/href</a></iframe><p>We test the autoscaler and we verify it balances across both nodegroups in different AZs</p><pre><em>kubectl run test --image=11111111111.dkr.ecr.eu-west-1.amazonaws.com/flasks3test --port=80 --replicas=30</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CCngYqkQ2MvAVce2" /></figure><p><strong>Part II : Create a Web App</strong></p><p>Create an app in Flask with the routes :</p><p><em>/donalduck</em> will invoke a function that uses boto3 to start a session with S3 and generate a presigned URL. The client browser will be redirected to this presigned url to see the image therefore the S3 bucket will be kept private. An instance profile will be used instead to generate the presigned url.</p><p><em>/cohimbra</em> will invoke a function that converts utc time to Lisbon time and this formatted time is rendered with the template.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17644f5dc6300cc5306cc47658285006/href">https://medium.com/media/17644f5dc6300cc5306cc47658285006/href</a></iframe><p><strong>Part III : dockerize the app</strong></p><pre><em>$cat Dockerfile</em></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70ba7f6ec8afd7b9fae648543f29e4e8/href">https://medium.com/media/70ba7f6ec8afd7b9fae648543f29e4e8/href</a></iframe><pre><em>sudo docker run -d -p 80:5000 --name=my_flask_app_container flasks3.test</em></pre><p><strong>Part IV: Create an ECR repo and store the image there</strong></p><pre><em>sudo docker tag flasks3.test 11111111111.dkr.ecr.eu-west-1.amazonaws.com/flasks3test</em></pre><pre><em>aws ecr get-login --no-include-email --region eu-west-1</em></pre><p>(copy and execute the output)</p><pre><em>sudo docker push 11111111111.dkr.ecr.eu-west-1.amazonaws.com/flasks3test</em></pre><p><strong>Part V: Create a service for the app</strong></p><pre><em>kubectl create -f flaskdeployment.yaml</em></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c579331197ebf90c63491e8f10f64125/href">https://medium.com/media/c579331197ebf90c63491e8f10f64125/href</a></iframe><pre><em>kubectl create -f flask_service.yaml</em></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d10698c2fe9bcc3c8058c6e32e3543f9/href">https://medium.com/media/d10698c2fe9bcc3c8058c6e32e3543f9/href</a></iframe><p><strong>Part VI: Install prometheus</strong></p><p>For this just take a look at this link below in order to configure the NodePort type for the server and be able to access prometheus from the worker node ip:</p><p><a href="https://eksworkshop.com/monitoring/deploy-prometheus/">https://eksworkshop.com/monitoring/deploy-prometheus/</a></p><p>In the prometheus values file ensure you have this excerpt, if not add it</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/614e5edd3b3b773765bf52358180fa84/href">https://medium.com/media/614e5edd3b3b773765bf52358180fa84/href</a></iframe><p>Finally execute</p><pre><em>helm install -f prometheus-values.yaml stable/prometheus --name prometheus --namespace prometheus</em></pre><p>You will find the app metrics endpoint in targets and in the graph section you will be able to see the total number of requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DBrARs65mow5lQk0" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1V_E4rwUmIYoQ7dz" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=218419d22cf7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pablo-perez/fastly-launch-an-eks-cluster-with-eksctl-deploying-a-docker-flask-web-app-with-cluster-autoscaler-218419d22cf7">Fastly launch an EKS cluster with eksctl deploying a docker Flask web app with cluster autoscaler…</a> was originally published in <a href="https://medium.com/pablo-perez">Pablo Perez</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How can I avoid waiting for one hour if my custom resource lambda function fails to execute?]]></title>
            <link>https://medium.com/pablo-perez/how-can-i-avoid-waiting-for-one-hour-if-my-custom-resource-lambda-function-fails-to-execute-b1e17fe6de25?source=rss----e6f453ad5d9d---4</link>
            <guid isPermaLink="false">https://medium.com/p/b1e17fe6de25</guid>
            <category><![CDATA[time-out]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[custom-resource]]></category>
            <category><![CDATA[fail]]></category>
            <dc:creator><![CDATA[Pablo Perez]]></dc:creator>
            <pubDate>Tue, 26 Mar 2019 15:13:37 GMT</pubDate>
            <atom:updated>2019-04-22T18:29:24.097Z</atom:updated>
            <content:encoded><![CDATA[<p>We need a couple of things:</p><p>1.- Catch and handle the exception (lambda execution error) to send the FAILED status signal back to CloudFormation before the lambda execution terminates:</p><pre>try:<br>    #function code<br> …<br> …<br> except Exception:<br>    #sending FAILED signal to CloudFormation<br>     cfnresponse.send(event, context, cfnresponse.FAILED, responseData, physicalResourceId )</pre><p>2.- We will enable also a system logger, optionally set to DEBUG level, to get further information in CloudWatch logs of all the execution actions as well as the stack trace of the exception being raised.</p><pre>import logging<br>logging.basicConfig(level=logging.DEBUG)<br>log = logging.getLogger(__name__)</pre><pre>try:<br>    #function code<br>except Exception:<br>    log.exception(“Lambda execution has failed!”)</pre><p>As an example let’s create a custom resource that creates a S3 bucket and tags it with the Stack Name.</p><p>After creating a stack with a faulty lambda function , the below would be showed in Cloudwatch logs if try to create a S3 bucket specifying a wrong region :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0LtntKyJzW1cFzvnC3CfAQ.png" /></figure><p>Or if you specify an invalid name for the bucket with capital letters :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GN5Yrl4eiRqVKJbmxVNCQg.png" /></figure><p>You can see the stack fails immediately…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWGv_AwurC83UKjTywpklw.png" /></figure><p>here you have the template, just insert a capital letter in the parameter for the bucket name to make it fail</p><pre>Parameters:<br>  S3BucketName:<br>    Type: String<br>    Default: ttngmys3bktname</pre><pre>FunctionRole:<br>    Type: String<br>    Default: &quot;arn:aws:iam::759661093277:role/lambda_s3_exec_role&quot;</pre><pre>Resources:<br>  MyCustomResource:<br>    Type: Custom::MyCustomResource<br>    Properties:<br>      ServiceToken: !GetAtt MyLambdaFunction.Arn<br>      StackName: !Ref AWS::StackName<br>      NewS3Bucket: !Ref S3BucketName</pre><pre>MyLambdaFunction:<br>    Type: &quot;AWS::Lambda::Function&quot;<br>    Description: Creates a S3 bucket and tags it with the stack name.<br>    Properties:<br>      Handler: &quot;index.lambda_handler&quot;<br>      Role: !Ref FunctionRole<br>      Timeout: 15<br>      Runtime: python3.6<br>      Code:<br>        ZipFile: |<br>          import boto3<br>          import cfnresponse<br>          import logging<br>          import time</pre><pre>def lambda_handler(event, context):<br>              logging.basicConfig(level=logging.DEBUG)<br>              log = logging.getLogger(__name__)<br>         <br>              responseData = {}<br>              physicalResourceId = {}<br>              s3 = boto3.client(&#39;s3&#39;)</pre><pre>if event[&#39;RequestType&#39;] == &#39;Delete&#39;:<br>                  try:<br>         <br>                      NewS3Bucket = event[&#39;ResourceProperties&#39;][&#39;NewS3Bucket&#39;]<br>                      bucket = s3.Bucket(NewS3Bucket)<br>                      for key in bucket.objects.all():<br>                          key.delete()<br>                          bucket.delete()<br>                          cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, physicalResourceId )<br>                          return<br>                  except Exception:<br>                      cfnresponse.send(event, context, cfnresponse.FAILED, responseData, physicalResourceId )<br>                      log.exception(&quot;Lambda execution has failed!&quot;)<br>                      return</pre><pre>try:<br>                  NewS3Bucket = event[&#39;ResourceProperties&#39;][&#39;NewS3Bucket&#39;]<br>                  StackName = event[&#39;ResourceProperties&#39;][&#39;StackName&#39;]<br>              <br>                  s3.create_bucket(Bucket=NewS3Bucket)<br>                  time.sleep(5)<br>                  response = s3.put_bucket_tagging(<br>                      Bucket=NewS3Bucket,<br>                      Tagging={<br>                          &#39;TagSet&#39;: [<br>                          {<br>                          &#39;Key&#39;: &#39;StackName&#39;,<br>                          &#39;Value&#39;: StackName<br>                          },] })<br>    <br>                  cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, physicalResourceId )<br>                  return<br>              except Exception:<br>                  cfnresponse.send(event, context, cfnresponse.FAILED, responseData, physicalResourceId )<br>                  log.exception(&quot;Lambda execution has failed!&quot;)<br>                  return</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1e17fe6de25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pablo-perez/how-can-i-avoid-waiting-for-one-hour-if-my-custom-resource-lambda-function-fails-to-execute-b1e17fe6de25">How can I avoid waiting for one hour if my custom resource lambda function fails to execute?</a> was originally published in <a href="https://medium.com/pablo-perez">Pablo Perez</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to automatically deploy new Docker image updates in an ECS service being the Dockerfiles in…]]></title>
            <link>https://medium.com/pablo-perez/how-to-automatically-deploy-new-docker-image-updates-in-an-ecs-service-being-the-dockerfiles-in-742d44a36d32?source=rss----e6f453ad5d9d---4</link>
            <guid isPermaLink="false">https://medium.com/p/742d44a36d32</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec]]></category>
            <category><![CDATA[ecr]]></category>
            <category><![CDATA[codepipeline]]></category>
            <category><![CDATA[bitbucket]]></category>
            <dc:creator><![CDATA[Pablo Perez]]></dc:creator>
            <pubDate>Thu, 03 Jan 2019 22:52:09 GMT</pubDate>
            <atom:updated>2019-01-03T22:53:40.958Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How to automatically deploy new Docker image updates in an ECS service being the Dockerfiles in BitBucket and the Docker images in ECR.</strong></h3><p><strong>How to automatically deploy new Docker image updates in an ECS service being the Dockerfiles in BitBucket and the Docker images in ECR.</strong></p><p><strong>Part 0. What we already have.</strong></p><p>Having a use case where the developers update Dockerfile versions all the time, and needing to automatically update our ECS service tasks with the correspondent image new versions we will need to deploy the following to achieve this.</p><p>Very detailed explanation:</p><p>We have a bitbucket repository where the Dockerfile is and gets updated from time to time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*jPY6gyPgBG2KB1hR_jrk7Q.png" /></figure><p>We have an ECS cluster where a service runs task from a task definition with the resulting image of the original Dockerfile which has been pushed to ECR before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*iY1Q3VOucKLg4AI_3TPkLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*IafdXQ1ay6r3slus2nN9lQ.png" /></figure><p>We’ll start creating the AWS CodePipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*x2Cj9CLCK9mODH5vjb6-gg.png" /></figure><p>However, You can see CodePipeline doesn’t support Bitbucket…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Dq1ggVTOV7wkEbcYEtKsxw.png" /></figure><p>So, in order to integrate BitBucket with CodePipeline you will need to:</p><p><strong>PART 1. Preparing webhooks.</strong></p><ol><li>- Get the Oath Key from BitBucket. Click on “Settings” under your avatar and click on “Oauth”, then click on “Add consumer”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Xrpu0g6p3uLINCfiGCashQ.png" /></figure><p>Annotate the resulting Key and Secret.</p><p>2.- This QuickStart implements the required like a lambda function triggered by a webhook in order to pull your new Bitbucket commits and zip up the code placing it in S3. When this function. In this way you bridge Git services with AWS services like AWS CodePipeline.</p><p>In the following link click on “launch quickstart”:</p><p><a href="https://aws.amazon.com/quickstart/architecture/git-to-s3-using-webhooks/">https://aws.amazon.com/quickstart/architecture/git-to-s3-using-webhooks/</a></p><p>This will open a CloudFormation console, please, be aware that by default it’s launched in OHIO region and it has to be in the region where you have your pipeline!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*AwhkVBTEp2bTSXCo9UIEHg.png" /></figure><p>Leave the parameter fields as follows, you only need to add the OAuth2 key and secret you creted before:</p><p>I have set <strong>0.0.0.0/0 </strong>in Allowed IPs as other ip ranges were used like 18.234.32.227, 18.234.32.226 and 18.234.32.225 as I could see in the Lambda function (created by the Quickstart CloudFormation stack) Cloudwatch logs that pull the content and uploaded it to S3. For further hardening check with Atlassian.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Y1yHW1XicMbFINtwpwiLjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*nbgC5qs5HjgT0L4p5nFhBQ.png" /></figure><p>Once the CloudFormation stack completes the creation process annotate the following values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*x9S4P4Lt2mVU6spi6kSTug.png" /></figure><p>3.- Now create the Webhook in your Bitbucket account.</p><p>Click settings under your “repo” and click “Add Webhook”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*WngDzeCwHw_DwUtcllJNAA.png" /></figure><p>Then you will only fill the URL part, use the GitPullWebHookApi value which is the webhook endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*PJBMnjH3JPaNnzJTmFZrAQ.png" /></figure><p>4.- Copy the SSH public key generated in the Outputs section of the CloudFormation stack and add it in your bitbucket repo keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*8smn26qfJDceQrDXKQsymw.png" /></figure><p><strong>PART 2. Creating the Pipeline.</strong></p><p>1.- Now, we’ll start creating the AWS CodePipeline from scratch, in the “Source” stage we’ll select S3 as the source provider and the S3 bucket name generated in the CloudFormation stack outputs, this is “OutputBucketName”. The object key will be Dockerfile as it is what the developers will commit.</p><p>The S3 Object Key is composed like this:</p><p>yourbitbucketaccountuser/ yourbitbucketreponame /branch/master/yourbitbucketaccountuser_yourbitbucketreponame_branch_master.zip</p><p><a href="https://s3-eu-west-1.amazonaws.com/git-to-amazon-s3v2-outputbucket-6d77x8virh5b/pabloperfer/testimage/branch/master/pabloperfer_testimage_branch_master.zip">pabloperfer/testimage/branch/master/pabloperfer_testimage_branch_master.zip</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*s5CuEcDG39EswlaCti-BbA.png" /></figure><p>2.- In the next stage we’ll select Codebuild as the Build provider, we will create a project and we’ll generate the necessary output artifact containing the container and image name in order for ECS to deploy .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*pkKzn1niKtfX-f_KEvtLJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*GCrHkKSBV7ktL_nBWdOOnw.png" /></figure><p>Click on “insert build” commands and then “switch to editor”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*hTrXU8rwBIQ_9lgJbUiQ9w.png" /></figure><p>Be very careful at this point when you create imagedefinitions.json. It needs the exact container name to be passed, it has to match with the container name running in the task</p><p>[{“name”:”<em>container_name</em>”,”imageUri”:”<em>image_URI</em>”}]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*_vsJhvmfNPv15CdouooLRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*F7VhGx0VPx006BEBCwoHyA.png" /></figure><p>Add ECR permissions to the CodeBuild role</p><p>4.- The last stage will be the deploy one, where we’ll select the ECS cluster, service and provide the image definitions json file which indicates the image to deploy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*5z6vuJ9cuGKIGIZWFOqxBQ.png" /></figure><p><strong>Part 3. From the developer push in bitbucket to the deploy in ECS.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*pY3O8j3tQ3h6uAQ0w8SjMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*HIFw_EhErYsmAWeSfEn_-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*sOQFZbPdUL4x80fejyZMwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*MWDVhLeF1RPK__YB2PsIpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*X7H9DVXmsoa5mG_jZHZnew.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=742d44a36d32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pablo-perez/how-to-automatically-deploy-new-docker-image-updates-in-an-ecs-service-being-the-dockerfiles-in-742d44a36d32">How to automatically deploy new Docker image updates in an ECS service being the Dockerfiles in…</a> was originally published in <a href="https://medium.com/pablo-perez">Pablo Perez</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>