<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kay Ren Fa on Medium]]></title>
        <description><![CDATA[Stories by Kay Ren Fa on Medium]]></description>
        <link>https://medium.com/@kay.renfa?source=rss-2d401c9d729d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uNhiU4oiC7gjJDxT</url>
            <title>Stories by Kay Ren Fa on Medium</title>
            <link>https://medium.com/@kay.renfa?source=rss-2d401c9d729d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:47:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kay.renfa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dynamic nightmare for Terraforming AWS WAFV2]]></title>
            <link>https://medium.com/@kay.renfa/dynamic-nightmare-for-terraforming-aws-wafv2-d0513600c25d?source=rss-2d401c9d729d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0513600c25d</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Kay Ren Fa]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 11:04:59 GMT</pubDate>
            <atom:updated>2023-09-12T03:30:52.206Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*qioP08OhthASQeug" /></figure><p>A couple of weeks ago, I started working on implementing Web Application Firewall (WAF) on our ALB. A quick introduction of WAF, it is an AWS resource that can be associated to Cloudfront, ALB and/or API Gateway API. It can be used to inspect all request that go through the resource and then it blocks, challenges, captcha, counts or allows the request if it matches certain rules. The rules can be self defined like IP Set, Geolocation or managed rules like Cross-site scripting, SQL Injection.</p><p>Going through the <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/wafv2_web_acl.html">Terraform documentation</a>, I was blown away how tedious it is to implement the resources. Most of the AWS resources provides granular sub-resource, for example for IAM, there is one for policy, role and one to associate both together.</p><pre>resource &quot;aws_iam_group&quot; &quot;group&quot; {<br>  name = &quot;test-group&quot;<br>}<br><br>data &quot;aws_iam_policy_document&quot; &quot;policy&quot; {<br>  statement {<br>    effect    = &quot;Allow&quot;<br>    actions   = [&quot;ec2:Describe*&quot;]<br>    resources = [&quot;*&quot;]<br>  }<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;policy&quot; {<br>  name        = &quot;test-policy&quot;<br>  description = &quot;A test policy&quot;<br>  policy      = data.aws_iam_policy_document.policy.json<br>}<br><br>resource &quot;aws_iam_policy_attachment&quot; &quot;test-attach&quot; {<br>  name       = &quot;test-attachment&quot;<br>  groups     = [aws_iam_group.group.name]<br>  policy_arn = aws_iam_policy.policy.arn<br>}</pre><p>Whereas for WAF, it is one single resource that tries to do everything at one go which is very different from others. Even for AWS step function that can have complex rules, it takes in a JSON input of the whole state machine. AWS CodeDeploy/CodePipeline that has a long set of attributes or nested blocks, it wasn’t that painful to implement. Hence, it blew my mind that it doesn’t follow the same design principles like the others. Going through both <a href="https://docs.aws.amazon.com/cli/latest/reference/wafv2/update-web-acl.html">AWS documentation</a> and <a href="https://github.com/hashicorp/terraform-provider-aws/blob/b45c86f8550effb632ca60335538ce2a04164d5f/internal/service/wafv2/web_acl.go">Terraform source code</a>, I guess it is mostly AWS “fault” to implement such a convoluted resource since there are no sub-resource to create.</p><p>The reason why it grinds my gear is because having a smaller set of “resources” allows us to have more flexibility to add extensibility from variables without much hassle. For wafv2_acl`, we will have to add numerous dynamic blocks for us to have extensibility. Not saying dynamic blocks are bad, but having too many makes the code unreadable and even harder to visualise the end output as dynamic iterates and generates a set of code.</p><p>To refresh everyone’s memory how dynamic block works on Terraform. Dynamic can be used to generate copies of block. Below are 3 snippet of code, where first 2 generate the same output, and 3rd doesn’t.</p><pre>//Version A<br>resource &quot;aws_something&quot; &quot;main&quot; {<br>  rule {<br>    attribute = &quot;valueA&quot;<br>  }<br>  rule {<br>    attribute = &quot;valueB&quot;<br>  }<br>  rule {<br>    attribute = &quot;valueC&quot;<br>  }<br>}<br><br>//Version B<br>variable &quot;input_variable&quot; {<br>  type    = list<br>  default = [&quot;valueA&quot;, &quot;valueB&quot;, &quot;valueC&quot;]<br>}<br><br>resource &quot;aws_something&quot; &quot;main_same&quot; {<br>  dynamic &quot;rule&quot;{<br>    for_each = var.input_variable<br>    content {<br>      attribute = rule.value<br>    }<br>  }<br>}<br><br>//Version C - Wrong example as it create an array of map<br>resource &quot;aws_something&quot; &quot;main_wrong&quot; { <br>  rule = [for s in var.input_variable : {attribute:s}]<br>}<br>/*<br>resource &quot;aws_something&quot; &quot;main_wrong_output&quot; { <br>  rule = [<br>          {attribute:&quot;valueA&quot;},<br>          {attribute:&quot;valueB&quot;}, <br>          {attribute:&quot;valueC&quot;}<br>        ]<br>}<br>*/</pre><p>If you compare Version C and Version A, there is a slight difference. Version C takes in an array, but Version A itself is a block of “rule”. I have slight bias-ness for using map object as provides more extensibility than dynamic. WAF for terraform further amplify this problem by a few fold with by needing multiple nested blocks.</p><p>Though I agree that WAF provides an extensive customisation and not everyone has the same use case. But I think for 80% of the users are simple minded people like me. I use it with a simple use case, scan all requests, block requests that match the rules, else allow. As mentioned, everyone has different needs, hence, there is no silver bullet to implement WAF.</p><p>Fear not, for this 80% group of people, I have simplified the implementation.</p><pre>resource &quot;aws_wafv2_web_acl&quot; &quot;main&quot; {<br>  name  = &quot;waf-${var.name}-acl-alb&quot;<br>  scope = &quot;REGIONAL&quot;<br><br>  default_action {<br>    allow {}<br>  }<br><br>  rule {<br>    name     = &quot;waf-block-ipset&quot;<br>    priority = 0<br>    action {<br>      block {}<br>    }<br>    statement {<br>      ip_set_reference_statement {<br>        arn = aws_wafv2_ip_set.block.arn<br>      }<br>    }<br>    visibility_config {<br>      cloudwatch_metrics_enabled = true<br>      metric_name                = &quot;waf-block-ipset&quot;<br>      sampled_requests_enabled   = true<br>    }<br>  }<br><br>  dynamic &quot;rule&quot; {<br>    for_each = toset(var.rules)<br>    content {<br>      name     = rule.value.name<br>      priority = rule.value.priority<br>      override_action {<br>        none {}<br>      }<br>      statement {<br>        managed_rule_group_statement {<br>          name        = rule.value.name<br>          vendor_name = rule.value.vendor_name<br>          dynamic &quot;managed_rule_group_configs&quot; {<br>            for_each = rule.value.name == &quot;AWSManagedRulesBotControlRuleSet&quot; ? [1] : []<br>            content {<br>              aws_managed_rules_bot_control_rule_set {<br>                inspection_level = &quot;COMMON&quot;<br>              }<br>            }<br>          }<br>          dynamic &quot;rule_action_override&quot; {<br>            for_each = rule.value.allow<br>            content {<br>              name = rule_action_override.value<br>              action_to_use {<br>                allow {}<br>              }<br>            }<br>          }<br>          dynamic &quot;rule_action_override&quot; {<br>            for_each = rule.value.block<br>            content {<br>              name = rule_action_override.value<br>              action_to_use {<br>                block {}<br>              }<br>            }<br>          }<br>          dynamic &quot;rule_action_override&quot; {<br>            for_each = rule.value.count<br>            content {<br>              name = rule_action_override.value<br>              action_to_use {<br>                count {}<br>              }<br>            }<br>          }<br>          dynamic &quot;rule_action_override&quot; {<br>            for_each = rule.value.challenge<br>            content {<br>              name = rule_action_override.value<br>              action_to_use {<br>                challenge {}<br>              }<br>            }<br>          }<br>          dynamic &quot;rule_action_override&quot; {<br>            for_each = rule.value.captcha<br>            content {<br>              name = rule_action_override.value<br>              action_to_use {<br>                captcha {}<br>              }<br>            }<br>          }<br>        }<br>      }<br>      visibility_config {<br>        cloudwatch_metrics_enabled = true<br>        metric_name                = rule.value.name<br>        sampled_requests_enabled   = true<br>      }<br>    }<br>  }<br>  visibility_config {<br>    cloudwatch_metrics_enabled = true<br>    metric_name                = &quot;cw-${var.name}-waf-alb&quot;<br>    sampled_requests_enabled   = true<br>  }<br>}<br><br>resource &quot;aws_wafv2_web_acl_association&quot; &quot;main&quot; {<br>  resource_arn = var.alb.alb_arn<br>  web_acl_arn  = aws_wafv2_web_acl.main.arn<br>}<br><br>resource &quot;aws_wafv2_ip_set&quot; &quot;block&quot; {<br>  name               = &quot;waf-${var.name}-block-ipset-alb&quot;<br>  scope              = &quot;REGIONAL&quot;<br>  ip_address_version = &quot;IPV4&quot;<br>  addresses          = var.block_ip_set<br>}<br><br>variable &quot;rules&quot; {<br>  type = list(any)<br>  default = [{<br>    name        = &quot;AWSManagedRulesCommonRuleSet&quot;<br>    vendor_name = &quot;AWS&quot;<br>    priority    = 1<br>    allow = [<br>      &quot;SizeRestrictions_BODY&quot;,<br>      &quot;CrossSiteScripting_BODY&quot;<br>    ]<br>    block = [<br>      &quot;NoUserAgent_HEADER&quot;,<br>      &quot;UserAgent_BadBots_HEADER&quot;,<br>      &quot;SizeRestrictions_QUERYSTRING&quot;,<br>      &quot;SizeRestrictions_Cookie_HEADER&quot;,<br>      &quot;SizeRestrictions_URIPATH&quot;,<br>      &quot;EC2MetaDataSSRF_BODY&quot;,<br>      &quot;EC2MetaDataSSRF_COOKIE&quot;,<br>      &quot;EC2MetaDataSSRF_URIPATH&quot;,<br>      &quot;EC2MetaDataSSRF_QUERYARGUMENTS&quot;,<br>      &quot;GenericLFI_QUERYARGUMENTS&quot;,<br>      &quot;CrossSiteScripting_URIPATH&quot;,<br>      &quot;GenericLFI_URIPATH&quot;,<br>      &quot;GenericLFI_BODY&quot;,<br>      &quot;RestrictedExtensions_URIPATH&quot;,<br>      &quot;RestrictedExtensions_QUERYARGUMENTS&quot;,<br>      &quot;GenericRFI_QUERYARGUMENTS&quot;,<br>      &quot;GenericRFI_BODY&quot;,<br>      &quot;GenericRFI_URIPATH&quot;,<br>      &quot;CrossSiteScripting_COOKIE&quot;,<br>      &quot;CrossSiteScripting_QUERYARGUMENTS&quot;,<br>    ]<br>    captcha   = []<br>    challenge = []<br>    count     = []<br>    }, {<br>    name        = &quot;AWSManagedRulesLinuxRuleSet&quot;<br>    vendor_name = &quot;AWS&quot;<br>    priority    = 2<br>    allow       = []<br>    block = [<br>      &quot;LFI_URIPATH&quot;,<br>      &quot;LFI_QUERYSTRING&quot;,<br>      &quot;LFI_HEADER&quot;<br>    ]<br>    captcha   = []<br>    challenge = []<br>    count     = []<br>    }, {<br>    name        = &quot;AWSManagedRulesUnixRuleSet&quot;<br>    vendor_name = &quot;AWS&quot;<br>    priority    = 3<br>    allow       = []<br>    block = [<br>      &quot;UNIXShellCommandsVariables_QUERYARGUMENTS&quot;,<br>      &quot;UNIXShellCommandsVariables_BODY&quot;,<br>    ]<br>    captcha   = []<br>    challenge = []<br>    count     = []<br>    }, {<br>    name        = &quot;AWSManagedRulesSQLiRuleSet&quot;<br>    vendor_name = &quot;AWS&quot;<br>    priority    = 4<br>    allow       = []<br>    block = [<br>      &quot;SQLi_QUERYARGUMENTS&quot;,<br>      &quot;SQLiExtendedPatterns_QUERYARGUMENTS&quot;,<br>      &quot;SQLi_BODY&quot;,<br>      &quot;SQLiExtendedPatterns_BODY&quot;,<br>      &quot;SQLi_COOKIE&quot;,<br>    ]<br>    captcha   = []<br>    challenge = []<br>    count     = []<br>    }, {<br>    name        = &quot;AWSManagedRulesKnownBadInputsRuleSet&quot;<br>    vendor_name = &quot;AWS&quot;<br>    priority    = 5<br>    allow       = []<br>    block = [<br>      &quot;JavaDeserializationRCE_HEADER&quot;,<br>      &quot;JavaDeserializationRCE_BODY&quot;,<br>      &quot;JavaDeserializationRCE_URIPATH&quot;,<br>      &quot;JavaDeserializationRCE_QUERYSTRING&quot;,<br>      &quot;Host_localhost_HEADER&quot;,<br>      &quot;PROPFIND_METHOD&quot;,<br>      &quot;ExploitablePaths_URIPATH&quot;,<br>      &quot;Log4JRCE_HEADER&quot;,<br>      &quot;Log4JRCE_QUERYSTRING&quot;,<br>      &quot;Log4JRCE_BODY&quot;,<br>      &quot;Log4JRCE_URIPATH&quot;,<br>    ]<br>    captcha   = []<br>    challenge = []<br>    count     = []<br>    }, {<br>    name        = &quot;AWSManagedRulesBotControlRuleSet&quot;<br>    vendor_name = &quot;AWS&quot;<br>    priority    = 6<br>    allow = [<br>      &quot;SignalAutomatedBrowser&quot;,<br>      &quot;CategoryHttpLibrary&quot;,<br>      &quot;SignalNonBrowserUserAgent&quot;<br>    ]<br>    block     = []<br>    captcha   = []<br>    challenge = []<br>    count = [<br>      &quot;CategoryAdvertising&quot;,<br>      &quot;CategoryArchiver&quot;,<br>      &quot;CategoryContentFetcher&quot;,<br>      &quot;CategoryEmailClient&quot;,<br>      &quot;CategoryLinkChecker&quot;,<br>      &quot;CategoryMiscellaneous&quot;,<br>      &quot;CategoryMonitoring&quot;,<br>      &quot;CategoryScrapingFramework&quot;,<br>      &quot;CategorySearchEngine&quot;,<br>      &quot;CategorySecurity&quot;,<br>      &quot;CategorySeo&quot;,<br>      &quot;CategorySocialMedia&quot;,<br>      &quot;CategoryAI&quot;,<br>      &quot;SignalKnownBotDataCenter&quot;<br>    ]<br>    }<br>  ]<br>}<br><br>variable &quot;alb&quot; {<br>  type        = map(any)<br>  description = &quot;Map of Application (with alb) dependency outputs&quot;<br>}<br><br>variable &quot;name&quot; {<br>  default     = &quot;resource&quot;<br>  type        = string<br>}<br><br>variable &quot;block_ip_set&quot; {<br>  default     = []<br>  type        = list(string)<br>  description = &quot;List of IP to block&quot;<br>}</pre><p>If you see the `aws_wafv2_web_acl` resource, it has layers of dynamic block. But with the simple list of variables, it is much easier to configure the rules many assumption that we reuse the same name as the rules, and little to no customisation to these rules. At least its less painful to customise the input now! With this code, you can have “count” for dev and staging environment and “block” for production with the same implementation.</p><p>I hope the above code solves some of the pain point when introducing WAF ACL. Do note that above does not cover all scenario, hence, feel free to extend to the code! Til next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0513600c25d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple ECS Deploy via Gitlab]]></title>
            <link>https://medium.com/@kay.renfa/multiple-ecs-deploy-via-gitlab-5334ce258472?source=rss-2d401c9d729d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5334ce258472</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Kay Ren Fa]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 06:24:50 GMT</pubDate>
            <atom:updated>2023-08-10T01:36:46.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*8sCTAQyjMY6CHlap" /></figure><p>Gitlab provides a way to allow one to <a href="https://docs.gitlab.com/ee/ci/cloud_deployment/ecs/deploy_to_aws_ecs.html">deploy your containerised application to ECS</a>. Documentation briefly explains to you that you need to provide some of the variables like the ECS Cluster, Service, etc but it doesn’t go into detail how it works under the hood.</p><p>In my opinion, it will be challenging if I do not know what is happening in the deployment process. Specifically, does it handle pushing the images? How does it handle the task definition? Is it able to deploy multiple services under single job? Does it allow blue-green deployment? And so on.</p><p>In order for me to clear my doubt, I had to zoom into Gitlab’s implementation of their template code. For the curious minds, it can be found <a href="https://gitlab.com/gitlab-org/cloud-deploy/-/blob/master/aws/src/bin/ecs?ref_type=heads">here</a>.</p><p>After studying the code, I start to understand what is happening. The code provides two ways to deploy.</p><p>The first way is when you don’t specify CI_AWS_ECS_TASK_DEFINITION_FILE variable which it will then fetching task definition from CI_AWS_ECS_TASK_DEFINITION . Using the latest task definition, it will do couple of jq operation to replace the first container image name to your image name and tag. This is really neat for basic usage as it registers a new revision every time which means it gives you a way to rollback your service to previous revision. Alternative will be just redeploying your code via Gitlab. Just by using this method, you are better than many teams because some might just go via the shortcut manner, reusing the same tag such as latest and then stopping the task to refresh the container images.</p><p>Second way is simply provide task definition as a file. It reads the file and deploy as it is. I guess the general expectation to use this method is to commit your task definition file into your git repository. This essentially means you will end up doing what I just mentioned which is fixate on a particular image tag. Alternatively, you might need to overwrite the default job and add before_script to dynamically generate these new task definition file.</p><p>In summary, these are some of the shortfalls</p><ol><li>It doesn’t handle image pushing</li><li>It doesn’t allow deployment of multiple ECS Services</li><li>It doesn’t support blue green deployment</li></ol><p>As covered in my recent post on <a href="https://medium.com/@kay.renfa/ci-cd-pipeline-design-principles-crafts-a62a3f79c660">CI/CD Pipeline Design Principles</a>, I mentioned about one point on completeness. One of my use case is I have 3 AWS account which means I will have 3 ECR (i.e. development, staging and production). Hence, it doesn’t fulfil my criteria because I need one stage to push my image before I can deploy the new task definition and service.</p><p>Another challenge as part of completeness is that my application is single git repository that builds multiple container images and these images are tightly coupled, with frontend and backend service. Hence, I don’t want it to be stuck in a position where the application is partially deploy as it might have unforeseen problem. Hence, the current method doesn’t meet my needs.</p><p>Thirdly, I have a use case where the developers want to display the semantic version of the code deployed to the environment on the frontend application. This means that I will need a way to dynamically modify the task definition based on variable in additional to the image tag.</p><p>Lastly, one of the image I deployed is used for Database migration which I run it as ECS task which triggers from Eventbridge image pushevent. This task gets created, apply database migration and end gracefully. Essentially, this is not an ECS Service.</p><p>How to best tackle these problem with the least amount of work? Well I had to re-engineer the ECS deploy method that gitlab has provided and reusing that they have provided.</p><p>To summarise what are my 4 needs:</p><ol><li>To authenticate, pull, retag, re-authenticate and push multiple images to destination ECR</li><li>To have a way to deploy multiple services</li><li>To have a way to modify multiple task definitions before deploying</li><li>Not all ECS Service need to be deployed, just need the image push</li></ol><p>I developed the below snippet of code to tackle all of these problem.</p><pre>.ecs_deploy:<br>  image: &quot;${CI_TEMPLATE_REGISTRY_HOST}/gitlab-org/cloud-deploy/aws-ecs:latest&quot;<br>  services:<br>     - docker:20.10.16-dind<br>  variables:<br>    DOCKER_HOST: tcp://docker:2376<br>    DOCKER_TLS_CERTDIR: &quot;/certs&quot;<br>    DOCKER_TLS_VERIFY: 1<br>    DOCKER_CERT_PATH: &quot;$DOCKER_TLS_CERTDIR/client&quot;<br>    SRC_AWS_PROFILE: &quot;default&quot;  # Source AWS Profile<br>    SRC_IMAGES_AND_TAG: &quot;&quot;      # Container image and tag i.e. without account number<br>    SRC_ECR_REGISTRY: &quot;&quot;        # ECR Registry URL<br>    DEST_ECR_REGISTRY: &quot;&quot;       # Destination ECR Registry URL<br>    DEST_AWS_PROFILE: &quot;default&quot; # Destination AWS Profile<br>    DEST_IMAGES_AND_TAG: &quot;&quot;     # Destination Image and tag<br>    DEST_TASK_DEFINITIONS: &quot;&quot;   # Destination Task definition to pull from<br>    DEST_ECS_SERVICE: &quot;&quot;        # Destination ECS Service<br>    CI_AWS_ECS_CLUSTER: &quot;&quot;      # Destination ECS Cluster Name<br>    APP_CONTAINER_NAME: &quot;app&quot;   # Main Application Container Name<br>  before_script:<br>    - until docker info; do sleep 1; done<br>  script:<br>    - if [[ -z &quot;$SRC_ECR_REGISTRY&quot; || -z &quot;$SRC_IMAGES_AND_TAG&quot; || -z &quot;$DEST_ECR_REGISTRY&quot; || -z &quot;$DEST_IMAGES_AND_TAG&quot; || -z &quot;$DEST_TASK_DEFINITIONS&quot; || -z &quot;$DEST_ECS_SERVICE&quot; || -z &quot;$CI_AWS_ECS_CLUSTER&quot; || -z &quot;$DEST_ECS_SERVICE&quot; ]]; then echo &quot;.ecs_deploy - missing mandatory variables&quot;; env; exit 1; fi<br>    - IMAGE_VERSION=&quot;${CI_COMMIT_TAG:-$CI_COMMIT_SHORT_SHA}&quot;<br>    - ARRAY_SRC_IMAGES_AND_TAG=(${SRC_IMAGES_AND_TAG//,/ })<br>    - ARRAY_DEST_IMAGES_AND_TAG=(${DEST_IMAGES_AND_TAG//,/ })<br>    - ARRAY_DEST_TASK_DEFINITIONS=(${DEST_TASK_DEFINITIONS//,/ })<br>    - ARRAY_DEST_ECS_SERVICE=(${DEST_ECS_SERVICE//,/ })<br>    - | <br>      if [ ${#ARRAY_SRC_IMAGES_AND_TAG[@]} -ne ${#ARRAY_DEST_IMAGES_AND_TAG[@]} ];<br>      then<br>          echo ecs_deploy: Unequal number of images<br>          exit 1<br>      fi<br>      if [ ${#ARRAY_DEST_TASK_DEFINITIONS[@]} -ne ${#ARRAY_DEST_IMAGES_AND_TAG[@]} ];<br>      then<br>          echo ecs_deploy: Unequal number of task definition<br>          exit 1<br>      fi<br>      if [ ${#ARRAY_DEST_ECS_SERVICE[@]} -ne ${#ARRAY_DEST_IMAGES_AND_TAG[@]} ];<br>      then<br>          echo ecs_deploy: Unequal number of ecs service<br>          exit 1<br>      fi<br># Pulling image from different source<br>    - |<br>      if [[ ! -z &quot;$SRC_AWS_PROFILE&quot; ]]<br>      then <br>        export AWS_PROFILE=$SRC_AWS_PROFILE<br>        aws ecr get-login-password --region ap-southeast-1 | docker login --username AWS --password-stdin $SRC_ECR_REGISTRY<br>      else<br>        crane auth login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY<br>      fi<br># Pulling all images<br>    - |<br>      for i in &quot;${!ARRAY_SRC_IMAGES_AND_TAG[@]}&quot;; do<br>        SRC_IMAGE_NAME=${ARRAY_SRC_IMAGES_AND_TAG[i]%%:*}<br>        SRC_IMAGE_TAG=${ARRAY_SRC_IMAGES_AND_TAG[i]##*:}<br>        DEST_IMAGE_NAME=${ARRAY_DEST_IMAGES_AND_TAG[i]%%:*}<br>        DEST_IMAGE_TAG=${ARRAY_DEST_IMAGES_AND_TAG[i]##*:}<br>        docker pull $SRC_ECR_REGISTRY/${ARRAY_SRC_IMAGES_AND_TAG[i]}<br>        docker tag $SRC_ECR_REGISTRY/${ARRAY_SRC_IMAGES_AND_TAG[i]} $DEST_ECR_REGISTRY/${ARRAY_DEST_IMAGES_AND_TAG[i]} <br>        docker tag $SRC_ECR_REGISTRY/${ARRAY_SRC_IMAGES_AND_TAG[i]} $DEST_ECR_REGISTRY/$DEST_IMAGE_NAME:$IMAGE_VERSION<br>        docker tag $SRC_ECR_REGISTRY/${ARRAY_SRC_IMAGES_AND_TAG[i]} $DEST_ECR_REGISTRY/$DEST_IMAGE_NAME:$CI_COMMIT_SHA<br>      done<br>    - export AWS_PROFILE=$DEST_AWS_PROFILE<br>    - aws ecr get-login-password --region ap-southeast-1 | docker login --username AWS --password-stdin $DEST_ECR_REGISTRY<br># Pushing all images, by tagging based on what was given, git hash and git tag if any<br>    - |<br>      for i in &quot;${!ARRAY_DEST_IMAGES_AND_TAG[@]}&quot;; do<br>        DEST_IMAGE_NAME=${ARRAY_DEST_IMAGES_AND_TAG[i]%%:*}<br>        DEST_IMAGE_TAG=${ARRAY_DEST_IMAGES_AND_TAG[i]##*:}<br>        docker push $DEST_ECR_REGISTRY/${ARRAY_DEST_IMAGES_AND_TAG[i]}<br>        docker push $DEST_ECR_REGISTRY/$DEST_IMAGE_NAME:$IMAGE_VERSION<br>        docker push $DEST_ECR_REGISTRY/$DEST_IMAGE_NAME:$CI_COMMIT_SHA<br>      done<br>    - mkdir -p manifests<br># Pull the latest task definition, not the one currently in use<br># Replace the image tag with image:githash<br># Replace env variable to VERSION_COMMIT to commit id<br># Replace env variable to VERSION_TAG to git tag if any, else git hash<br># Replace redudant fields if not it will throw error<br># if we provide nil, it will not trigger deployment. i.e. we just want to push image<br>    - |<br>      for i in &quot;${!ARRAY_DEST_TASK_DEFINITIONS[@]}&quot;; do<br>        if [[ ${ARRAY_DEST_TASK_DEFINITIONS[i]} != &quot;nil&quot; ]]<br>        then<br>          echo &quot;ecs_deploy: Generating Task Definition ${ARRAY_DEST_ECS_SERVICE[i]} to ${CI_AWS_ECS_CLUSTER}&quot;<br>          DEST_IMAGE_NAME=${ARRAY_DEST_IMAGES_AND_TAG[i]%%:*}<br>          DEST_IMAGE_TAG=${ARRAY_DEST_IMAGES_AND_TAG[i]##*:}<br>          aws ecs describe-task-definition --output json --task-definition ${ARRAY_DEST_TASK_DEFINITIONS[i]} --query taskDefinition &gt; template_${ARRAY_DEST_TASK_DEFINITIONS[i]}.json<br>          jq --arg APP_CONTAINER_NAME $APP_CONTAINER_NAME --arg IMAGE_NAME &quot;$DEST_ECR_REGISTRY/$DEST_IMAGE_NAME:$CI_COMMIT_SHA&quot; --arg IMAGE_VERSION $IMAGE_VERSION --arg DEST_IMAGE_NAME $DEST_IMAGE_NAME --arg CI_COMMIT_SHA $CI_COMMIT_SHA &#39;del(.taskDefinitionArn, .revision, .status, .requiresAttributes, .compatibilities, .registeredAt, .registeredBy) | .containerDefinitions[] |= <br>            if .name == $APP_CONTAINER_NAME then<br>              .image = $IMAGE_NAME |<br>              (.environment[] | select(.name == &quot;VERSION_COMMIT&quot;)).value = $CI_COMMIT_SHA |<br>              (.environment[] | select(.name == &quot;VERSION_TAG&quot;)).value = $IMAGE_VERSION<br>            else<br>              .<br>            end&#39; template_${ARRAY_DEST_TASK_DEFINITIONS[i]}.json &gt; manifests/${ARRAY_DEST_TASK_DEFINITIONS[i]}.json<br>          export CI_AWS_ECS_TASK_DEFINITION_FILE=manifests/${ARRAY_DEST_TASK_DEFINITIONS[i]}.json<br>          export CI_AWS_ECS_SERVICE=${ARRAY_DEST_ECS_SERVICE[i]}<br>          echo &quot;ecs_deploy: Deploying to ${ARRAY_DEST_ECS_SERVICE[i]} to ${CI_AWS_ECS_CLUSTER}&quot;<br>          ecs update-task-definition<br>        else<br>          echo &quot;ecs_deploy: Skipping deployment for ${ARRAY_DEST_IMAGES_AND_TAG[i]}&quot;<br>        fi<br>      done<br>  artifacts:<br>    paths:<br>      - manifests<br>  tags:<br>    - privileged</pre><p>In order to start using the above code, firstly you need to have Gitlab runner that supports privileged to run docker in docker service. This is essentially required to retag the image.</p><p>Fortunately, this image provided by Gitlab has docker installed, which I do not need to build another image just to get it to work. But if you don’t have a way to run docker in docker, you might want to rebuild one with crane or skopeo .</p><p>As Gitlab doesn’t have a way to provide a list of string values, I am chaining a list of values with comma delimited which I will then split these values and loop them.</p><p>There are couple of validation at the start to ensure the number ECS Service count matches number of Task Definition and Container Images.</p><p>It starts off to authenticate with container registry, pull the images, retag and re-authenticate with destination ECR and push the images. As you can see here, I am pulling 1 tag but pushing 3 tags i.e. commit id, provided tag and git tag if any else short git commit id.</p><p>Next, it will pull the destination task definition. I am using jq to manipulate the task definition by replacing the container image for the container what has the same name provided in APP_CONTAINER_NAME. This is a different approach as Gitlab way, by not assuming the first container is the container that I want to update. The jq command also update VERSION_TAG and VERSION_COMMIT which inject the git tag and git hash into the task definiton. This way, the application can look up these environment variables to display the semantic version on the UI.</p><p>Once the jq operation is done, it saves as a file and we will call Gitlab’s ecs update-task-definiton . This will then use the second deployment method i.e. deploy task definition via local file.</p><p>I have also added a condition where if I provide nil to DEST_TASK_DEFINITIONS, it will skip the ECS deployment. This gives me the flexibility to not needing provide 3 ECS services.</p><p>Lastly, the job also publish the generated task definition as artifact, which may be useful for verification.</p><p>This method also give me the flexibility to not commit the task definition into the git repository. Ideally, I want to manage the task definition in my terraform code and let gitlab handle the updating of the remaining values. If there are changes on the terraform code, I do not need to update the task definition into the application git repository. This essentially makes my terraform code base the single source of truth!</p><p>To end this article, I hope some of these thought process will be helpful, especially the part when I relate back the previous article I have written. Do feel free to reach out if this has been useful to your work!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5334ce258472" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD Pipeline Design Principles — CRAFTS]]></title>
            <link>https://medium.com/@kay.renfa/ci-cd-pipeline-design-principles-crafts-a62a3f79c660?source=rss-2d401c9d729d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62a3f79c660</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Kay Ren Fa]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 08:33:28 GMT</pubDate>
            <atom:updated>2023-08-10T01:40:02.797Z</atom:updated>
            <content:encoded><![CDATA[<h3>CI/CD Pipeline Design Principles — CRAFTS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*-ULlcf1NEt8nSkwg" /></figure><p>As a DevOps Engineer, working on CI/CD Pipelines is pretty much our bread and butter responsibility. In most occasion, most engineers don’t have the opportunity to build from scratch, as they usually inherit pipeline that has been frequently fine-tuned over time.</p><p>Luck for me, I had the opportunity to design pipeline numerous time during the course of my career which I has learned from many mistakes and come up with couple of guiding principles when designing and working on pipelines.</p><p>In this article, I will not be covering any technical implementation (there are too many widely available), instead, will share the principles that I have picked up.</p><p>To give more into context on why I am covering this topic. Couple of months back, my organization is enforcing a organization wide standardisation to use the same set of CI/CD orchestration tooling. My team was using a mix bag of teamcity, bamboo for CI/CD pipeline and bitbucket for SCM and we had to migrate them all to Gitlab and that is when we got our hands dirty again.</p><p>I have years of working with Jenkin, developing declarative pipeline, writing in groovy using shared libraries for Tanzu, Openshift, Andriod and IOS Pipelines. Jenkins used to be a popular software for CI/CD but it has grew short in capability and plugin support as compared to the new tools in the market.</p><p>Nevertheless, using with Gitlab is rather new to me which I need to go through its documentation understand its functionality. We successfully completed the migration all pipeline within 2 months with little roadblocks. I won’t go into detail what was done to make it a success, rather, I want to share what was the thought process regardless it is Gitlab or other tools.</p><h3>The Components</h3><p>Generally a Pipeline comprises of these components, and they play a part how you design your pipeline.</p><ol><li>CI/CD Orchestration tool</li><li>Source Code Management (SCM)</li><li>Branching Strategy</li><li>Runners/Agents</li><li>Deployment Strategy</li></ol><h4>CI/CD Orchestration tool</h4><p>Each tool has it way of using them. It is important to study how the it expect you to use them and do couple of Proof of concept before solidify your design.</p><p>For instance, Jenkins decouples from SCM, hence, it expects you to manually setup project whenever there is a new repository (of course there is Github or other integrations which solves some of these pain points).</p><p>Gitlab and Github, on the other hand, contain pipeline code in the repository which automatically loads the pipeline code.</p><p>Gitlab has a myriad range of rule set such as triggering pipeline when certain file has been modified. This greatly changes the rule how you can design your pipeline, especially more towards monorepo design.</p><p>Another point to mention is some has its own way of support viewing of test reports, such as junit test. Jenkins has a way to publish HTML reports to view the unit test reports, whereas Gitlab ingest json output from test stages and display as its own format.</p><p>Each tools has its own way syntax of developing pipeline, such as groovy, or .gitlab-ci.yaml and so on. For the case of Jenkins, it will then require you to pick up a “scripting” language and Jenkins DSL.</p><h4>SCM</h4><p>While there are tools that combines orchestration tool with SCM, there are some that are standalone like Gerrit, <em>old</em> Bitbucket.</p><p>SCM may play a part as some may have different merging strategy support for pull request, or webhooks to orchestration tool.</p><p>I generally prefer tools that combines SCM and orchestration tool as it integrate well within it own ecosystem without the need of constant polling, and therefore you get near instantaneous invocation of pipeline.</p><h4>Branching Strategy</h4><p>Branch strategy shapes how the team develops, operates and pipeline run.</p><p>Before I did the migration, my application which comprises of 2 teams, which has somewhat similar branching strategy. They develop on their feature branch and merge to development branch and development branch will be deployed to CI environment to run a series of regression test before the commit get promoted to master branch and then it get promoted again after it get deployed to staging environment and lastly promoted to release branch. In between these promotion, it is either automated or manually code merge or cherry-picking.</p><p>This migration gave me the opportunity to correct their branching strategy to solely trunk based development. Though there was slight resistant at the start on how “bad/ untested” code or feature leaks, or they cant “manipulate” the branch anymore but it was good that we moved forward.</p><p>Trunk based development should still be the de facto standard because we should keep the branching as lean as possible without the need to manage nor manipulate and any “bugs” should be fixed on the trunk as early as possible. Feature toggle plays a very important role to toggle broken/unready code.</p><h4>Runners</h4><p>All pipelines has to be run on some server. There are 2 forms of runners, <strong>Dedicated runner</strong> and <strong>Container based runner</strong>.</p><p><strong>Dedicated runners</strong> are VMs that is used by all pipelines. It reuses the same workspace. Generally these are the less favoured way of running pipeline because you need to ensure you have the necessary tools in the VM, which in most of the time, abd they are snowflakes in nature, hence, there might be slight disparity in tools version. Some orchestration tools allow multiple builds on the same runner, which introduce more flakiness to failure these jobs co-share the CPU and Memory within the same VM. While it may be faster by reusing the same workspace without the need to re-pull the whole codebase, it is prone to “manipulation” where one may SSH into the server to modify the workspace which can introduce false positive success and false negative failure in the build. Shallow clone can also be used to workaround full git clone issue.</p><p><strong>Container based runners</strong> are cleaner and consistent approach as it retains the clean slate of the image each time you run the jobs. Most importantly, team should follow good container practices by properly tagging the image rather than using latest .</p><p>One of the key factor that my team had little roadblocks was also because I manage my own agents rather than using shared runners. As I setup my own kubernetes executors on Gitlab, I can easily diagnose issues with kubectl top/describe/exec/port-forward .</p><h4>Deployment Strategy</h4><p>There are many deployment strategy and it is best to consider what really suit your team and product. Do consider this series of questions</p><ol><li>Can you afford downtime?</li><li>Can you afford running a lot more resources for smooth transition? Such as running twice amount of compute resource.</li><li>Is your team developing the product with backward compatibility? Such as having v1 and v2 api?</li><li>Does your team accept small amount of failure just to test out a small subset of audience?</li></ol><p>Each deployment strategy will affect the way your code your pipeline. For complicated strategies like canary deployment, at bare minimum you will need to have two stages:</p><ol><li>Deploy the application and route X% of the traffic to the new version.</li><li>You will need to halt the deployment for the verification before you rollback or switch the application to the version.</li></ol><p>A good list of deployment strategies can be <a href="https://www.baeldung.com/ops/deployment-strategies">here</a>.</p><p>There can be more other factors in the play such as application tech stack but I won’t be covering that.</p><p>As mentioned, there are some guiding principles I abide when designing the pipeline using this acronyms <strong>CRAFTS</strong>.</p><ol><li>Completeness</li><li>Rapid</li><li>Audit-ability</li><li>Feedback</li><li>Traceability</li><li>Simplicity</li></ol><h4>Completeness</h4><p>While some of these point are talking about the whole pipeline, this point solely focus on deployment as it is the ultimate goal for CI/CD. Hence, what constitute as a complete deployment?</p><p>Ideally, it should be a whole new clean slate instead of incremental. This reduces the chances of missing parts and ensures rollbacks are consistent too.</p><p>Imagine a deployment strategy is to unzip an artifact and copy the content to a directory.</p><p>Sounds complete safe but what is the risk here? As copying files only overwrites files but it doesn’t remove files that are supposed to be there as per the commit. It may result in failure as the “extra” files may also fail your application. Hence, it introduces risk to failure during deployment, hence it is not complete per se.</p><p>Whereas for container deployments are generally complete as it the filesystems are “reset” each time.</p><p><strong>Rapid</strong></p><p>It is no brainer that everyone wants fast feedback from pipeline. Various tool allows parallelism in the build stages which speeds up the testing stages, others allow caching to avoid re-building or re-downloading dependencies. These are good techniques to not repeat time consuming stages.</p><p>One example would be docker build caches saves the trouble of rebuilding all layers, and only start from the stage where changes are made.</p><p>Another method to make pipelines rapid is to reduce lead time between stages. That is to have as little manual process and human intervention such as parameterizing certain values manually. A good pipeline should be as automated as possible with little stop point and abort immediately whenever there is any failure. This also ties back to the 4th point on feedback so that the team can rapidly react and make the necessary changes.</p><p>Teams should strike a balance between the type of test as too many tests may slow things down and too little may result in insufficient test coverages. Developers should also regularly revisit their test cases to remove depreciated test scenarios.</p><p>While Rapid is the goal we want to achieve, at times certain test are incredible long such as load testing, DAST. Generally you want to park them out of the main pipeline for more of the schedule based jobs. They are good to have but not mission critical in general that should bar anyone from merging the code. Imagine a scenario where these test takes 2hours, can you imagine how it will affect overall team velocity to wait for these test to complete in order to proceed?</p><h4>Audit-ability</h4><p>I suppose this is not a commonly thought of point but I felt this is very important. Why this is important is because a good pipeline should also have control in place to prevent people from finding any loophole though no shame that I have done this numerous time.</p><p>It is important is to ensure that there are check in place or gatekeepers to prevent any loophole from occurring.</p><p>For instance, only code that is from the trunk and the particular commit has gone through all code scan with no failure can deploy to production. The reason is not all commit in the trunk passes the scan, hence, it might be a minefield of faulty code. Hence, you has to pick the right commit that is safe to use after code merge, therefore the checks should be in place to prevent wrong code from going in to production.</p><p>You may also need to ensure you “lock” the pipeline files, and/or print out which commit you are using if you have an external repository for pipeline code. This is to ensure there is no temporary switch of commit to “malicious” commit that may grant bad actors to disable some of the important checks.</p><h4>Feedback</h4><p>Feedback plays an important role to let them know what went wrong in their code or deployment. There are two forms of feedback.</p><p>Jobs should always fail during any testing such as static code analysis, unit test when things are wrong. Tests should not be flaky which will lead the developers to rerun the jobs hoping it will work the next time. It should always fail stages when something is wrong and prevent subsequent stages such as deployment from proceeding.</p><p>Another form of feedback is to send notifications such as slack, telegram, email, or a form of dashboard. This will be extremely useful to get the team to look into the issues immediately.</p><h4>Traceability</h4><p>By best practice, deployment should reuse the same deployment artifacts across all environments and it is the configurations that set the application apart.</p><p>Quite importantly, there should be a way to determine if an artifact is tied to a particular commit, build and not tampered. This can be done by signing the artifact after build is complete like cosigning.</p><p>You can also make it impossible to overwrite existing artifacts such as ECR immutable tags, Nexus repositories restricting overwriting files. These write only once features ensure no artifact can be fabricated from another source.</p><p>By naming the artifact based on the commit Id or git tag, it makes it easy to traceback to the version of the code that is used to produce the files. Certain SCM also associates pipeline build to commit Id which further enhances the traceability of the input and output.</p><h4>Simplicity</h4><p>A well-designed pipeline is intuitive to users. It should be simple enough for people to understand and use. It should also provide enough flexibility for one to use it for whatever purpose.</p><p>One flexibility will always be to deploy a feature branch changes to an environment for review. Ideally we should do most of our testing locally, certain scenario may not be achievable through local testing or limited compute power. Hence, you may still need to deploy to certain environment to perform end-to-end testing. Hence, giving team a flexibility to deploy on need basis, ideally on their own namespace will further empower the developers.</p><p>One of my team’s need is to be able to apply hotfix whenever possible. That means to have a backdoor to deploy to production without the need to go through the usual series of test. Though it is not by trunk based development practice to have hotfixbranch, but I do understand the challenge to transit directly to trunk based development as the team doesn’t deploy the the trunk to production frequently enough. Hence, I made it as a “breakglass” scenario whenever we have to do one.</p><p>Simplicity can also be drilled all the way down the the error message whenever a job fails. As pipeline development may happen together with feature developments, pipeline may randomly fail due to new changes. Developers may quick to judge that it is pipeline issue than code issue. Pipeline code are usually bunch of bash commands than developers aren’t familiar, hence, these messages play an important part for them understand what is happening rather than random exit 1 errors.</p><p>As a closing note, developing a pipeline is no different from application design. There is no silver bullet on how pipeline should be written as every team are bounded by different constraints such as teams culture, tech stack, CI/CD tools, but general principles as shared above do come into play. I hope some of these points will bring value to your work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62a3f79c660" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Security Group with Terraform]]></title>
            <link>https://medium.com/@kay.renfa/aws-security-group-with-terraform-4805b955ad5c?source=rss-2d401c9d729d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4805b955ad5c</guid>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Kay Ren Fa]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 04:15:52 GMT</pubDate>
            <atom:updated>2023-08-10T02:03:17.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*rLUUHTXTz6WvOrcD" /></figure><p>In this article, I will cover the different ways to define security groups in AWS in Terraform. Though it sounds like a straightforward topic, many times, team will end up exposing more traffic than they should, such as using AWS default egress rules. I will cover when you should use CIDR range and when you should use Security Group ID. I will cover my interpretation of secure yet dynamic security group.</p><h3>Introduction</h3><p>Security Group contains a collection of security group rules that defines the set of traffic that is allowed inbound or outbound, defined as ingress and egress respectively.</p><p>Each security group rules are made up of 3 parts:</p><ul><li>Type of protocol (UDP/TCP)</li><li>Port Number</li><li>CIDR Range (IPV4/IPV6) or Security Group ID</li></ul><p>Any traffic not specified will be blocked. Security group rules are stateful, hence, you do not need to handle for ephemeral port. By default, if no egress rules defined, AWS will append a All Traffic 0.0.0.0/0. Many times, people will neglect the need to also implement secure egress rules.</p><h3>The Scenarios</h3><p>Typically, you will need to define 2 sets of rules, one for the consumer (egress), one for the provider (ingress). This is common when the resources are “within your control”.</p><p>For instance, EC2 -&gt; MySQL scenario, you should have these 2 set of rules</p><ul><li>EC2 Egress TCP 3306 to MySQL</li><li>MySQL Ingress TCP 3306 to EC2</li></ul><p>However, there are scenarios where you only have 1 set of rules, such as accessing endpoints that is “out of your control”, such as static IP from external endpoint.</p><ul><li>EC2 Egress TCP 443 to External Static Endpoint</li></ul><p>What is the differences between these 2 scenario? In the former case, you have access to add the rules to these 2 set of resources. They can be within the same VPC, or even peered VPC. In the latter case, you do not have the access to the External endpoint, hence, you can only add 1 set of rules.</p><p>Simple enough? Lets dive even deeper than that!</p><h3>Advance</h3><p>In the latter scenario, the only way is to use CIDR range when adding the Egress rule. Reason being, you have no way to point to the other endpoint’s security_group_id.</p><p>However, for former scenario, you will have the 2 options, CIDR Range and Security Group ID. I will rank following approaches from least secure to the most secure method:</p><ol><li>Anywhere</li><li>VPC CIDR</li><li>Subnet CIDR</li><li>Static IP</li><li>Security Group ID</li></ol><p>If you notice, in the same ordering, it is also the reverse order of easiest to hardest to implement.</p><ul><li>Anywhere is easiest to implement as it covers all IP range by setting 0.0.0.0/0</li><li>VPC CIDR is a broad IP range that covers all IP within the VPC, which you can query via data_source. However, note that VPC supports multiple VPC CIDR ranges</li><li>Subnet CIDR becomes more slightly more complicated as AWS advocates services to be running across 3 AZs. Hence, you will need to cover all 3 IP ranges</li><li>Static IP like most likely to be implemented as a terraform variable. But Static IP are more as flexible as there are chances where the “static” IP change out of the blue.</li></ul><h3>The Forbidden Fruit</h3><p>Why is security_group_id is the hardest to implement? For the case of CIDR range, it does not reference the rules to a resource. However, it does for security_group_id. Then it becomes more complicated as it becomes cyclical dependency.</p><p>Using the earlier example EC2 -&gt; RDS. EC2 will need to refer to RDS security_group_id, and RDS will need to refer to EC2 security_group_id. In most terraform modules for security group, it does not allow you to do that as there will result in a cyclical dependency.</p><p>The perks of using security_group_id is that you don’t need to be bothered by IP address at all. You have one security group specifically for EC2 for egress to RDS and you have one for for ingress to EC2. Only thing that you need to do is to add the security group to the resource and it will gain the access that it should.</p><p>One may argue, this sounds too good to be true but it may be prone to be abused. If an attacker who managed to gain access, they just need to attach the necessary security group to resources and immediately gain the access. Whereas CIDR range approach, it MAY require them to modify the security group rule to open wider range. My take is that using security_group_id is not the problem, but granting the attacker the wrong IAM policy is. Truth to the matter, any attacker with administrator permission can do anything they want, hence, it won’t defer in terms of whichever approach.</p><h3>Implementation</h3><p>If you are enticed by the benefit of security_group_id, how can we then tackle the cyclical dependency issue?</p><p>The way to handle it is to use the native resource which is security_group and security_group_rule. While you can put all rules within security_group resource, to achieve what we want is to have 2 separately resources. Reason is that you need both security_group resources to be created before you can references each other.</p><pre>resource &quot;aws_security_group&quot; &quot;rds-sg&quot; {<br>  name        = &quot;sgrp-rds&quot;<br>  description = &quot;Security group for RDS&quot;<br>  vpc_id      = var.vpc_id<br>}<br><br>resource &quot;aws_security_group_rule&quot; &quot;rds-sg&quot; {<br>  type                     = &quot;ingress&quot;<br>  description              = &quot;Security Group for RDS&quot;<br>  from_port                = var.port<br>  to_port                  = var.port<br>  protocol                 = &quot;tcp&quot;<br>  source_security_group_id = aws_security_group.rds-sg-for-app.id<br>  security_group_id        = aws_security_group.rds-sg.id<br>}<br><br>resource &quot;aws_security_group&quot; &quot;rds-sg-for-app&quot; {<br>  name        = &quot;sgrp-app-to-rds&quot;<br>  description = &quot;Security Group for App to RDS&quot;<br>  vpc_id      = var.vpc_id<br>}<br><br>resource &quot;aws_security_group_rule&quot; &quot;rds-sg-for-app&quot; {<br>  type                     = &quot;egress&quot;<br>  description              = &quot;Security Group for App to RDS&quot;<br>  from_port                = var.port<br>  to_port                  = var.port<br>  protocol                 = &quot;tcp&quot;<br>  source_security_group_id = aws_security_group.rds-sg.id<br>  security_group_id        = aws_security_group.rds-sg-for-app.id<br>}</pre><p>So for above scenario, assuming I have a RDS Terraform module, I will have these 4 sets of resources. This will create 2 security groups that opens for each other.</p><p>Then for my EC2 instances, I will just need to bind the aws_security_group.rds-sg-for-app security group ID. That can be done via data.terraform_remote_state. As simple as that, you have a very secure and dynamic security setup.</p><h3>Extra materials</h3><p>You can also point security group id to itself, that is using the self attribute. That is more relevant when you have a setup needs to communicate within itself such as synchronising states.</p><p>You can also point your security group rules to prefix_list_id. This allows you to point to AWS regional endpoints instead of opening to Anywhere.</p><h3>Final thoughts</h3><p>In my opinion, we should use security_group_id for security group rules whenever possible as it gives more secure and flexible setup without bothering about IP address. You can do the same for AWS PrivateLink setting egress to your PrivateLink security group.</p><p>CIDR range give you a quick and dirty way to implement and test connectivity, but it shouldn’t be the final setup for production environment unless you have no alternative way to do so.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4805b955ad5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ECS Service Task Reload when Parameter Store Changes]]></title>
            <link>https://medium.com/@kay.renfa/ecs-service-task-reload-when-parameter-store-changes-c5b42e85cd65?source=rss-2d401c9d729d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5b42e85cd65</guid>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Kay Ren Fa]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 04:31:32 GMT</pubDate>
            <atom:updated>2022-12-03T10:05:45.795Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the really neat feature of Kubernetes is that any changes to Secrets and ConfigMaps will result in recreation of the Pods. However, ECS does not natively come with such functionality.</p><p>While you can hook Parameter Store changes to EventBridge, it doesn’t come with the capability to stop “outdated” ECS task. Hence, another approach is to do it via Step Function. One of the use case of such frequent Parameter Store changes can be feature toggling which is frequently used in testing environments to simulate different scenarios.</p><p>In this article, I will show one of such use case where I have to change couple of Parameter Store values and reloading the ECS tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIrgEjz7Iy3oVUuv5ph3rA.png" /><figcaption>Step Function</figcaption></figure><p>The general idea from the above is</p><ol><li>Enabling/Disabling of certain functionality is passed as input.<br><em>{“enable_feature”: “true”}</em></li><li>Based on the choice given, it will route of either of the flow which will update the parameters</li><li>Once Parameters are updated, it fetches all ECS Tasks ID from the given ECS Service. In this example, I am hardcoding to one ECS Service, but it can be easily enhanced to be more dynamic</li><li>Once ECS Task ID is retrieved, you will need to use the intrinsic function to split the string for the TASK ID as List Task returns you the ARN of the task. Using the Task ID, you can stop them in order for ECS Service to recreate new ones. In this example, I am not introducing maximum parallelism as I do not require such functionality. But if you are doing this for high availability environments, do add delays and parallelism as ECS tasks may take a while to be ready.</li></ol><p>The step function code will look like such</p><pre>{<br>  &quot;Comment&quot;: &quot;A description of my state machine&quot;,<br>  &quot;StartAt&quot;: &quot;IS_FEATURE_ENABLED&quot;,<br>  &quot;States&quot;: {<br>    &quot;IS_FEATURE_ENABLED&quot;: {<br>      &quot;Type&quot;: &quot;Choice&quot;,<br>      &quot;Choices&quot;: [<br>        {<br>          &quot;Variable&quot;: &quot;$.enable_feature&quot;,<br>          &quot;StringMatches&quot;: &quot;true&quot;,<br>          &quot;Next&quot;: &quot;ENABLE_FEATURE_PARALLEL&quot;<br>        }<br>      ],<br>      &quot;Default&quot;: &quot;DISABLE_FEATURE_PARALLEL&quot;<br>    },<br>    &quot;ENABLE_FEATURE_PARALLEL&quot;: {<br>      &quot;Type&quot;: &quot;Parallel&quot;,<br>      &quot;Branches&quot;: [<br>        {<br>          &quot;StartAt&quot;: &quot;ENABLE_FEATURE_A_PROVIDER&quot;,<br>          &quot;States&quot;: {<br>            &quot;ENABLE_FEATURE_A_PROVIDER&quot;: {<br>              &quot;Type&quot;: &quot;Task&quot;,<br>              &quot;End&quot;: true,<br>              &quot;Parameters&quot;: {<br>                &quot;Name&quot;: &quot;/param/A&quot;,<br>                &quot;Value&quot;: &quot;valueA&quot;,<br>                &quot;Overwrite&quot;: true<br>              },<br>              &quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:ssm:putParameter&quot;<br>            }<br>          }<br>        },<br>        {<br>          &quot;StartAt&quot;: &quot;ENABLE_FEATURE_B_PROVIDER&quot;,<br>          &quot;States&quot;: {<br>            &quot;ENABLE_FEATURE_B_PROVIDER&quot;: {<br>              &quot;Type&quot;: &quot;Task&quot;,<br>              &quot;End&quot;: true,<br>              &quot;Parameters&quot;: {<br>                &quot;Name&quot;: &quot;/param/B&quot;,<br>                &quot;Value&quot;: &quot;valueB&quot;,<br>                &quot;Overwrite&quot;: true<br>              },<br>              &quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:ssm:putParameter&quot;<br>            }<br>          }<br>        }<br>      ],<br>      &quot;Next&quot;: &quot;Pass&quot;<br>    },<br>    &quot;DISABLE_FEATURE_PARALLEL&quot;: {<br>      &quot;Type&quot;: &quot;Parallel&quot;,<br>      &quot;Branches&quot;: [<br>        {<br>          &quot;StartAt&quot;: &quot;DISABLE_FEATURE_A_PROVIDER&quot;,<br>          &quot;States&quot;: {<br>            &quot;DISABLE_FEATURE_A_PROVIDER&quot;: {<br>              &quot;Type&quot;: &quot;Task&quot;,<br>              &quot;End&quot;: true,<br>              &quot;Parameters&quot;: {<br>                &quot;Name&quot;: &quot;/param/A&quot;,<br>                &quot;Value&quot;: &quot;valueX&quot;,<br>                &quot;Overwrite&quot;: true<br>              },<br>              &quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:ssm:putParameter&quot;<br>            }<br>          }<br>        },<br>        {<br>          &quot;StartAt&quot;: &quot;DISABLE_FEATURE_B_PROVIDER&quot;,<br>          &quot;States&quot;: {<br>            &quot;DISABLE_FEATURE_B_PROVIDER&quot;: {<br>              &quot;Type&quot;: &quot;Task&quot;,<br>              &quot;End&quot;: true,<br>              &quot;Parameters&quot;: {<br>                &quot;Name&quot;: &quot;/param/B&quot;,<br>                &quot;Value&quot;: &quot;valueZ&quot;,<br>                &quot;Overwrite&quot;: true<br>              },<br>              &quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:ssm:putParameter&quot;<br>            }<br>          }<br>        }<br>      ],<br>      &quot;Next&quot;: &quot;Pass&quot;<br>    },<br>    &quot;Pass&quot;: {<br>      &quot;Type&quot;: &quot;Pass&quot;,<br>      &quot;Next&quot;: &quot;ListTasks&quot;<br>    },<br>    &quot;ListTasks&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Next&quot;: &quot;Map&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;Cluster&quot;: &quot;YOUR_ECS_CLUSTER_NAME&quot;,<br>        &quot;ServiceName&quot;: &quot;YOUR_ECS_SERVICE_NAME&quot;<br>      },<br>      &quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:ecs:listTasks&quot;<br>    },<br>    &quot;Map&quot;: {<br>      &quot;Type&quot;: &quot;Map&quot;,<br>      &quot;Iterator&quot;: {<br>        &quot;StartAt&quot;: &quot;StopTask&quot;,<br>        &quot;States&quot;: {<br>          &quot;StopTask&quot;: {<br>            &quot;Type&quot;: &quot;Task&quot;,<br>            &quot;End&quot;: true,<br>            &quot;Parameters&quot;: {<br>              &quot;Task.$&quot;: &quot;States.ArrayGetItem(States.StringSplit($ ,&#39;/&#39;),2)&quot;,<br>              &quot;Reason&quot;: &quot;State Machine SSM Update&quot;,<br>              &quot;Cluster&quot;: &quot;YOUR_ECS_CLUSTER_NAME&quot;<br>            },<br>            &quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:ecs:stopTask&quot;<br>          }<br>        }<br>      },<br>      &quot;End&quot;: true,<br>      &quot;ItemsPath&quot;: &quot;$.TaskArns&quot;<br>    }<br>  }<br>}</pre><p>For this whole workflow to work, you will also require IAM role which has access to</p><ol><li>SSM Put Parameter</li><li>KMS Key Encrypt and Decrypt (If SSM is encrypted with Customer Managed Key)</li><li>ECS List Task</li><li>ECS Stop Task</li><li>Cloudwatch for logging</li></ol><h3>Closing Note</h3><p>While the solution above is not as intuitive and automated like Kubernetes where it knows the dependencies of parameters, it is one of the closest solution to automate repetitive operational task.</p><p>There is more that you can further enhance on this workflow such as taking in more inputs to replace Parameters, or replacing certain set of ECS Service Tasks. This can greatly save you the trouble of updating Terraform parameters or manually updating parameter store values.</p><p>I hope this article will give you an idea on how you can automate other parts of your operational tasks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5b42e85cd65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Lambda “Router” (NodeJS)]]></title>
            <link>https://medium.com/@kay.renfa/the-lambda-router-nodejs-e1022ea2f683?source=rss-2d401c9d729d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1022ea2f683</guid>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Kay Ren Fa]]></dc:creator>
            <pubDate>Sun, 06 Nov 2022 07:21:39 GMT</pubDate>
            <atom:updated>2023-01-06T02:43:41.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*MbkKbTRCM0pK0g7SD8MlcA.jpeg" /></figure><p>In this article, I will cover one of the requirements my team had to abide as part of organization security policy. Above diagram is a simplified overview of the how our application can communicate with each other.</p><ol><li>APP_A doesn’t have IGW/NATGW attached to the VPC for direct access to public internet. Instead, all internet traffic has to be rerouted to APIGW_A.</li><li>APIGW_A will be integrated to a lambda function which sits in a special VPC which only allow traffic to flow through internet via a forward proxy.</li><li>If APP_A needs to communicate to APP_B, we are not allowed to point directly to APP_B endpoint, instead we have to point to APIGW_B which will then have VPC link to NLB which then leads to the APP_B.</li><li>To further complicate the design, each client talking to the APIGW should be using a different API Key. As such, APP_A to APIGW_A should be using KEY_A and Lambda to APIGW_B should be using KEY_B.</li></ol><p>Though I do not 100% agree with such architecture design but I do see some benefit of doing so, such as having a more controlled network traffic in and out of the whole ecosystem and having some level of restriction between each nodes. This implementation can also be simplified with just route table for all external network to forward proxy without the need for API Gateway.</p><h3><strong>Pre-requisite before the implementation</strong></h3><ol><li>VPC Endpoint for API Gateway execution to be created</li><li>Forward Proxy such as Squid with the required address and port to be whitelisted</li><li>Working APP_A and APP_B and EXT_ENDPOINT. For APP_B, it needs to be fronted by a NLB for private API gateway setup to work.</li><li>In this example, I will use jsonplaceholder.typicode.com for the external integration.</li></ol><p>We will start off with the variables. We will need the details of the forward proxy ip and port to setup the security group for the lambda request.</p><pre>variable &quot;proxy_ip&quot; {<br>  type        = string<br>  description = &quot;Forward proxy ip address&quot;<br>}</pre><pre>variable &quot;proxy_port&quot; {<br>  type        = number<br>  description = &quot;Forward proxy port&quot;<br>}</pre><pre>variable &quot;lambda_vpc&quot; {<br>  type        = string<br>  description = &quot;VPC ID of lambda function&quot;<br>}</pre><pre>variable &quot;lambda_subnets&quot; {<br>  type        = list(string)<br>  description = &quot;List of subnet id where lambda will be procured&quot;<br>}</pre><pre>variable &quot;dummy_endpoint&quot; {<br>  type        = string<br>  description = &quot;dummy Endpoint&quot;<br>}</pre><p>Next, we will add some data source. As you can see, i am using remote state to fetch the NLB ARN. Do replace that block of code accordingly.</p><pre>data &quot;aws_vpc_endpoint&quot; &quot;api_gateway_endpoint&quot; {<br>  vpc_id       = var.vpc_id<br>  service_name = &quot;com.amazonaws.${var.aws_region}.execute-api&quot;<br>}</pre><pre>data &quot;aws_vpc_endpoint&quot; &quot;lambda_api_gateway_endpoint&quot; {<br>  vpc_id       = var.lambda_vpc<br>  service_name = &quot;com.amazonaws.${var.aws_region}.execute-api&quot;<br>}</pre><pre>data &quot;terraform_remote_state&quot; &quot;app_b_nlb&quot; {<br>  backend = &quot;s3&quot;<br>  config = {<br>    bucket = var.bucket<br>    key    = format(&quot;environments/%s/%s/%s/terraform.tfstate&quot;, var.environment, &quot;app_b&quot;, &quot;nlb&quot;)<br>    region = var.aws_region<br>  }<br>}</pre><p>Next, we will have couple of helper local variable to facilitate the naming of the resources. Completely optional but we practice this to ensure consistency in the naming convention as we have more parameters as part of the naming.</p><pre>locals {<br>  app_a_name = format(&quot;%s-%s&quot;, var.environment, &quot;app_a&quot;)<br>  app_b_name = format(&quot;%s-%s&quot;, var.environment, &quot;app_b&quot;)<br>}</pre><p>Next, we will start with the key resource which is api gateway and api keys. I have also added the vpc_endpoints for both lambda and APP_A vpc so that it can hit the API gateway endpoint.</p><pre>resource &quot;aws_api_gateway_rest_api&quot; &quot;app_a&quot; {<br>  name = &quot;apigw-${local.app_a_name}&quot;<br>  endpoint_configuration {<br>    types = [&quot;PRIVATE&quot;]<br>    vpc_endpoint_ids = [data.aws_vpc_endpoint.lambda_api_gateway_endpoint.id, data.aws_vpc_endpoint.api_gateway_endpoint.id]<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_rest_api&quot; &quot;app_b&quot; {<br>  name = &quot;apigw-${local.app_b_name}&quot;<br>  endpoint_configuration {<br>    types = [&quot;PRIVATE&quot;]<br>    vpc_endpoint_ids = [data.aws_vpc_endpoint.lambda_api_gateway_endpoint.id, data.aws_vpc_endpoint.api_gateway_endpoint.id]<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_api_key&quot; &quot;app_a&quot; {<br>  name = &quot;apigw-${local.app_a_name}-app-key&quot;<br>}</pre><pre>resource &quot;aws_api_gateway_api_key&quot; &quot;app_a_gw&quot; {<br>  name = &quot;apigw-${local.app_b_name}-gw-key&quot;<br>}</pre><pre>resource &quot;aws_api_gateway_rest_api_policy&quot; &quot;policy&quot; {<br>  rest_api_id = aws_api_gateway_rest_api.app_a.id<br>  policy      = &lt;&lt;EOF<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>  {<br>    &quot;Effect&quot;: &quot;Allow&quot;,<br>    &quot;Principal&quot;: &quot;*&quot;,<br>    &quot;Action&quot;: &quot;execute-api:Invoke&quot;,<br>    &quot;Resource&quot;: &quot;${aws_api_gateway_rest_api.app_a.execution_arn}/*&quot;<br>  }<br>  ]<br>}<br>EOF<br>}</pre><p>Next, we will work on Stage and usage plan. As we have 2 APIGW, we need to setup 2 sets of resources to work.</p><pre>resource &quot;aws_api_gateway_deployment&quot; &quot;app_a&quot; {<br>  rest_api_id = data.aws_api_gateway_rest_api.app_a.id<br>  triggers = {<br>  redeployment = sha1(jsonencode([<br>    aws_api_gateway_resource.external.id,<br>    aws_api_gateway_resource.external_proxy.id,<br>    aws_api_gateway_method.external.id,<br>    aws_api_gateway_integration.external.id,<br>    aws_api_gateway_resource.app_b.id,<br>    aws_api_gateway_resource.app_b_proxy.id,<br>    aws_api_gateway_method.app_b.id,<br>    aws_api_gateway_integration.app_b.id,<br>  ]))<br>  }<br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_stage&quot; &quot;app_a&quot; {<br>  deployment_id        = aws_api_gateway_deployment.app_a.id<br>  rest_api_id          = data.aws_api_gateway_rest_api.app_a.id<br>  stage_name           = var.environment<br>  xray_tracing_enabled = true<br>}</pre><pre>resource &quot;aws_api_gateway_method_settings&quot; &quot;app_a&quot; {<br>  rest_api_id = data.aws_api_gateway_rest_api.app_a.id<br>  stage_name  = aws_api_gateway_stage.app_a.stage_name<br>  method_path = &quot;*/*&quot;<br>  settings {<br>    metrics_enabled = true<br>    logging_level   = &quot;INFO&quot;<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_deployment&quot; &quot;app_b&quot; {<br>  rest_api_id = data.aws_api_gateway_rest_api.app_b.id<br>  triggers = {<br>  redeployment = sha1(jsonencode([<br>    aws_api_gateway_resource.app_b_gw.id,<br>    aws_api_gateway_resource.app_b_gw_proxy.id,<br>    aws_api_gateway_method.app_b_gw.id,<br>    aws_api_gateway_integration.app_b_gw.id,<br>  ]))<br>  }<br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_stage&quot; &quot;app_b&quot; {<br>  deployment_id        = aws_api_gateway_deployment.app_a.id<br>  rest_api_id          = data.aws_api_gateway_rest_api.app_b.id<br>  stage_name           = var.environment<br>  xray_tracing_enabled = true<br>}</pre><pre>resource &quot;aws_api_gateway_method_settings&quot; &quot;app_b&quot; {<br>  rest_api_id = data.aws_api_gateway_rest_api.app_b.id<br>  stage_name  = aws_api_gateway_stage.app_b.stage_name<br>  method_path = &quot;*/*&quot;<br>  settings {<br>    metrics_enabled = true<br>    logging_level   = &quot;INFO&quot;<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_usage_plan&quot; &quot;app_a&quot; {<br>  name        = &quot;apigw-${local.app_a_name}-usageplan&quot;<br>  description = &quot;Usage Plan for ${var.environment} Api GW&quot;<br>  api_stages {<br>   api_id = data.aws_api_gateway_rest_api.app_a.id<br>    stage  = aws_api_gateway_stage.app_a.stage_name<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_usage_plan&quot; &quot;app_b&quot; {<br>  name        = &quot;apigw-${local.app_b_name}-usageplan&quot;<br>  description = &quot;Usage Plan for ${var.environment} Api GW&quot;<br>  api_stages {<br>   api_id = data.aws_api_gateway_rest_api.app_b.id<br>    stage  = aws_api_gateway_stage.app_b.stage_name<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_usage_plan_key&quot; &quot;app_a&quot; {<br>  key_id        = aws_api_gateway_api_key.app_a.id<br>  key_type      = &quot;API_KEY&quot;<br>  usage_plan_id = aws_api_gateway_usage_plan.app_a.id<br>}</pre><pre>resource &quot;aws_api_gateway_usage_plan_key&quot; &quot;app_a_gw&quot; {<br>  key_id        = aws_api_gateway_api_key.app_a_gw.id<br>  key_type      = &quot;API_KEY&quot;<br>  usage_plan_id = aws_api_gateway_usage_plan.app_b.id<br>}</pre><p>Next we will work on security group. To be extreme secure, we only allow traffic to VPC Endpoint and Forward Proxy. For VPC Endpoint security group should just allow 443 Ingress.</p><pre>resource &quot;aws_security_group&quot; &quot;forward_proxy&quot; {<br>  name        = &quot;sgrp_forward_proxy&quot;<br>  vpc_id      = var.lambda_vpc<br>  ingress {<br>    description     = &quot;APIGW to Lambda&quot;<br>    from_port       = 443<br>    to_port         = 443<br>    protocol        = &quot;tcp&quot;<br>    security_groups = [tolist(data.aws_vpc_endpoint.lambda_api_gateway_endpoint.security_group_ids)[0]]<br>  }<br>  egress {<br>    description = &quot;Lambda to forward proxy&quot;<br>    from_port   = var.proxy_port<br>    to_port     = var.proxy_port<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;${var.proxy_ip}/32&quot;]<br>  }<br>}</pre><pre>resource &quot;aws_security_group&quot; &quot;reverse_proxy&quot; {<br>  name        = &quot;sgrp_reverse_proxy&quot;<br>  vpc_id      = var.lambda_vpc<br>  ingress {<br>    description     = &quot;APIGW to Lambda&quot;<br>    from_port       = 443<br>    to_port         = 443<br>    protocol        = &quot;tcp&quot;<br>    security_groups = [tolist(data.aws_vpc_endpoint.lambda_api_gateway_endpoint.security_group_ids)[0]]<br>  }<br>  egress {<br>    description     = &quot;Lambda to APIGW VPCE&quot;<br>    from_port       = 443<br>    to_port         = 443<br>    protocol        = &quot;tcp&quot;<br>    security_groups = [tolist(data.aws_vpc_endpoint.lambda_api_gateway_endpoint.security_group_ids)[0]]<br>  }<br>}</pre><p>We will also need to setup couple of IAM Role for logging and lambda function</p><pre>resource &quot;aws_iam_role&quot; &quot;lambda_role&quot; {<br>  name = &quot;iam_role_lambda&quot;<br>  assume_role_policy = &lt;&lt;POLICY<br>  {<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>  {<br>    &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>    &quot;Principal&quot;: {<br>      &quot;Service&quot;: &quot;lambda.amazonaws.com&quot;<br>    },<br>    &quot;Effect&quot;: &quot;Allow&quot;<br>    }<br>  ]<br>}<br>POLICY</pre><pre>  inline_policy {<br>  name = &quot;iam_policy_${local.gcc_name}_lambda&quot;<br>    policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>{<br>  Action = [&quot;ec2:CreateNetworkInterface&quot;,<br>  &quot;ec2:DeleteNetworkInterface&quot;,<br>  &quot;ec2:DescribeNetworkInterfaces&quot;,<br>  &quot;logs:CreateLogGroup&quot;,<br>  &quot;logs:CreateLogStream&quot;,<br>  &quot;logs:PutLogEvents&quot;]<br>  Effect   = &quot;Allow&quot;<br>  Resource = &quot;*&quot;<br>  },<br>  ]<br>  })<br>  }<br>}</pre><pre>resource &quot;aws_iam_role&quot; &quot;apigw_log&quot; {<br>  name = &quot;iam_role_apigw_log&quot;<br>  assume_role_policy = &lt;&lt;POLICY<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>  {<br>    &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>    &quot;Principal&quot;: {<br>    &quot;Service&quot;: &quot;apigateway.amazonaws.com&quot;<br>  },<br>  &quot;Effect&quot;: &quot;Allow&quot;<br>  }<br>  ]<br>}</pre><pre>POLICY<br>  inline_policy {<br>    name = &quot;  policy_apigw_log&quot;<br>    policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>    {<br>      Action = [&quot;logs:CreateLogGroup&quot;,<br>&quot;logs:CreateLogStream&quot;,<br>&quot;logs:DescribeLogGroups&quot;,<br>&quot;logs:DescribeLogStreams&quot;,<br>&quot;logs:PutLogEvents&quot;]<br>      Effect   = &quot;Allow&quot;<br>      Resource = &quot;*&quot;<br>    },<br>  ]<br>  })<br>  }<br>}</pre><pre>// For setting logging<br>resource &quot;aws_api_gateway_account&quot; &quot;apigw_log&quot; {<br>  cloudwatch_role_arn = aws_iam_role.apigw_log.arn<br>}</pre><p>Finally, after all these setup, we can start on the lambda function. To begin, create a folder and lambda/proxy-service/src and lambda/proxy-service/nodejs which will store the router and lambda layers respectively. From the code below, it does a npm ci --production to download node_modules which will be packaged into lambda layers.</p><p>In your local setup, you can also opt to setup this via serverless framework and docker-compose for squid proxy. In this example, I will not go into details for these two parts.</p><pre>resource &quot;null_resource&quot; &quot;lambda_layer&quot; {<br>  provisioner &quot;local-exec&quot; {<br>  command = &quot;cd lambda/proxy-service/nodejs &amp;&amp; npm ci --production&quot;<br>  }<br>}</pre><pre>data &quot;archive_file&quot; &quot;lambda_layer&quot; {<br>  type        = &quot;zip&quot;<br>  source_dir  = &quot;lambda/proxy-service&quot;<br>  output_path = &quot;tf_lambda_layer.zip&quot;<br>  excludes    = [&quot;README.md&quot;, &quot;package.json&quot;, &quot;package-lock.json&quot;, &quot;src&quot;, &quot;node_modules&quot;]<br>  depends_on  = [null_resource.lambda_layer]<br>}</pre><pre>resource &quot;aws_lambda_layer_version&quot; &quot;lambda_layer&quot; {<br>  filename   = &quot;tf_lambda_layer.zip&quot;<br>  layer_name = &quot;axios&quot;<br>  compatible_runtimes = [&quot;nodejs16.x&quot;]<br>  source_code_hash    = data.archive_file.lambda_layer.output_base64sha256<br>}</pre><pre>data &quot;archive_file&quot; &quot;lambda&quot; {<br>  type        = &quot;zip&quot;<br>  source_dir  = &quot;lambda/proxy-service&quot;<br>  excludes    = [&quot;README.md&quot;, &quot;nodejs&quot;, &quot;node_modules&quot;]<br>  output_path = &quot;tf_lambda.zip&quot;<br>}</pre><p>Next, we will go into the details for the lambda function. I am using Axios for sending request. This “router” function takes in the request from application, then send the same request to respective party.</p><p>I also also removed some of the headers from original set as it may reject the request and response. For example, some of the x-amzn header includes VPC details, which APIGW_B will reject the request. Similarly, the Content-Type header will cause the request to be rejected when its not application/json by default.</p><p>In the lambda code, it replaces the requested url (with the stage and route) with the expected url. For example <a href="https://apigw_a.com/dev/external/posts">https://APIGW_A.com/dev/external/path/posts</a>?id=1 will be translated to ${env.ENDPOINT}/path/posts?id=1 . And if the API_KEY is provided, it will be appended into the header which will be sent APIGW_B</p><pre>var axios = require(&quot;axios&quot;);<br>const HttpsProxyAgent = require(&quot;https-proxy-agent&quot;);<br><br>exports.handler = async function(event, context) {<br>    if (process.env.DEBUG){<br>      console.log(&#39;## ENVIRONMENT VARIABLES: &#39; + serialize(process.env))<br>      console.log(&#39;## CONTEXT: &#39; + serialize(context))<br>      console.log(&#39;## EVENT: &#39; + serialize(event))<br>    }<br><br>    let request = {<br>      method: event.httpMethod,<br>      url: await getUrl(process.env.ENDPOINT_URL, event),<br>      data: tryParseJSONObject(event.body),<br>      headers: getHeader(event.headers)<br>    }<br><br>    if(process.env.PROXY_HOST &amp;&amp; process.env.PROXY_PORT ){<br>      let httpsAgent = new HttpsProxyAgent({host: process.env.PROXY_HOST, port: process.env.PROXY_PORT })<br>      axios = axios.create({httpsAgent});<br>    }<br><br>    let response = await axios(request).then(function (response) {<br>        return {<br>          statusCode: response.status,<br>          body:       (typeof response.data == &quot;object&quot;) ? serialize(response.data) : response.data<br>        }<br>    }).catch(function(error){<br>      console.log(error.toJSON());<br>      let response = {<br>        statusCode: 500,<br>        body:       serialize({message: `${process.env.AWS_LAMBDA_FUNCTION_NAME} Lambda unexpectedly failed: ${error}`}),<br>      }<br>      if(error.response){<br>        response = {<br>          statusCode: error.response.status,<br>          body: (typeof error.response.data == &quot;object&quot;) ? serialize(error.response.data) : error.response.data<br>        }<br>      }<br>      return response<br>    });<br>  return response;<br>};<br><br>function serialize(object) {<br>  return JSON.stringify(object, null, 2)<br>}<br><br>function getHeader(header, isRequestHeader = true) {<br>  let sanitized_header = { }<br>  if (header != null &amp;&amp; header != undefined){<br>    let ignore_headers = [&#39;authorization&#39;, &#39;accept-encoding&#39;, &#39;accept&#39;, &#39;user-agent&#39;, &#39;x-forwarded-for&#39;]<br>    for (const [key, value] of Object.entries(header)){<br>      let lowercase = key.toLowerCase()<br>      if(ignore_headers.includes(lowercase)){<br>        sanitized_header[key] = value;<br>      }<br>    }<br>  }<br>  if (process.env.API_KEY &amp;&amp; isRequestHeader){<br>    sanitized_header[&#39;x-api-key&#39;] = process.env.API_KEY<br>  }<br>  if (process.env.DEBUG){<br>    console.log(&#39;## HEADERS: &#39; + serialize(sanitized_header))<br>  }<br>  return sanitized_header<br>}<br><br>async function getUrl(url, event) {<br>  let base_path = event.path.replace(event.resource.replace(&#39;/{proxy+}&#39;, &#39;&#39;), &#39;&#39;);<br>  let final_url = (event.queryStringParameters) ? `${url}${base_path}?${new URLSearchParams(event.queryStringParameters).toString()}`:`${url}${base_path}`<br>  return final_url<br>}<br><br>// To parse the original body back as json object or string based on the given type<br>function tryParseJSONObject (jsonString){<br>    try {<br>        var o = JSON.parse(jsonString);<br>        if (o &amp;&amp; typeof o === &quot;object&quot;) {<br>            return o;<br>        }<br>    }<br>    catch (e) { }<br>    return jsonString;<br>};</pre><p>The final piece of the puzzle is the route and lambda integration. For external traffic, it will go through /external path of the APIGW_A.</p><pre>resource &quot;aws_api_gateway_resource&quot; &quot;external&quot; {<br>  path_part   = &quot;external&quot;<br>  parent_id   = data.aws_api_gateway_rest_api.app_a.root_resource_id<br>  rest_api_id = data.aws_api_gateway_rest_api.app_a.id<br>}</pre><pre>resource &quot;aws_api_gateway_resource&quot; &quot;external_proxy&quot; {<br>  path_part   = &quot;{proxy+}&quot;<br>  parent_id   = aws_api_gateway_resource.external.id<br>  rest_api_id = data.aws_api_gateway_rest_api.app_a.id<br>}</pre><pre>resource &quot;aws_api_gateway_method&quot; &quot;external&quot; {<br>  rest_api_id      = data.aws_api_gateway_rest_api.app_a.id<br>  resource_id      = aws_api_gateway_resource.corppass_proxy.id<br>  http_method      = &quot;ANY&quot;<br>  authorization    = &quot;NONE&quot;<br>  api_key_required = true<br>}</pre><pre>resource &quot;aws_api_gateway_integration&quot; &quot;external&quot; {<br>  rest_api_id             = data.aws_api_gateway_rest_api.app_a.id<br>  resource_id             = aws_api_gateway_resource.external_proxy.id<br>  http_method             = aws_api_gateway_method.external.http_method<br>  integration_http_method = &quot;POST&quot;<br>  type                    = &quot;AWS_PROXY&quot;<br>  uri                     = aws_lambda_function.external.invoke_arn<br>}</pre><pre>resource &quot;aws_lambda_function&quot; &quot;external&quot; {<br>  filename      = &quot;tf_lambda.zip&quot;</pre><pre>function_name = &quot;lambda-${local.app_a_name}-external&quot;</pre><pre>  role          = data.terraform_remote_state.apigw.outputs.lambda_role_arn<br>  handler       = &quot;src/index.handler&quot;<br>  runtime       = &quot;nodejs16.x&quot;<br>  timeout       = 60<br>  layers        = [aws_lambda_layer_version.lambda_layer.arn]<br>  source_code_hash = data.archive_file.lambda.output_base64sha256</pre><pre>  vpc_config {<br>  subnet_ids         = var.lambda_vpc_subnets<br>  security_group_ids = [aws_security_group.forward_proxy.id] <br>  }<br>  environment {<br>    variables = {<br>    ENDPOINT_URL = var.dummy_endpoint<br>    PROXY_HOST   = var.proxy_ip<br>    PROXY_PORT   = var.proxy_port<br>    }<br>  }<br>  depends_on = [data.archive_file.lambda]<br>}</pre><pre>resource &quot;aws_lambda_permission&quot; &quot;external&quot; {<br>  statement_id  = &quot;AllowExecutionFromAPIGateway&quot;<br>  action        = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.external.function_name<br>  principal     = &quot;apigateway.amazonaws.com&quot;<br>  source_arn = &quot;arn:aws:execute-api:${var.aws_region}:${data.aws_caller_identity.current.account_id}:${data.aws_api_gateway_rest_api.app_a.id}/*/*/*&quot;<br>}</pre><p>And for APP_A to APP_B traffic, we will hit /app_b . As you can see in the lambda function, we are inputing the API Key and endpoint.</p><pre>resource &quot;aws_api_gateway_resource&quot; &quot;app_a&quot; {<br>  path_part   = &quot;app_b&quot;<br>  parent_id   = data.aws_api_gateway_rest_api.app_a.root_resource_id<br>  rest_api_id = data.aws_api_gateway_rest_api.app_a.id<br>}</pre><pre>resource &quot;aws_api_gateway_resource&quot; &quot;app_a_proxy&quot; {<br>  path_part   = &quot;{proxy+}&quot;<br>  parent_id   = aws_api_gateway_resource.app_a.id<br>  rest_api_id = data.aws_api_gateway_rest_api.app_a.id<br>}</pre><pre>resource &quot;aws_api_gateway_method&quot; &quot;app_a&quot; {<br>  rest_api_id      = data.aws_api_gateway_rest_api.app_a.id<br>  resource_id      = aws_api_gateway_resource.app_a_proxy.id<br>  http_method      = &quot;ANY&quot;<br>  api_key_required = true<br>  authorization = &quot;NONE&quot;<br>  request_parameters = {<br>    &quot;method.request.path.proxy&quot; = true<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_integration&quot; &quot;app_a&quot; {<br>  rest_api_id             = data.aws_api_gateway_rest_api.app_a.id<br>  resource_id             = aws_api_gateway_resource.app_a_proxy.id<br>  http_method             = aws_api_gateway_method.app_a.http_method<br>  integration_http_method = &quot;POST&quot;<br>  type                    = &quot;AWS_PROXY&quot;<br>  uri                     = aws_lambda_function.app_b.invoke_arn<br>}</pre><pre>resource &quot;aws_lambda_function&quot; &quot;app_b&quot; {<br>  filename      = &quot;tf_lambda.zip&quot;<br>  function_name = &quot;lambda-${local.app_a_name}-app_b&quot;<br>  role          = data.terraform_remote_state.apigw.outputs.lambda_role_arn<br>  handler       = &quot;src/index.handler&quot;<br>  runtime       = &quot;nodejs16.x&quot;<br>  timeout       = 60<br>  layers        = [aws_lambda_layer_version.lambda_layer.arn]<br>  source_code_hash = data.archive_file.lambda.output_base64sha256<br>  vpc_config {<br>    subnet_ids         = var.lambda_vpc_subnets<br>    security_group_ids = [security_group.reverse_proxy.id]<br>  }<br>  environment {<br>    variables = {<br>      ENDPOINT_URL = &quot;https://${data.aws_api_gateway_rest_api.app_b.id}.execute-api.${var.aws_region}.amazonaws.com/${var.environment}/app_b&quot;<br>      API_KEY      = aws_api_gateway_api_key.app_a_gw.value<br>    }<br>  }<br>  depends_on = [data.archive_file.lambda]<br>}</pre><pre>resource &quot;aws_lambda_permission&quot; &quot;app_a&quot; {<br>  statement_id  = &quot;AllowExecutionFromAPIGateway&quot;<br>  action        = &quot;lambda:InvokeFunction&quot;<br>  function_name = aws_lambda_function.app_a.function_name<br>  principal     = &quot;apigateway.amazonaws.com&quot;<br>  source_arn = &quot;arn:aws:execute-api:${var.aws_region}:${data.aws_caller_identity.current.account_id}:${data.aws_api_gateway_rest_api.app_a.id}/*/*/*&quot;<br>}</pre><pre>resource &quot;aws_api_gateway_resource&quot; &quot;app_b&quot; {<br>  path_part   = &quot;app_b&quot;<br>  parent_id   = data.aws_api_gateway_rest_api.app_b.root_resource_id<br>  rest_api_id = data.aws_api_gateway_rest_api.app_b.id<br>}</pre><pre>resource &quot;aws_api_gateway_resource&quot; &quot;app_b_proxy&quot; {<br>  path_part   = &quot;{proxy+}&quot;<br>  parent_id   = aws_api_gateway_resource.app_b2.id<br>  rest_api_id = data.aws_api_gateway_rest_api.app_b.id<br>}</pre><pre>resource &quot;aws_api_gateway_method&quot; &quot;app_b&quot; {<br>  rest_api_id      = data.aws_api_gateway_rest_api.app_b.id<br>  resource_id      = aws_api_gateway_resource.app_b_proxy.id<br>  http_method      = &quot;ANY&quot;<br>  api_key_required = true<br>  authorization = &quot;NONE&quot;<br>  request_parameters = {<br>    &quot;method.request.path.proxy&quot; = true<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_integration&quot; &quot;app_b&quot; {<br>  rest_api_id             = data.aws_api_gateway_rest_api.app_b.id<br>  resource_id             = aws_api_gateway_resource.app_b_proxy.id<br>  integration_http_method = &quot;ANY&quot;<br>  http_method             = aws_api_gateway_method.app_b.http_method<br>  connection_type         = &quot;VPC_LINK&quot;<br>  connection_id           = aws_api_gateway_vpc_link.app_a.id<br>  type                    = &quot;HTTP_PROXY&quot;<br>  uri                     = &quot;https://${data.aws_lb.<a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lb#dns_name">dns_name</a>}/{proxy}&quot;<br>  request_parameters = {<br>    &quot;integration.request.path.proxy&quot; = &quot;method.request.path.proxy&quot;<br>  }<br>}</pre><pre>resource &quot;aws_api_gateway_vpc_link&quot; &quot;app_a&quot; {<br>  name        = &quot;api-${local.app_a_name}-vpclink&quot;<br>  target_arns = [data.aws_lb.NLB.arn]<br>}</pre><pre>data &quot;aws_lb&quot; &quot;nlb&quot; {<br>  name = &quot;NLB_NAME&quot;<br>}</pre><p>You can imagine how things can go haywire when this is example ballooned to multiple different external application integration. However, this can be resolved with terraform modules. Nevertheless, it is a convoluted setup which introduce unnecessary complexity and little benefit. The 2 API Gateway does not provide any benefit in the picture as Private API Gateway provided by AWS does not have any network segment, which contributes no benefit when you split them into two.</p><h3>Gotchas</h3><p>As you can see, actually the lambda function can be the actual application logic instead of this “router” function. However, because our application already have the logic, which is why we didn’t want to duplicate and maintain 2 of the same function.</p><p>In addition, for signed request where URL is part of the request signing, do that not that you should not sign with API gateway URL. Instead, you should sign with the eventual URL and the request should be send to API gateway. This way, the lambda function will take the same request body, retranslate the url to eventual url.</p><p>Lastly, we also faced self-signed cert issue when integrating to internal services. The workaround is as simple as packing your self signed cert as a lambda layer and attached to the lambda. then you can configure your lambda environment variable NODE_EXTRA_CA_CERTS as /opt/certname.pem . This way, the NodeJS lambda will append with this CA cert when performing any HTTPS call.</p><h3>Final Words</h3><p>I have spent a bit chunk of my time trying to resolve the lambda function in the Axios request as I was facing “socket hang up” error and I was not able to pinpoint the issue. I originally thought the error is has to do with missing VPC configuration or API gateway does not allow request from lambda, or it could be some bug behind the Axios library. In the end, I did the exact request via curl and successfully replicated the error which I slowly took out the x-amzn header.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1022ea2f683" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ansible Playbook using EC2 Plugin via Portforwarding to SSH Port via Session Manager]]></title>
            <link>https://medium.com/@kay.renfa/ansible-playbook-using-ec2-plugin-via-session-manager-from-ssh-port-e68d5a962d2b?source=rss-2d401c9d729d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e68d5a962d2b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ansible]]></category>
            <dc:creator><![CDATA[Kay Ren Fa]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 15:49:57 GMT</pubDate>
            <atom:updated>2023-10-13T15:32:06.226Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS Session Manager provides a nifty way to allow user to hop into the EC2, ECS even though workload resides in private subnet. You can also enable SSH connection via Session manager via CLI. In this article, I will cover how to implement this feature.</p><h3>Pre-requisite</h3><ul><li>A set of EC2 instances with amazon-ssm-manager installed and running with key pair configured and security group opened for connectivity.</li><li>Ansible installed on local machine</li></ul><p>How can we perform both functionalities at the same time via Ansible? After some researching, I realised that there are no mention of such solution.</p><p>Firstly, you can start off with using EC2 dynamic inventory plugin. It is extremely useful when your CI/CD strategy involves constant recreation of EC2 instances via AMI. You will need to enable aws_ec2 plugin in your ansible.cfg file.</p><pre>#ansible.cfg<br>[defaults]<br>inventory_plugins = plugins/inventory<br>host_key_checking = False</pre><pre>[inventory]<br>enable_plugins = aws_ec2, host_list, script, auto, yaml, ini, toml</pre><p>Next, you need an inventory file suffixed with “aws_ec2.yml”. Based on the inventory below, the plugin will retrieve EC2 instance that has “Environment: dev” tags. We then add them into “dev” group. This will be very useful when you have “group_vars” variables that you want this group to inherit dev variables.</p><pre>#inventories/dev_aws_ec2.yml<br>---<br>plugin: aws_ec2<br>regions:<br>  - us-east-2<br>filters:<br>  tag:Environment: dev<br>hostnames:<br>  - instance-id<br>groups:<br>  dev: true</pre><p>Inside your group_vars, you can have environment specific variables. You can then define the SSM bucket which is used to transfer files during playbook execution and the private key to perform ssh connection. This setup will be great as you segregate different set of resource and keys per environment.</p><pre>#group_vars/dev/vars<br>ansible_ssh_private_key_file: ~/.ssh/dev.pem<br>url: dev.company.com</pre><p>The last pieces to the puzzle is the ansible_user which will be used for ssh connection with the private key and the ssh_common_args which is similar to what is suggested in AWS documentation.</p><pre># start.yml<br>- name: Start service<br>  hosts: dev<br>  vars:<br>    ansible_user: ec2-user<br>    ansible_become_method: sudo<br>    ansible_ssh_common_args: &#39;-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ProxyCommand=&quot;aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters &#39;&#39;portNumber=%p&#39;&#39;&quot;&#39;<br>  gather_facts: no<br>  become: yes<br>  tasks:<br>  - name: Start crond<br>    service:<br>      name: &#39;{{ item }}&#39;<br>      state: started<br>      enabled: yes<br>    loop:<br>     - crond</pre><p>By running the command below, it should be able to loop through the set of EC2 instances filtered by Environment tag.</p><pre>ansible-playbook -i inventories/dev start.yml</pre><h3>Gotchas</h3><p>Unlike typical playbook, using the ec2 plugin, instead of IP address, you will connect with instance id. Hence, take note when writing playbook when expecting the results to be IP address.</p><p>You can list the variables generated via the plugin to determine what is the underlying values.</p><pre>ansible-inventory -i inventories/dev_aws_ec2.yml --list / --graph</pre><h3>References</h3><ol><li><a href="https://docs.ansible.com/ansible/latest/collections/community/aws/aws_ssm_connection.html">https://docs.ansible.com/ansible/latest/collections/community/aws/aws_ssm_connection.html</a></li><li><a href="https://docs.ansible.com/ansible/latest/collections/amazon/aws/aws_ec2_inventory.html">https://docs.ansible.com/ansible/latest/collections/amazon/aws/aws_ec2_inventory.html</a></li><li><a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started-enable-ssh-connections.html">https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started-enable-ssh-connections.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e68d5a962d2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hassle-free AWS ECS BlueGreen CodePipeline]]></title>
            <link>https://medium.com/@kay.renfa/aws-ecs-bluegreen-codepipeline-with-private-git-repository-9268a3a65da6?source=rss-2d401c9d729d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9268a3a65da6</guid>
            <category><![CDATA[ec]]></category>
            <category><![CDATA[codepipeline]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Kay Ren Fa]]></dc:creator>
            <pubDate>Tue, 05 Jul 2022 05:33:13 GMT</pubDate>
            <atom:updated>2022-07-05T11:32:15.479Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pre-requisite knowledge</h3><ul><li>Terraform</li><li>Docker</li><li>Basic AWS ECS knowledge</li><li>DevOps BlueGreen Deployment</li></ul><h3>The problem</h3><p>Given this scenario :</p><ul><li>Your application is running on ECS.</li><li>Your git repository is stored in other Git Repository.</li><li>Continuous Integration is already handled by another orchestration tool such as Gitlab, Jenkins for your development environment.</li><li>You have several AWS accounts for different environments (e.g. staging, production)</li><li>Your accounts are managed by Terraform.</li><li>You need a simplified Continuous Deployment workflow to deploy your application to these accounts.</li><li>The problem you are facing is how to have the least tedious way to rollout deployments to these environments.</li></ul><p>Task definition is the blueprint of what the task should be created. Prior to ECS CodeDeploy, you need to provide a task definition and appspec file. But what are some of the options to do so?</p><p>One option is to have another Git repository in CodeCommit with these files inside for CodePipeline to pull as a source artifact and passed down to CodeDeploy. While this option works, you essentially need to manage 2 source of places (i.e. terraform and CodeCommit) whenever any changes to task definition.</p><p>Alternatively, you can dynamically generate the task definition and appspec file. This means that if your infrastructure is managed by Terraform, any changes to the task definition, CodePipeline will always get the latest information. In this article, I will cover how I have approached it.</p><h3>Pre-requisite</h3><p>You need to have following stuff setup and information beforehand</p><ul><li>ECR with images</li><li>ECS Cluster</li><li>Running ECS Service</li></ul><h3>Source</h3><p>For the whole CD process to work, you need to define which ECR and image tag you want CodePipeline to deploy at the end. CodePipeline will pull image tag via the SHA256.</p><p>For instance you set “nginx:stable” as the source. Whenever there is an external CI/CD workflow that builds new image and retag as “nginx:stable”, CodePipeline will fetch the newest image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*ey6qHhRmANFrD5d59zC3DQ.png" /></figure><p>To further level up this process, you can integrate CodePipeline to Eventbridge to monitor the ECR push events trigger CodePipeline. Below is a snippet of the code to implement via terraform.</p><pre>resource &quot;aws_cloudwatch_event_rule&quot; &quot;image_push&quot; {<br>name          = &quot;cwrule-&quot;<br>role_arn      = var.iam_role_cloudwatch_name<br>event_pattern = &lt;&lt;EOF<br>{<br>  &quot;source&quot;: [ &quot;aws.ecr&quot; ],<br>  &quot;detail&quot;: {<br>     &quot;action-type&quot;: [ &quot;PUSH&quot; ],<br>     &quot;image-tag&quot;: [ &quot;${local.cloudwatch_ecr_tag}&quot; ],<br>     &quot;repository-name&quot;: [ &quot;${local.repo_name}&quot; ],<br>     &quot;result&quot;: [ &quot;SUCCESS&quot; ] <br>  },<br>  &quot;detail-type&quot;: [ &quot;ECR Image Action&quot; ] <br>}<br>EOF<br>}</pre><h3>Build</h3><p>CodeBuild is the essential part of this whole integration. CodeBuild runs on an environment which will generate the taskdef.json and appspec.yaml.</p><p>In the previous stage, AWS generates imageDetail.json which contains information of the images in the ECR. This is essential to “inject” into the task definition file. The appspec.yaml defines which revision of task definition to be used for deployment. However, this information isn’t readily accessible for us every time! Therefore, CodeBuild and CodeDeploy use placeholders to replace these values on the fly. Hence, there is no need to constantly pushing the new revision to some git repository.</p><pre># appspec.yaml<br>Resources:<br>- TargetService:<br>   Type: AWS::ECS::Service<br>   Properties:<br>     TaskDefinition: &lt;TASK_DEFINITION&gt;<br>     LoadBalancerInfo:         <br>       ContainerName: &quot;app&quot;<br>       ContainerPort: 8080</pre><p>This fixes one part of the puzzle. How about task definition? Well, the best way is to query your task definition for the latest revision. This fixes the need to manage multiple task definition from various source and about any potential docker image cache with identical image tag. With couple of jq commands, you can replace the latest task definition image with a placeholder. This essentially fixes all loose ends!</p><p>Without much ado, this is how the buildspec.yml can handles it</p><pre># buildspec.yml<br>version: 0.2<br>phases:<br>  install:<br>    runtime-versions:<br>      docker: 18<br>  build:<br>    commands:<br>      - &quot;printf &#39;version: 0.0\nResources:\n  - TargetService:\n      Type: AWS::ECS::Service\n      Properties:\n        TaskDefinition: &lt;TASK_DEFINITION&gt;\n        LoadBalancerInfo:\n          ContainerName: \&quot;${container_name}\&quot;\n          ContainerPort: ${container_port}&#39; &gt; appspec.yaml&quot;<br>      - aws ecs describe-task-definition --output json --task-definition ${task_definition} --query taskDefinition &gt; template.json<br>      - jq &#39;.containerDefinitions | map((select(.name == &quot;${container_name}&quot;) | .image) |= &quot;&lt;IMAGE1_NAME&gt;&quot;) | {&quot;containerDefinitions&quot;:.}&#39; template.json &gt; template2.json<br>      - jq -s &#39;.[0] * .[1]&#39; template.json template2.json &gt; taskdef.json<br>artifacts:<br>  files:<br>    - imageDetail.json<br>    - appspec.yaml<br>    - taskdef.json</pre><p>What happened above is that that after the latest task definition is retrieved. jq command retrieves the containerDefinition section, and look for the container with the given name e.g. “app”. Then it will replace that portion with the placeholder &lt;IMAGE1_NAME&gt;. CodeBuild will then replace these placeholders with actual values before it zips all artifacts to a S3 bucket.</p><h3>Deploy</h3><p>CodeDeploy will pick up these 3 files and proceed with deployment. For BlueGreen deployment, you need to provide a load balancer with 2 target groups, ideally application load balancer for more flexibility.</p><p>ECS will manipulate these 2 target groups and 2 listeners to perform a BlueGreen deployment. For example, LISTENER_LIVE(port: 443) and LISTENER_TEST (port: 8443), TG_A (blue) and TG_B (green).</p><p>When a new deployment triggers, new task are created as TG_B and this get routed to LISTENER_TEST. You can then perform testing with LB DNS port 8443 for the new spun up instances. Once approved on CodeDeploy, ECS will map LISTENER_LIVE to TG_B which means now TG_B will be live. Once deployment is done, traffic from ECS tasks in TG_A will be drained and terminated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X36DFXDu-u7e6M2tcLruMA.png" /></figure><p>Subject to your needs, you can customise your deployment strategies such as</p><ul><li>How task are replaced (e.g. AllatOnce, HalfAtATime)</li><li>Whether you want a manual approval before the BlueGreen swap occurs. This gives you a window to test the Green application</li><li>Whether you want the blue to retain for sometime before termination</li></ul><h3>CodePipeline</h3><p>Lastly, CodePipeline glues these 3 portions together. Following terraform snippet will help in integrating them together.</p><pre>resource &quot;aws_codepipeline&quot; &quot;ecs_pipeline&quot; {<br>name     = &quot;codepipeline-${var.application_name}&quot;<br>role_arn = var.iam_role_codepipeline_name<br>artifact_store {<br>  location = var.bucket_name<br>  type     = &quot;S3&quot;<br>}<br>stage {<br>  name = &quot;Source&quot;<br>  action {<br>    name             = &quot;ImagePush&quot;<br>    category         = &quot;Source&quot;<br>    owner            = &quot;AWS&quot;<br>    provider         = &quot;ECR&quot;<br>    version          = &quot;1&quot;<br>    output_artifacts = [&quot;Image&quot;]<br>    configuration = {<br>      RepositoryName = var.ecr_registery_name<br>      ImageTag       = var.ecr_registery_tag<br>    }<br>  }<br>}<br>stage {<br>  name = &quot;Build&quot;<br>  action {<br>    name             = &quot;Build&quot;<br>    category         = &quot;Build&quot;<br>    owner            = &quot;AWS&quot;<br>    provider         = &quot;CodeBuild&quot;<br>    input_artifacts  = [&quot;Image&quot;]<br>    output_artifacts = [&quot;BuildArtifact&quot;]<br>    version          = &quot;1&quot;<br>    configuration = {<br>      ProjectName = var.codeDeploy_project_name<br>      PrimarySource = &quot;SourceArtifact&quot;<br>    }<br>  }<br>}<br>stage {<br>  name = &quot;Deploy&quot;<br>  action {<br>    name      = &quot;Deploy&quot;<br>    category  = &quot;Deploy&quot;<br>    owner     = &quot;AWS&quot;<br>    provider  = &quot;CodeDeployToECS&quot;<br>    version   = &quot;1&quot;<br>    run_order = 1<br>    input_artifacts = [&quot;BuildArtifact&quot;]<br>    configuration = {<br>      ApplicationName = var.codeDeploy_name<br>      DeploymentGroupName = var.codeDeploy_group_name<br>      TaskDefinitionTemplateArtifact = &quot;BuildArtifact&quot;<br>      TaskDefinitionTemplatePath     = &quot;taskdef.json&quot;<br>      AppSpecTemplateArtifact        = &quot;BuildArtifact&quot;<br>      AppSpecTemplatePath            = &quot;appspec.yaml&quot;<br>      Image1ArtifactName             = &quot;BuildArtifact&quot;<br>      Image1ContainerName            = &quot;IMAGE1_NAME&quot;<br>    }<br>  }<br> }<br>}</pre><h3>Final Thoughts</h3><p>It is definitely daunting for anyone who are new to setting up a CI/CD workflow on AWS as it appears to be a black-box behind the whole integration and a lot of reading required to understand what is required at each phases. But it make sense once everything fall into place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9268a3a65da6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>