<?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 AsmaTheWizard on Medium]]></title>
        <description><![CDATA[Stories by AsmaTheWizard on Medium]]></description>
        <link>https://medium.com/@asmathewizard?source=rss-2a18c2aab510------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8-nHAAxK4-MI1h7KOrynHA.png</url>
            <title>Stories by AsmaTheWizard on Medium</title>
            <link>https://medium.com/@asmathewizard?source=rss-2a18c2aab510------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:24:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asmathewizard/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[No Fluff, Just the Good Stuff: The Key Insights from ALDI(Unifying and Improving Domain Adaptive…]]></title>
            <link>https://asmathewizard.medium.com/no-fluff-just-the-good-stuff-the-key-insights-from-aldi-unifying-and-improving-domain-adaptive-e78dc99fcdf4?source=rss-2a18c2aab510------2</link>
            <guid isPermaLink="false">https://medium.com/p/e78dc99fcdf4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[domain-adaptation]]></category>
            <category><![CDATA[features-alignment]]></category>
            <category><![CDATA[knowledge-distillation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[AsmaTheWizard]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 23:09:31 GMT</pubDate>
            <atom:updated>2025-02-16T23:09:31.134Z</atom:updated>
            <content:encoded><![CDATA[<h3>No Fluff, Just the Good Stuff: The Key Insights from ALDI(Unifying and Improving Domain Adaptive Object Detection) paper with code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qzbLX004TSZ8U9vl5D0pg.png" /></figure><p><strong>Domain:</strong> This paper focuses on Domain Adaptive Object Detection (DAOD), where object detectors perform poorly on data that are different from the training set. ALDI tackles this problem using two-stage detectors based on Faster R-CNN. ALDI developers mentioned that it can be extended to support other type of detectors.</p><h3>The paper:</h3><ol><li>Introduces a <strong>unified framework and benchmark</strong> for Feature Alignment and Knowledge Distillation.</li><li>Proposes a <strong>training and evaluation protocol</strong> for DAOD.</li><li>Releases <strong>CFC-DAOD</strong>, a new dataset for DAOD benchmarking.</li><li>Enhances DAOD methods with a <strong>new approach called ALDI++</strong>.</li></ol><p>The ALDI framework is built using <strong>Detectron2.</strong></p><h3>Key Terminology</h3><h4><strong>Source-only Model (Baseline)</strong> :</h4><p>Trained only on the <strong>source dataset</strong>.</p><h4><strong>Oracle Model</strong>:</h4><p>Trained on the <strong>target dataset</strong> with full supervision.</p><h4><strong>DAOD Goal</strong> :</h4><p>Minimize the gap between the <strong>Baseline model</strong> and <strong>Oracle model</strong> <strong>without supervised training</strong> on the target domain.</p><h4>DAOD :</h4><p>In DAOD, there are many approaches to solve the gap. The most famous methods are : <strong>Feature Alignment</strong>, and the other one is <strong>Self-Distillation.</strong></p><blockquote>Note: ALDI <strong>combines both</strong> in a single framework.</blockquote><ol><li><strong>Feature Alignment</strong> — Reduces the <strong>distribution</strong> gap between the source and target domain.</li><li><strong>Self-Distillation</strong> — Uses a <strong>Teacher-Student</strong> model for knowledge transfer.</li></ol><h4>Feature Alignment</h4><ul><li>The goal is to minimize the distribution difference between the <strong>source domain</strong> (labeled dataset) and the <strong>target domain</strong> (unlabeled dataset).</li><li>It can be done either at the image level or feature level</li></ul><h4>Self-Distillation (Mean Teacher Approach)</h4><p>Also known as <strong>self-training</strong>, where a <strong>Teacher model</strong> generates predictions for the <strong>Student model</strong> to learn from.</p><p><strong>How It Works:</strong></p><ul><li>A <strong>Teacher model</strong> predicts on the <strong>target dataset</strong>.</li><li>The predictions act as labels for the <strong>Student model</strong>.</li><li>The <strong>Teacher model is updated using an Exponential Moving Average (EMA)</strong> of the Student model’s parameters.</li><li>This approach is called <strong>Mean Teacher</strong> in DAOD.</li></ul><h4>Other Known Mean Teacher Techniques are:</h4><ul><li><strong>MTOR</strong></li><li><strong>PT</strong></li><li><strong>CMT</strong></li></ul><blockquote><em>Note: Self-distillation is also used in </em><strong><em>model optimization for production</em></strong><em>, where the goal is to </em><strong><em>reduce model size</em></strong><em> while keeping accuracy close to the Teacher model.</em></blockquote><h3>ALDI Paper Breakdown:</h3><h3>Dataset and Training</h3><ul><li>The dataset consists of <strong>labeled source data</strong> and <strong>unlabeled target data</strong>.</li><li>Each training batch is a <strong>mix of source and target data</strong>:<br><strong>B = B_source + B_target</strong></li></ul><h4>Teacher-Student Model Training:</h4><ol><li>Both models <strong>start with the same weights</strong>, either from <strong>ImageNet pretraining</strong> (Detectron2 Model Zoo) or from supervised pretraining on the <strong>source dataset</strong> (called <strong>Burn-in</strong>).</li><li>The <strong>Teacher model’s weights are updated via EMA</strong>, while the <strong>Student model is trained via backpropagation</strong>.</li></ol><h3>Training Objectives (or Approaches)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qzbLX004TSZ8U9vl5D0pg.png" /><figcaption>ALDI Framework with 3 objectives</figcaption></figure><p>The ALDI framework is <strong>modular</strong>, meaning it can enable/disable specific training objectives. There are <strong>three main training objectives</strong>(I prefer to call it approaches)<strong>:</strong></p><h4>1. Supervised Training with Source Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBrsA1CEle6znWuEuaUjag.png" /><figcaption>ALDI Supervised Training with Source Data</figcaption></figure><ul><li>Uses <strong>labeled source data</strong>.</li><li>Applies Source-domain transformations, pass transformed data to student model, and computes <strong>supervised loss (Lsup)</strong> using Student model predictions and ground truth from <strong>target</strong> data.</li></ul><h4>2. Self-Distillation with Target Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XryxDYJVf7yzlXVyJ60kDQ.png" /><figcaption>ALDI Self-Distillation with Target Data</figcaption></figure><ul><li>Uses <strong>unlabeled target data, </strong>create<strong> </strong>Two copies</li><li>One apply a <strong>weak transformation</strong> → Passed to <strong>Teacher model</strong>.</li><li>One apply a <strong>strong transformation</strong> → Passed to <strong>Student model</strong>.</li><li>The <strong>Teacher’s predictions</strong> act as <strong>distillation targets</strong> for the Student predictions.</li><li>Computes <strong>distillation loss (Ldistill)</strong>.</li><li>Predictions can be <strong>Soft targets</strong> (logits, softmax…etc) or <strong>Hard targets</strong> (thresholded pseudo-labels).</li></ul><h4>3. Feature Alignment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qzbLX004TSZ8U9vl5D0pg.png" /><figcaption>ALDI Feature Alignment</figcaption></figure><ul><li>Aligns Source and Target sample using <strong>Lalign</strong>[Purple area in above image]<strong>, </strong>which basically enforce invariance across domains at either the image or feature level.</li><li>ALDI team used two losses used: <strong>Domain-Adversarial Training</strong> (DANN), and <strong>Image-to-Image Alignment.</strong></li></ul><p><strong>3.1- Domain-Adversarial Training (DANN)</strong></p><ul><li>Trains a <strong>domain classifier</strong> to differentiate between source and target features.</li><li>Simultaneously, the feature extractor <strong>learns to confuse the domain classifier</strong>, enforcing invariance across domains.</li></ul><p><strong>3.2- Image-to-Image Alignment</strong></p><ul><li>Works in <strong>pixel space</strong> by transforming source images into the target domain or vice versa. You can think of photoshopping/translating one image to another.</li><li>The transformed images are then used for training.</li></ul><h3>Codebase</h3><p>The framework use COCO format. You can either extend LOADER to work with other formats, or convert your dataset to COCO format.</p><p>The project GitHub repository has 4 folders, which are:</p><pre>.<br>├── README.md                   # Readme file<br>├── aldi/                       # ALDI framework folder<br>├── config/                     # YAML configuration files for building models<br>├── docs/                       # Documentation<br>├── tools/                      # Scripts to use ALDI framework, such as training script<br>├── .gitignore                  # Files and directories to be ignored by Git<br>└── pyproject.toml              # configuration file</pre><p>You don’t to install and build Detectron2, the ALDI framework will install it as part of its dependencies.</p><h4>Tools folder:</h4><p>It has many scripts, but the most important one is<strong> train_net.py</strong>. Here, you can either start a new training or run inference/evaluation. The script is Detectron2 train script, where you pass to it YAML config file for the model you want, and the run mode (train or eval), then the code will setup the configuration using Detectron2 base configuration settings and your YAML file. Build model, and run it.</p><p><strong>Aldi folder:</strong></p><pre>.<br>├── __init__.py                 <br>├── align.py                       <br>├── aug.py                     <br>├── backbone.py                       <br>├── checkpoint.py                      <br>├── config.py                     <br>├── dataloader.py                      <br>├── datasets.py                      <br>├── distill.py                   <br>├── dropin.py                       <br>├── ema.py                      <br>├── helpers.py                     <br>├── model.py                       <br>├── pseudolabeler.py                      <br>└── trainer.py              </pre><p>Most important files are:</p><h4>Aug.py:</h4><p>Python code that utilize Detectron2 augmentation function, to apply weak and strong augmentation in ALDI framework.</p><h4>Backbone.py:</h4><p>This code defines custom functions and modifications for a Vision Transformer (ViT) backbone. ALDI by default support Resnet50 w/ FPN from Detectron2, and this code change that to support VitDet-B backbone.</p><h4>Model.py:</h4><p>Here, the framework extend the Detectron2 default build model functionality to include AlignMixin(Feature Alignment function), and DistillMixin(self-distilation function), create the model from configuration passed from train_net.py and move the model to either GPU or CPU.</p><h3>Final Thoughts</h3><p>ALDI provides a <strong>unified framework</strong> that integrates Feature Alignment and Self-Distillation. The modular design allows different DAOD techniques to be easily implemented and benchmarked.</p><p>🔗 <strong>Links:</strong></p><ul><li><strong>Framework</strong>: <a href="https://github.com/justinkay/aldi/tree/main">https://github.com/justinkay/aldi/tree/main</a></li><li><strong>Dataset</strong>: arxiv.org/pdf/2403.12029</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e78dc99fcdf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asma QuickStart guide: Setup a HPC with AWS]]></title>
            <link>https://asmathewizard.medium.com/asma-quickstart-guide-setup-a-hpc-with-aws-b267edbf374d?source=rss-2a18c2aab510------2</link>
            <guid isPermaLink="false">https://medium.com/p/b267edbf374d</guid>
            <category><![CDATA[aws-parallelcluster]]></category>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[hpc]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud9]]></category>
            <dc:creator><![CDATA[AsmaTheWizard]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 05:10:28 GMT</pubDate>
            <atom:updated>2023-02-06T05:10:28.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxH0erCQODl9ucyoDNo88w.png" /></figure><p>High-Performance Computing (HPC) has become an increasingly important tool for solving complex scientific and engineering problems and can help accelerate research and innovation. However, setting up an HPC cluster can be a challenging and time-consuming task, requiring specialized hardware and expertise in system administration. Fortunately, cloud computing services like Amazon Web Services (AWS) offer a convenient and cost-effective alternative, enabling you to quickly and easily spin up a cluster of compute nodes with just a few clicks. In this post, I will guide you through the process of creating an HPC cluster on AWS, showing you how to use AWS services like EC2, S3, and EFS to build a scalable and flexible computing environment that meets your needs. Whether you’re a researcher, engineer, or data scientist, this post will help you get started with using AWS to solve your HPC problems.</p><h3><strong>Important points to remember:</strong></h3><p>1- No matter what approach you will use to create a cluster with AWS, you will directly or indirectly be using AWS CloudFormation.</p><p>2- CloudFormation in itself is free but it will create other AWS services such as EC2 instance which will charge you per use.</p><p>3-Always delete everything once you are done with the service.</p><p>4- Most importantly, pay attention to which region you are creating your services in. Services such as SSH key, a cluster,…etc should be in the same region.</p><p>5- Before creating any service, check if the region and zone you selected are supporting the type of services you want such as EC2 instance type.</p><h4>Head Node vs Computer Node:</h4><p>In an HPC cluster, the head node acts as the central control point for managing and coordinating the work performed by the compute nodes, which are optimized for running computational workloads. The head node handles job scheduling, user authentication, and access, while the compute nodes run parallel jobs and communicate with the head node. The head node and compute nodes work together to provide a scalable and efficient computing environment.</p><h4><strong>SLURM</strong></h4><p>Later on, when we will build the cluster, we will add a tool to be set-up with the cluster, this tool is called Slurm.</p><blockquote>SLURM (Simple Linux Utility for Resource Management) is an open-source job scheduler and resource manager for large-scale cluster systems. It provides a comprehensive set of tools to manage and allocate resources, such as computing nodes, memory, and I/O bandwidth, among other resources, to multiple users and workloads in a cluster environment.</blockquote><p>The simplest example I can think of is the cluster = your Airbnb apartment that you listed and SLURM is your Airbnb guests! You will build your apartment /renovate it once and listed to be rented by strangers to use it for some period of time.</p><h4><strong>AWS ParallelCluster CLI vs AWS ParallelCluster Manager:</strong></h4><p>As with any service in AWS, there are multiple approaches depending on your skill level and how much time you want to invest. To create a cluster in AWS you can do that by CLI or GUI.</p><ul><li>CLI tool is <strong>AWS ParallelCluster CLI</strong>.</li><li>GUI tool is <strong>AWS ParallelCluster Manager</strong>.</li></ul><p>AWS ParallelCluster is a tool that makes it easy to set up and manage HPC clusters on the AWS cloud. There are two main components of AWS ParallelCluster: the AWS ParallelCluster CLI and the AWS ParallelCluster Manager. The AWS ParallelCluster CLI is a command line interface that allows you to launch and manage HPC clusters directly from your terminal. It provides a simple and easy-to-use interface for controlling various aspects of your cluster, such as launching instances, setting up networking, and configuring storage. On the other hand, the AWS ParallelCluster Manager is a web-based graphical user interface that provides a more intuitive and interactive way to manage your HPC clusters. It offers a visual representation of your cluster resources and provides a convenient way to perform common cluster management tasks, such as adding or removing nodes, monitoring cluster usage, and managing storage. Both the AWS ParallelCluster CLI and Manager are useful tools for creating and managing HPC clusters on AWS, and the choice of which one to use will depend on your individual needs and preferences.</p><p>In this post, I’ll demonstrate the CLI option, if you want to learn more about the GUI you can refer to this link <a href="https://www.hpcworkshops.com/02-deploy-pcm.html">here</a>.</p><blockquote>In a few words, to use the GUI, you will have to install the GUI using AWS CloudFormation and from it, you can set up the cluster setting.</blockquote><h3>AWS ParallelCluster CLI:</h3><p>Personally, I prefer to use the command line method. To use CLI, We have 2 options, either we can use the command line from our local computer or use AWS Cloud9, the fastest method is to use AWS cloud9 which we will be using in this tutorial.</p><p>Note: you still can follow this tutorial with the same instructions but from your local machine, but first you have to install AWS CLI and setup it up locally, to do so follow the below tutorial.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRp-A84oh4G8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRp-A84oh4G8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRp-A84oh4G8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cfc31fa83c3471d3be0155c424c7c77/href">https://medium.com/media/7cfc31fa83c3471d3be0155c424c7c77/href</a></iframe><h3>AWS Cloud9:</h3><p>Log in to AWS, change region to Ohio us-east-2, and search cloud9 in the search bar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0ImmNU6EomrnUVbe6JdBg.png" /></figure><p>Click on Create environment button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzyl88VBA8Ia_srnsCOuYA.png" /></figure><p>Write any name you want for the cloud9 environment, and scroll down to the Timeout option, change it from 30 min to 1 day, the rest keep the default values. Click on create button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLToFzmNhwvPaY7sq9Fw5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyVq-Rd1NbmIQpLBakP4Aw.png" /></figure><p>It will take several minutes to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3x_LUhLUwpoY011P0IQ-KQ.png" /></figure><p>Click on the open link to open the IDE, now you have IDE on the cloud preconfigured with AWS CLI! The left panel is your file tree, the middle section is tap/taps, and the below section is your terminal with Bash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECh3vn1aTXI_kpVeazUy7Q.png" /></figure><p>To check AWS CLI version, you can run the below command in the terminal</p><pre>aws --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJie3P1kDkiw6PBLTeQD1w.png" /></figure><h3>Create SSH key:</h3><p>In AWS, you need to generate an ssh key before creating an ec2 instance or cluster, because, at the moment of creating them, AWS will ask you how you want to connect it. Again, with almost anything in AWS, you can create an SSH key either through GUI or CLI, we will use the latter by simply running the following command in the cloud9 terminal</p><pre>aws ec2 create-key-pair --key-name hpc-project --query KeyMaterial --output text &gt; hpc-project.pem</pre><p>Here, you can name your SSH key any name you like, in my case I named it ‘hpc-project’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lz2qIRzp5iHqyyKoydBWbg.png" /></figure><p>it will create a pem file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLj_o8Epq4F-Y484awT1UQ.png" /></figure><p>then run this command</p><pre>chmod 600 hpc-project.pem</pre><p>After that, add your file reference to .basher</p><pre>echo &quot;export AWS_KEYPAIR=hpc-project&quot; &gt;&gt; ~/.bashrc<br>source ~/.bashrc</pre><p>To check your keys, run the following command</p><pre>aws ec2 describe-key-pairs</pre><h3>AWS ParallelCluster:</h3><p>In the Cloud9 terminal, run this command to install AWS ParallelCluster</p><pre>pip3 install &quot;aws-parallelcluster&quot; --upgrade --user</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zMpk2ZC5_fW2befyMcyPQ.png" /></figure><p>to create a cluster, first, we need a cluster config file. You can create it using the interactive command line or create a config file directly. Both of them will generate a cluster configuration file that when you build it will create a CloudFormation stack.</p><blockquote>Cluster specifications -&gt; Cluster config file -&gt; Build- config file&gt; Cluster is ready</blockquote><p><strong>METHOD 1: the interactive method:</strong></p><p>run this command in the cloud9 terminal and answer prompt questions</p><pre>pcluster configure --config config.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5lb659utzmvDHd3PZJjYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U8RiW-5ynTmhJBlx8fHjqQ.png" /></figure><p><strong>METHOD 2: Create config file:</strong></p><p>run the following command in the cloud9 terminal, to get subnet and region values.</p><pre>IFACE=$(curl --silent http://169.254.169.254/latest/meta-data/network/interfaces/macs/)<br>SUBNET_ID=$(curl --silent http://169.254.169.254/latest/meta-data/network/interfaces/macs/${IFACE}/subnet-id)<br>VPC_ID=$(curl --silent http://169.254.169.254/latest/meta-data/network/interfaces/macs/${IFACE}/vpc-id)<br>REGION=$(curl --silent http://169.254.169.254/latest/meta-data/placement/availability-zone | sed &#39;s/[a-z]$//&#39;)</pre><p>then change YOUR_KEY_NAME in the below script before running it in cluoud9 terminal</p><pre>cat &gt; config.yaml &lt;&lt; EOF<br>Region: ${REGION}<br>Image:<br>  Os: alinux2<br>SharedStorage:<br>  - MountDir: /shared<br>    Name: default-ebs<br>    StorageType: Ebs<br>HeadNode:<br>  InstanceType: c5.xlarge<br>  Networking:<br>    SubnetId: ${SUBNET_ID}<br>    ElasticIp: false<br>  Ssh:<br>    KeyName: YOUR_KEY_NAME<br>Scheduling:<br>  Scheduler: slurm<br>  SlurmQueues:<br>    - Name: compute<br>      CapacityType: ONDEMAND<br>      ComputeResources:<br>        - Name: compute<br>          InstanceType: c5.xlarge<br>          MinCount: 0<br>          MaxCount: 8<br>          DisableSimultaneousMultithreading: true<br>      Networking:<br>        SubnetIds:<br>          - ${SUBNET_ID}<br>        PlacementGroup:<br>          Enabled: true<br>EOF</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIL0IEJoMzbn0jCY09iMKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*rRfLeC8w9S2VNJ-Ejs6Fsw.png" /></figure><h3>Build a Cluster:</h3><p>No matter what method you used, you will end up with yaml config file to create the cluster.</p><h4><strong>Note:</strong></h4><p>As you can see from above, I always pick Slurm to be created with the cluster.</p><p>To build the cluster, run the below command in the cloud9 terminal</p><pre>pcluster create-cluster --cluster-name hpc-cluster --cluster-configuration config.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mu8s2pI8USrDbDT2LRKTjw.png" /></figure><p>the cluster is currently in progress, to check the status, you can run this command</p><pre>pcluster list-clusters</pre><p>Or go to the CloudFormation page to see the new cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-SQtbBf8WfIYLuTNTC1UEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxojwJ4hmXQP5xLLHRbiKw.png" /></figure><p>Once it shows that the clusterStatus is “CREATE_COMPLETE”, we are ready to log in to the cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uI9P3oagqBI2OKV2rMzAHA.png" /></figure><h3><strong>Log in:</strong></h3><p>from the cloud9 terminal you can log in to the cluster head node by running</p><pre>pcluster ssh --cluster-name hpc-cluster -i hpc-project.pem</pre><p>The prompt will ask you “Are you sure you want to continue connecting?” write yes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFwNZre5fX12cTtwvrocZg.png" /></figure><p>Now, you are logged in to your cluster head node!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26FmSeF5yosvEgWNq%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26FmSeF5yosvEgWNq%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F26FmSeF5yosvEgWNq%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/e48184be6c25431a6abebf73dd1b5e3d/href">https://medium.com/media/e48184be6c25431a6abebf73dd1b5e3d/href</a></iframe><h3><strong>Resources</strong>:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYXkt4SDxkAc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYXkt4SDxkAc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYXkt4SDxkAc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba54710bf7117e51ecd2d0bb7ac02e21/href">https://medium.com/media/ba54710bf7117e51ecd2d0bb7ac02e21/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOZRYRqDrkCM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOZRYRqDrkCM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOZRYRqDrkCM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/358bd387de9827f51a71128018474e2e/href">https://medium.com/media/358bd387de9827f51a71128018474e2e/href</a></iframe><p><a href="https://docs.aws.amazon.com/parallelcluster/latest/ug/getting-started-configuring-parallelcluster.html">Configuring AWS ParallelCluster</a></p><p><a href="https://chat.openai.com/">https://chat.openai.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b267edbf374d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asma QuickStart guide: Dataset and Dataloader in Pytorch]]></title>
            <link>https://asmathewizard.medium.com/asma-quickstart-guide-dataset-and-dataloader-in-pytorch-f77b2e377f51?source=rss-2a18c2aab510------2</link>
            <guid isPermaLink="false">https://medium.com/p/f77b2e377f51</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dataloader]]></category>
            <category><![CDATA[custom-dataset]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[dataset]]></category>
            <dc:creator><![CDATA[AsmaTheWizard]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 03:00:58 GMT</pubDate>
            <atom:updated>2023-02-06T03:00:58.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNaNk-F2Bmq56AtvD7dVSg.png" /><figcaption>Credit: DALL-E</figcaption></figure><p>In this post, we’ll explore how to use the Dataset and DataLoader classes to efficiently load, pre-process, and batch your data, and provide examples of how to use it. Whether you&#39;re a beginner or an experienced PyTorch user, this post will provide you with a comprehensive understanding of how to use these essential components in your deep-learning projects.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FBpGWitbFZflfSUYuZ9%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FBpGWitbFZflfSUYuZ9%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMXo0bTV5a285Znp6Zjg1OGJwanAwMTF0dDdtYnoyOGUxbGpyY2d4ciZlcD12MV9naWZzX2dpZklkJmN0PWc%2FBpGWitbFZflfSUYuZ9%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="363" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f3adc02048a2e7c8a20f23b21df942f/href">https://medium.com/media/3f3adc02048a2e7c8a20f23b21df942f/href</a></iframe><h3>What is Pytorch?</h3><p>It is an open-source software library for machine learning(ML), primarily used for natural language processing (NLP) and computer vision tasks. It provides a rich set of tools and libraries for data loading, processing, and model training, making it a popular choice for both research and production use.</p><h3>What is Dataset in Pytorch?</h3><p>In PyTorch, a dataset is a collection of data that can be used to train a ML model. It is a key component of the PyTorch data loading and processing pipeline.</p><p>It’s worth mentioning that the ML pipeline in PyTorch can be represented as follows:</p><blockquote>Preprocess data /creates dataset <strong>-&gt;</strong> load data <strong>-&gt; </strong>train -&gt; evaluate</blockquote><p>To create a dataset, you need to do the following steps:</p><p>1-Import libraries</p><p>2- Create a class that inherits from <strong>Dataset</strong> class</p><p>3-Override __len__ and __getitem__ methods, the first method returns the number of samples in the dataset, while the second method returns a specific sample from the dataset given an index.</p><h3>What is Dataloader in Pytorch?</h3><p>It’s used to easily load the dataset and iterate over the data in a dataset efficiently. Not only that, but it also provides batching, shuffling, and multi-threaded loading features.</p><p>You can use built-in datasets by the PyTorch team for famous datasets such as MNIST <a href="https://pytorch.org/vision/stable/datasets.html">here</a> or build your own custom dataset from scratch which what I will cover in this post.</p><h3>Structure of Data:</h3><h4><strong>Annotations:</strong></h4><p>You can have your annotations saved as one JSON file, or one txt or XML file per image. It doesn’t make that huge difference because, at the end of the day, we just want to locate bounding boxes and labels for each image. In this case, I had annotation saved as XML files, one XML file per each image, and the file name match the image name.</p><h4><strong>Folder Structure:</strong></h4><p>You can save all of your images and labels in one folder or separate them, personally, I prefer to follow this folder structure to make things simpler and straightforward</p><pre>Root Folder:<br>- Dataset Folder<br>   - - Train folder<br>        - - - IMAGES folder<br>        - - - LABELS folder<br>   - - Test Folder<br>        - - - IMAGES folder<br>       -  - - LABELS folder<br>- Model Folder</pre><h4><strong>Bounding Boxes(2D):</strong></h4><p>I mentioned earlier that the file of annotation n doesn’t make a huge difference, which it’s true but the format of Bounding Boxes-in the annotation file- will make or break your project. You can convert Bounding boxes before the dataset step or during the dataset step.</p><p><strong>Bounding boxes formats can be:</strong></p><ul><li><strong>x, y, width, height:</strong> top-left corner of the bounding box, width, and height of the bounding box. Commonly known as COCO format (from the COCO dataset)</li><li><strong>x1, y1, x2, y2</strong>: top-left corner or bounding box and bottom-right corner, also it can be written as <strong>x_min, y_min, x_max, y_max</strong>, both are the same. Commonly known as PASCAL VOC (from the PASCAL VOC dataset).</li><li><strong>x_center, y_center, width, height</strong>: it represents the center coordinate of the bounding box with its width and height of it. Till now, I saw this format only used with any YOLO model.</li></ul><h3>Code:</h3><h4>Libraries</h4><pre>#libraries<br>import os<br>import albumentations as A # for image transformation <br>import cv2 # load image, resize<br>import numpy as np <br>import torch<br>from torch.utils.data import Dataset, DataLoader<br><br>#because my annotation files are XML, so I&#39;ll use it to extract data<br>from xml.etree import ElementTree as et</pre><h4>Dataset Class Structure</h4><p>We will create a class, you can name it whatever you want, here I named it CustomDataset :) the class will inherit from Dataset, and it will have 4 methods:</p><ul><li><strong>__init__:</strong> initiate variables values and get the list of images we have (just names). The dataset will not work without this method.</li><li><strong>get_image_files: </strong>helper method to get the list of images’ names.</li><li><strong>__getitem__</strong>: here we will get the image, its labels, and its bounding boxes by id. The dataset will not work without this method.</li><li><strong>__len__</strong>: to get length of images list that we created in __init__ method</li></ul><pre>class CustomDataset(Dataset):<br>    def __init__(self):<br>        ...<br>    <br>    def get_image_files(self):<br>       ...<br><br>    def __getitem__(self):<br>        ...<br><br><br>    def __len__(self):<br>        ...</pre><h4><strong>__init__</strong></h4><p>You don’t have to follow the code exactly. What we need to do here is</p><p>1- set paths for the images folder and annotations folder, you still can use only the root path and inside code build subdirectory paths.</p><p>2- pass the list of classes /label names, the order is important here.</p><p>3- pass the new height and width of an image to resize it later in <strong>__getitem__</strong>. You can resize all images beforehand and skip resizing each image in <strong>__getitem__ </strong>but if you resize the image you need to calculate a new bounding box.</p><p>4- create a list of all image names. Again, to simplify things, save names in the list without extension.</p><p>5- pass transformer function, we will create a global function using albumentations library, one for training and another one for testing.</p><pre>def __init__(self, dir_img_path, dir_annotation_path, classes, width, height, transforms=None):<br>  self.dir_img_path = dir_img_path<br>  self.dir_annotation_path = dir_annotation_path<br>  self.classes = classes<br>  self.new_height = height<br>  self.new_width = width<br>  self.all_images = self.get_image_files()<br>  self.transforms = transforms</pre><h4>__getitem__</h4><p>Here, we mainly do 2 things:</p><p>1- load the image and process it (convert color channel, resize) also apply the transformer.</p><p>2- load the annotation file, extract data from it (the extraction part will vary depending on your annotation file and format), process the bounding box (resize if we resized its image, convert from one format to another if needed, normalization procedure if needed), and extract label(convert from text to class id).</p><pre>def __getitem__(self, idx):<br>      #get image name by id <br>      image_name = self.all_images[idx]<br>      image_path = os.path.join(self.dir_img_path, image_name)<br>      <br>      #read the image<br>      image = cv2.imread(image_path)<br><br>      #convert BGR to RGB color format, because cv2 read image as BRG and we need RGB<br>      image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)<br>      image_resized = cv2.resize(image, (self.new_width, self.new_height)) #resize image<br>      image_resized /= 255.0<br>      <br>      # get the annotation file<br>      annot_filename = image_name + &#39;.xml&#39;<br>      annot_file_path = os.path.join(self.dir_annotation_path, annot_filename)<br>      <br>      boxes = []<br>      labels = []<br><br>      #because my annotation file is xml<br>      tree = et.parse(annot_file_path)<br>      root = tree.getroot()<br>      <br>      #get the height and width of the image (original height and width)<br>      image_width = image.shape[1]<br>      image_height = image.shape[0]<br>      <br>      for member in root.findall(&#39;object&#39;):<br>          labels.append(self.classes.index(member.find(&#39;name&#39;).text))<br>          xmin = int(member.find(&#39;bndbox&#39;).find(&#39;xmin&#39;).text)<br>          xmax = int(member.find(&#39;bndbox&#39;).find(&#39;xmax&#39;).text)<br>          ymin = int(member.find(&#39;bndbox&#39;).find(&#39;ymin&#39;).text)<br>          ymax = int(member.find(&#39;bndbox&#39;).find(&#39;ymax&#39;).text)<br>          <br>          #resize the bounding boxes <br>          xmin_final = (xmin/image_width)*self.new_width<br>          xmax_final = (xmax/image_width)*self.new_width<br>          ymin_final = (ymin/image_height)*self.new_height<br>          yamx_final = (ymax/image_height)*self.new_height<br>          <br>          #if you need to calculate bounding boxes normalization, then you should do it here before appending the bounding box to the list<br>          boxes.append([xmin_final, ymin_final, xmax_final, yamx_final])<br>      <br>      #bounding box to tensor<br>      boxes = torch.as_tensor(boxes, dtype=torch.float32)<br>      #area of the bounding boxes<br>      area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])<br>      #no crowd instances<br>      iscrowd = torch.zeros((boxes.shape[0],), dtype=torch.int64)<br>      #labels to tensor<br>      labels = torch.as_tensor(labels, dtype=torch.int64)<br>      # prepare the final `target` dictionary<br>      target = {}<br>      target[&quot;boxes&quot;] = boxes<br>      target[&quot;labels&quot;] = labels<br>      target[&quot;area&quot;] = area<br>      target[&quot;iscrowd&quot;] = iscrowd<br>      image_id = torch.tensor([idx]) #convert img id to tensor as well<br>      target[&quot;image_id&quot;] = image_id<br>      <br>      #apply the image transforms<br>      if self.transforms:<br>          sample = self.transforms(image = image_resized,<br>                                    bboxes = target[&#39;boxes&#39;],<br>                                    labels = labels)<br>          image_resized = sample[&#39;image&#39;]<br>          target[&#39;boxes&#39;] = torch.Tensor(sample[&#39;bboxes&#39;])<br>          <br>      return image_resized, target</pre><h4>__len___</h4><p>Just return the length of the image names list.</p><pre>    def __len__(self):<br>        return len(self.all_images)</pre><h4>Transformer</h4><p>A transformer in PyTorch using Albumentations is a data augmentation technique that is used to increase the size of the training dataset by applying random transformations to the existing images. Here, I created 2 functions, one for the training dataset and the other one for the testing dataset. You can play with configuration here, the only thing that you need to keep in mind is that you need to tell it the bounding box format by using <strong>bbox_params</strong>. Otherwise, it will nor performs as you hope.</p><pre># the training tranforms<br>def get_train_transform():<br>    return A.Compose([<br>        A.Flip(0.5),<br>        A.RandomRotate90(0.5),<br>        ToTensorV2(p=1.0),<br>    ], bbox_params={<br>        &#39;format&#39;: &#39;pascal_voc&#39;,<br>        &#39;label_fields&#39;: [&#39;labels&#39;]<br>    })<br><br># the test transforms<br>def get_test_transform():<br>    return A.Compose([<br>        ToTensorV2(p=1.0),<br>    ], bbox_params={<br>        &#39;format&#39;: &#39;pascal_voc&#39;, <br>        &#39;label_fields&#39;: [&#39;labels&#39;]<br>    })</pre><p>Now, we will create 2 datasets as follows:</p><pre>train_dataset = CustomDataset(IMG_TRAIN_DIR, ANN_TRAIN_DIR, CLASSES,  WIDTH, HEIGHT,  get_train_transform())<br>valid_dataset = CustomDataset(IMG_TEST_DIR, ANN_TEST_DIR, CLASSES,  WIDTH, HEIGHT,  get_test_transform())</pre><h3>Dataloader:</h3><p>Now we can load the dataset to use it later for training, we will have to specify batch size and pass a function to combine a list of samples into a batch.</p><pre>#used to combine a list of samples into a batch, which is then passed<br>def collate_fn(batch):<br>    return tuple(zip(*batch))</pre><pre>train_loader = DataLoader(<br>    train_dataset,<br>    batch_size=BATCH_SIZE,<br>    shuffle=True,<br>    num_workers=0,<br>    collate_fn=collate_fn<br>)<br><br>valid_loader = DataLoader(<br>    valid_dataset,<br>    batch_size=BATCH_SIZE,<br>    shuffle=False,<br>    num_workers=0,<br>    collate_fn=collate_fn<br>)<br></pre><p>In conclusion, Dataset and DataLoader classes are fundamental components in the PyTorch framework that make it easy to load and process your data. By using these classes, you can efficiently load and batch your data, apply pre-processing transformations, and feed it into your model for training. Understanding how to use these classes will help you build robust and efficient deep-learning pipelines, and will enable you to tackle a wide range of tasks with ease. This post has provided a comprehensive introduction to using the Dataset and DataLoader classes in PyTorch, and I hope it has helped you to gain a deeper understanding of these important concepts. Happy learning!</p><p>And that’s a wrap!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F8VrtCswiLDNnO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F8VrtCswiLDNnO%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F8VrtCswiLDNnO%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="250" frameborder="0" scrolling="no"><a href="https://medium.com/media/04414d15a0e17348b804eec3b4c2b2d1/href">https://medium.com/media/04414d15a0e17348b804eec3b4c2b2d1/href</a></iframe><p><strong>Resources:</strong></p><ul><li><a href="https://debuggercafe.com/custom-object-detection-using-pytorch-faster-rcnn/">Custom Object Detection using PyTorch Faster RCNN</a></li><li><a href="https://www.kaggle.com/code/basu369victor/pytorch-tutorial-the-classification/notebook">PyTorch-Tutorial (The Classification)</a></li></ul><p><a href="https://chat.openai.com/">https://chat.openai.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f77b2e377f51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asma QuickStart Guide: Your first day with Firebase Local Emulator Suite and Firebase Functions…]]></title>
            <link>https://asmathewizard.medium.com/asma-quickstart-guide-your-first-day-with-firebase-local-emulator-suite-and-firebase-functions-ef74e0002344?source=rss-2a18c2aab510------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef74e0002344</guid>
            <category><![CDATA[emulator]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[firestore]]></category>
            <dc:creator><![CDATA[AsmaTheWizard]]></dc:creator>
            <pubDate>Sun, 18 Apr 2021 01:00:13 GMT</pubDate>
            <atom:updated>2021-04-18T01:00:13.203Z</atom:updated>
            <content:encoded><![CDATA[<h3>Asma QuickStart Guide: Your first day with Firebase Local Emulator Suite and Firebase Functions and Firebase Firestore</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEpcRrKBMjFnMAqbyHJRtA.jpeg" /></figure><p>I promised two of my friends that I will write QuickStart guide to Firebase, so here we are :)</p><p>Malak and Sultan… this is for you as I promised</p><h4>This post will cover briefly following topics:</h4><ul><li>What is Firebase?</li><li>Installing Firebase CLI</li><li>Running Firebase Emulator</li><li>Firebase functions</li><li>Firebase Firestore vs Firebase Realtime Database</li><li>Simple Firebase function CRUD</li><li>Deploy Firebase function</li></ul><h3>What is Firebase?</h3><p>*under progress</p><h3>Installing Firebase CLI</h3><p>1- install node.js, it require version 10+</p><p>2- run command</p><pre>npm install -g firebase-tools</pre><p>to double check that you successfully installed Firebase CLI, run below command in terminal/cmd. It should print to you the firebase CLI version.</p><p>Note: V is capital letter</p><pre>firebase -V</pre><p>After that you should login to firebase by running</p><pre>firebase login</pre><p>It will ask you if you want to allow Firebase CLI to collect information about your usage and error report, type Y then press enter, it will open your default browser to the famous Google login page, enter your gmail account and password click next, then click Allow button, if this page is shown then you are set to FLY!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*SDMB39yVCDtnY44dFySexQ.png" /></figure><h3>Running Firebase Emulator</h3><p>The Firebase team created tools to <strong>mimic</strong> various Firebase services <strong>locally</strong> which can be used to build, run and test apps, these tools called Firebase Local Emulator Suite.</p><p>With Firebase Local Emulator Suite you can test locally following services:</p><ul><li>Cloud Firestore</li><li>Realtime Database</li><li>Authentication</li><li>Cloud Functions</li><li>Pub/Sub (only for Node.js Admin SDK)</li><li>Firebase Hosting</li></ul><p><a href="https://firebase.google.com/docs/emulator-suite">Introduction to Firebase Local Emulator Suite</a></p><p>Pre-requests&#39;:</p><ul><li>node.js</li><li>Java</li></ul><p>then create directory in you local machine that is Firebase project. I created mine in my Desktop and I name it AsmaRock then in terminal inside folder, I run</p><pre>firebase init</pre><p>the terminal will show message asking you if you are ready :), type Y then press enter key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xn38ZeVj0z4jVH2IibFVPQ.png" /></figure><p>then it will ask you what Firebase CLI features you want to use, you can move between list by clicking on Up and Down key, and press on Space button to select option, here I picked Firestore, Functions, and Emulator. Press enter key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4-j45EYJ6cYPaXwS2Yfsw.png" /></figure><p>Then, it will ask you to select project, I will pick “Create a new project” option. For project id, it should be unique across all Firebase, so I recommend you to enter random number otherwise it will through error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRmd30U1ckap8aqMsSE9_g.png" /></figure><p>it successfully created project for us, and because it is the first time, we need to go to Firebase web UI to set Firebase Firestore. So, copy and paste in your browser the link shown in terminal, below page will be open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uxwDwhkEdhd23f41des-w.png" /></figure><p>click on Create database button, pop-up modal will shown with two option, for quick development purpose you can use Test mode but DO NOT go to production with this option ever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYJVfatQqwbdexvmgr_tKw.png" /></figure><p>click Next button, it will ask you to choose a location, it’s recommended to chose a region that is nearest to your customers otherwise they will face some slowness.</p><p>For demo purpose, I will go with default option for location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3r1NLU-FqYo_iGyeeKQniQ.png" /></figure><p>click Enable.</p><p>Now, go back to terminal and run again</p><pre>Firebase init</pre><p>but this time choose “use an existing project”, it will show list of projects -in your case it should be only one project, the one we just created above-, choose the project and press enter. It will setup Firebase, it will ask you couple of questions related to settings files name, go with default options by typing enter. When terminal ask you about which language you would like to use, either JavaScript or TypeScript, I will choose JavaScript. And continue with default settings by pressing enter key.</p><p>The terminal will ask you now which emulators you want to run, I picked Firestore and Functions, by pressing on Space key to select, when you select all options that you want, click on enter key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUz6_fWGZypbZWGet40BFA.png" /></figure><p>It will ask you about port numbers, as always go with default options unless you want to change it for a specific reason.</p><p>Then it will ask you if you want to download emulators, type Y then press enter. It will download emulator and finalize set-up, when it’s complete it show complete message as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWd6f0Vr5ZVaiC7RcDpgBA.png" /></figure><p>To run emulator, type in terminal</p><pre>firebase emulators:start</pre><p>If everything is good, your terminal should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sE66KbTcSv3WoJro23eRjA.png" /></figure><p>don’t close your terminal, leave it.</p><p>Now in new browser open <a href="http://localhost:4000/">http://localhost:4000</a> -or whatever it shows in your terminal- you will see emulator UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNWKa-6xSY7_UFF0x8MLYA.png" /></figure><p>from emulator UI, you can see each service status in your local machine, in above screenshot, you can see that both Firestore emulator and functions emulator both are enabled. Also, you can access each service locally by either click on service box or from navigation menu.</p><p>when you click on Firetsore, you will see this page, from here you can create collections/documents either manually or using Firebase functions which I will explain it later in this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOQIlnWAQCmzNf5wVxxhpw.png" /></figure><p>and for Firebase functions in emulator you can only see logs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvra3rhbtNSTWXjQZGKdKQ.png" /></figure><h3>Firebase Firestore vs Firebase Realtime Database</h3><p>*under progress</p><h3>Firebase functions</h3><p>*under progress</p><h3>Simple Firebase function CRUD</h3><p>*under progress</p><h3>Deploy Firebase function</h3><p>*under progress</p><p>Ok, I think that’s all</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F9o59Pga7BWlDrzWhhh%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F9o59Pga7BWlDrzWhhh%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F9o59Pga7BWlDrzWhhh%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/17addc7f64a811043cf00543bbef06db/href">https://medium.com/media/17addc7f64a811043cf00543bbef06db/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef74e0002344" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asma QuickStart guide: Say hi to AWS Serverless Developer Portal]]></title>
            <link>https://asmathewizard.medium.com/asma-quickstart-guide-say-hi-to-aws-serverless-developer-portal-52956bb8ba09?source=rss-2a18c2aab510------2</link>
            <guid isPermaLink="false">https://medium.com/p/52956bb8ba09</guid>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[sam]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <dc:creator><![CDATA[AsmaTheWizard]]></dc:creator>
            <pubDate>Sat, 06 Mar 2021 20:44:54 GMT</pubDate>
            <atom:updated>2021-03-07T06:18:26.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klvttlMc6JFMqSKKpgOqYQ.jpeg" /><figcaption>Image by <a href="http://rawpixel.com/">rawpixel.com</a></figcaption></figure><p>In this post I will explain how to deploy AWS Serverless Develoer Portal only, so have fun :)</p><p>I highly recommend you to read my post about AWS CloudFormation first, <a href="https://asmathewizard.medium.com/asma-quickstart-guide-working-with-cloudformation-for-the-first-time-3f036afc1d4e">here</a></p><p><strong>What is Serverless Developer Portal?</strong></p><p>It is an open-source application to make your APIs available to others. It works with your API gateway. I think if it as front-door of your house.</p><blockquote>Note: I will call serverless developer portal as SDP for short</blockquote><h3>Deployment:</h3><p>You have two options to deploy SDP, which are:</p><ul><li>AWS Serverless Application Repository</li><li>Download the source code from AWS GitHub and deploy it using AWS CLI/ SAM CLI</li></ul><p>Before exploring two options in detail, I want to cover some of SDP settings, in other words, SDP stack parameters.</p><h4>SDP Settings:</h4><p>We have 12 settings/parameters, only 3 of them are required, we can deploy stack with the default value for the rest.</p><blockquote>Note: you can change those settings after deployment, through CloudFormation stack page</blockquote><ul><li><strong>ArtifactsS3BucketName </strong>[required]<strong>: </strong>CloudFormation will auto-generate private S3 bucket to store metadata. You must follow S3 bucket names rules otherwise, you will have a lot of confusing errors</li><li><strong>CognitoDomainNameOrPrefix </strong>[required]<strong>: </strong>you can put any name here, it will be used with Cognito UI for sing-up and sing-in page, for example, I put “asma” as value, the start of URL for sing-up and the sing-in page would be like this https://asma.auth.us-east-1.amazoncognito.com/login?</li><li><strong>CognitoIdentityPoolName </strong>[optional]: CloudFormation will create Cognito identity pool, default name is <strong>DevPortalIdentityPool</strong></li><li><strong>CustomDomainNameAcmCertArn </strong>[optional]: if you will use a domain name with an ACM certificate, you should provide ACM certificate ARN. If you leave it empty, SDP will be generated without a custom domain name</li><li><strong>DevPortalAdminEmail </strong>[optional]: if you put an email address here, SDP will show “Got an opinion? button for customers to send their feedback</li><li><strong>DevPortalFeedbackTableName </strong>[optional]: if we want to use DevPortalAdminEmail to receive feedback<strong>, </strong>CloudFormation will create for us DynamoDB table to store feedback. The default table name is -if we provide an email address- is DevPortalFeedback</li><li><strong>DevPortalCustomersTableName </strong>[optional]: CloudFormation will create for us DynamoDB table to store customer accounts. The default table name is DevPortalCustomers</li><li><strong>DevPortalSiteS3BucketName</strong> [required]: CloudFormation will auto-generate private S3 bucket to store web application code. You must follow S3 bucket names rules otherwise, you will have a lot of confusing errors</li><li><strong>MarketplaceSubscriptionTopicProductCode </strong>[optional]: useless unless we want to use AWS marketplace integration</li><li><strong>StaticAssetRebuildMode </strong>[optional]: it’s dangerous, so don’t touch it :) go with the default and you will be fine!</li><li><strong>StaticAssetRebuildToken </strong>[optional]: if you want to rebuild SDP site static assets, use can use a timestamp</li><li><strong>UseRoute53Nameservers </strong>[optional]: when we set it to true, that means we will provide our own name server hosting. The default value is false</li></ul><blockquote>you must check S3 Bucket naming rules <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html">here</a></blockquote><p>That was looong and boring, now back to the fun part!</p><h4><strong><em>First option: AWS Serverless Application Repository</em></strong></h4><p>You can have your SDP up and running in no time with only two clicks! BUT, this way you will not be able to either customize the UI of SDP or functions if you want.</p><p>1- go to api-gateway-dev-portal page in AWS repository <a href="https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverlessrepo:us-east-1:563878140293:applications~api-gateway-dev-portal">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jfxg-pq_mWPrN2KqebT01A.png" /></figure><p>2- click on Deploy button</p><p>3- it will redirect you to your AWS account to log in, so log-in</p><p>4- lambda function page will be open with details for our api-gatewat-dev-portal as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wStB8ggs_d7fpFr9Vi8eXg.png" /></figure><p>5- you can check template, permission, and stack information from this page and most importantly we will configure SDP settings here! in the Application settings section, so go down a little bit</p><p>6- Now we need to fill in the required settings as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTNfc7wWkDGf4R9vZQeFlw.png" /></figure><ul><li><strong>Application name:</strong> is the stack name, and keep it short, otherwise, you will run into a strange error! so remember KEEP IT SHOOORT</li><li><strong>AccountRegistrationMode:</strong> you can either use “open” or “invite” mode, I prefer the latter as I don’t want anyone to have access to SDP</li><li><strong>ArtifactsS3BucketName: </strong>I explained it above, here I entered “asmamusicartifacts3”</li><li><strong>CognitoDomainNameOrPrefix:</strong> I explained it above, here I entered “rock”</li><li><strong>DevPortalSiteS3BucketName</strong>: I explained it above, here I entered “asmadev2”</li></ul><p>7- check “I acknowledge that this app creates custom IAM roles and resource policies.”</p><p>8- click on Deploy button</p><p>9- WAIT and WAIT</p><p>now CloudFormation will do its magic and will spin-off everything for us. You can check deployment status from the CloudFormation page.</p><h4>Second option: Download the source from AWS GitHub and deploy it using AWS CLI/ SAM CLI</h4><p>You need to deploy manually it may be a little bit chaotic at first, BUT you can fully customize UI and functions if you want.</p><p><strong>What is SAM?</strong></p><p>SAM is framework from AWS team, I like to think about it as sugarcoatd AWS CLI for CloudFormation. It uses CloudFormation template but with little bit different I will not cover it here as it’s not in the scope of the post :)</p><p><strong>prerequisites:</strong></p><ul><li>AWS CLI installed</li><li>SAM CLI installed</li><li>private S3 bucket to upload zipped Lambda functions and AWS SAM template</li><li>configure your AWS CLI by running</li></ul><pre>aws configure</pre><p>then enter your AWS Access Key ID and AWS Secret Access Key</p><blockquote>Note: for this option, we will create one S3 bucket and CloudFormation will create two S3 bucket as mentioned in SDP settings</blockquote><p>1- go to AWS GitHub and clone aws-api-gateway-developer-portal to your local machine</p><pre>git clone <a href="https://github.com/awslabs/aws-api-gateway-developer-portal.git">https://github.com/awslabs/aws-api-gateway-developer-portal.git</a></pre><p>2- go to project root folder</p><p>3- run below command. Don’t forgot to replace YOUR_BUCKET_NAME with your actual s3 bucket name :)</p><pre>sam package --template-file ./cloudformation/template.yaml \<br>    --output-template-file ./cloudformation/packaged.yaml \<br>    --s3-bucket YOUR_BUCKET_NAME</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQXL1tLdLQphADXcsF8rTg.png" /></figure><p>sam package will upload your zipped Lambda functions to your S3 bucket</p><blockquote>Any sam deployment consists of 3 steps, sam build, sam package, then sam deploy. If you make any change to source code, you need to run sam build first</blockquote><p>4- deploy template by running</p><pre>sam deploy --template-file ./cloudformation/packaged.yaml \<br>    --s3-bucket YOUR_BUCKET_NAME \<br>    --stack-name &quot;YOUR_STACK_NAME&quot; \<br>    --capabilities CAPABILITY_NAMED_IAM \<br>    --parameter-overrides CognitoDomainNameOrPrefix=&quot;YOUR_COGNITO_DOMAIN_NAME_OR_PREFIX&quot; DevPortalSiteS3BucketName=&quot;YOUR_S3_BUCKET_NAME_FOR_DEV_PORTAL&quot; ArtifactsS3BucketName=&quot;YOUR_S3_BUCKET_NAME_FOR_ARTIFACTS&quot;</pre><ul><li><strong>YOUR_BUCKET_NAME:</strong> name of your S3 bucket that you used to upload zipped Lambda functionsto, now we will use it again to upload sam template</li><li><strong>YOUR_STACK_NAME: </strong>you can name your stack/application anything but remember to keep it SHORT and this time follow S3 bucket name rules because we will use it for naming two S3 buckets</li><li><strong>capabilities CAPABILITY_NAMED_IAM: </strong>remember checkbox for agreement in first option? yeah it this :)</li><li><strong>parameter-overrides</strong>: we will set the 3 reuiried SDP settings here, DevPortalSiteS3BucketName, CognitoDomainNameOrPrefix and ArtifactsS3BucketName.</li></ul><blockquote>Note: For DevPortalSiteS3BucketName and ArtifactsS3BucketName both of their name should start with YOUR_STACK_NAME-S3BucketName</blockquote><p>my command will be like this</p><pre>sam deploy --template-file ./cloudformation/packaged.yaml \<br>    --s3-bucket asmasdp2 \<br>    --stack-name &quot;asma2rock-dev-portal&quot; \<br>    --capabilities CAPABILITY_NAMED_IAM \<br>    --parameter-overrides CognitoDomainNameOrPrefix=&quot;rock2ui&quot; DevPortalSiteS3BucketName=&quot;asma2rock-dev-portal-static-assets&quot; ArtifactsS3BucketName=&quot;asma2rock-dev-portal-artifacts&quot;</pre><blockquote>Note: for parameter-overrides, do not leave space before and after equal sign</blockquote><p>your terminal will be show similar output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7broBsxx-nLieJ4kSQ7meA.png" /></figure><p>again, WAIT and WAIT :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jmfk7GUQFFOGcWGBkabaew.png" /><figcaption>DONE!</figcaption></figure><p>Outupt in terminal will show us URL for our developer portal.</p><h3>Access Developer Portal:</h3><p>You can use SDP admin section to manage your users, invite them, delete them, and check APIs scubscriptions.</p><p>After deploying SDP in either way -first option or second option- you can get URL for SDP by going to CloudFormation page, then open stack, and go to output tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_B-Wcf_NpQtnocIlTOWTg.png" /></figure><p>If I open <a href="https://d10y1g1k0oc116.cloudfront.net/">https://d10y1g1k0oc116.cloudfront.net/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehlP0PUhb2J1q1cTV8gh3w.png" /></figure><h3>Create Admin User for SDP:</h3><p>1- go to SDP webpage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehlP0PUhb2J1q1cTV8gh3w.png" /></figure><p>2- click on Reigester</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBUSUNoi0ixTUdDql_Lecg.png" /></figure><p>3- after reigtesrtaion, you will receive OTP in your email</p><p>4-if you successfully reigesterd, SDP will be like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iM2IMqDI0bMnphNKI2gRfg.png" /></figure><p>5- in your was account, go to Cognito page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hgT3bQPR9jH03vITywr8Q.png" /></figure><p>6- click on Manage User Pools button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycFS6I7LbEmGktNtdvmoMQ.png" /></figure><p>7-click on your application pool, in our case, it is DevPortalIdentityPool</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPUD7CYmAt23TU_9mDMmDQ.png" /></figure><p>8- click on Users and groups from left navigation menu</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZNVEKDPqs0uQgf-byN9nw.png" /></figure><p>9- click on username that you want to promote to be admin, yeah we only have one right now :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2Yi9L9atkJuL5yz_XgSXQ.png" /></figure><p>10- click on Add to group button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mtWlczFM_WNBtt2PKxc9A.png" /></figure><p>11-select admin group from drop-down list and click on Add to group button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qlPZ-VCd5QGeYBROh7rGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xp6xewugcoKaaLAytl1_Tw.png" /></figure><p>12- go back to SDP webpage, singout then log-in, you will find extra menu in top navigation which say “Admin Portal”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pExAScOLLlMV1sXpCxvoqw.png" /></figure><p>It was a long long day … next time I will cover how to configure API gateway to expose endpoints in SDP 0:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26gssklrvo2gTnlD2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26gssklrvo2gTnlD2%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F26gssklrvo2gTnlD2%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/df3a25a59b957d3ee441babf4b9fb921/href">https://medium.com/media/df3a25a59b957d3ee441babf4b9fb921/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52956bb8ba09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asma QuickStart guide: Working with CloudFormation for the first time]]></title>
            <link>https://asmathewizard.medium.com/asma-quickstart-guide-working-with-cloudformation-for-the-first-time-3f036afc1d4e?source=rss-2a18c2aab510------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f036afc1d4e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[cloudformation]]></category>
            <dc:creator><![CDATA[AsmaTheWizard]]></dc:creator>
            <pubDate>Fri, 05 Mar 2021 18:02:16 GMT</pubDate>
            <atom:updated>2021-03-06T20:43:13.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lG9CeEl1geaiCCKeVqNbxQ.jpeg" /><figcaption>Image by <a href="http://rawpixel.com/">rawpixel.com</a></figcaption></figure><p>I was working on a CloudFormation task related to my work during the weekend and I thought to myself “Why not?” so here is the QuickStart guide for anyone working with CloudFormation for the first time. I won’t get deep into details.</p><h4>The post will cover :</h4><ul><li>What is CloudFormation?</li><li>Create CloudFormation Stack</li><li>Deploy CloudFormation Stack</li><li>Update CloudFormation Stack</li><li>Delete CloudFormation Stack</li></ul><h3>What is CloudFormation ?</h3><p>It is one of AWS services, it basically helps us to define infrastructure as code then deploy, manage and delete in simple steps. CloudFormation made up of stacks, each stack consisting of one or more resources defined as code in a template file.</p><p>CloudFormation -&gt; made of stacks, each stack -&gt; made of a template</p><p>For writing templates, you can use either JSON or YAML.</p><p>Each CloudFormation template has 9 parts/sections, 8 of them are optional and one is mandatory, sections are:</p><ul><li><strong>AWSTemaplateFormatVersion</strong> [optional]: AWS uses it to prove the template if in a future template format change. I think of it as AWS template versioning</li><li><strong>Description</strong> [optional]: description for template. Note, if you add it, it should come right after AWSTemplateFormatVersion</li><li><strong>Metadata </strong>[optional]: it has many uses such as specifying how information in the console will be shown when you deploy the template. Note, all of the resources in the template can use the data mentioned here.</li><li><strong>Parameters </strong>[optional]: we can configure variables so the template will ask the user to enter the value. Also, we can set a default value. For example, the size of the instance</li><li><strong>Mapping </strong>[optional]: I think of it as “Flag” values of template, for example, we can set environment types such as Dev, Staging, or Production, and based on environment type, we map certain resources to spin-off.</li><li><strong>Conditions</strong> [optional]: It is “IF” statements of template, based on number of values we set here, the template will know if we want to spin off certain resources or not</li><li><strong>Transform</strong> [optional]: it is used for serverless application</li><li><strong>Resources</strong> [Required]: it has logical AWS resource we want to create</li><li><strong>Outputs</strong> [optional]: if we want to get value/output after the stack is completely deployed, such as URL of the resource.</li></ul><p>The stack will take logical resources we create in the Resources section and create physical resources in AWS</p><blockquote>You can create a template with only the Resources section, but personally, I like to add AWSTemplateFormatVersion and Description sections as well.</blockquote><h3>Create CloudFormation Stack:</h3><p>We will create S3 bucket to store images of our favorite bands. First, we will create a logical resource of type S3 and we can name it anything, for example, I will name my logical resource “Metallica” :)</p><p>Our CloudFormation template should be like this</p><pre>AWSTemplateFormatVersion: &quot;2010-09-09&quot;</pre><pre>Description:<br>  this template create S3 bucket for my fav band</pre><pre>Resources:<br>  Metallica:<br>    Type: &quot;AWS::S3::Bucket&quot;</pre><p>Note: logical name of a resource doesn’t reflect its physical name in AWS. So till this point, our S3 bucket name is not “Metallica”</p><p><em>Why would we not name physical resources?</em></p><p>It is recommended to let AWS CloudFormation do that for us instead of us hard-coded resources name, this way our template is reusable.</p><h3>Deploy CloudFormation Stack:</h3><p>To deploy CloudFormation template, you have a couple of options, I will demonstrate two of them which are: using AWS web console or AWS CLI.</p><p><strong>AWS Web Console:</strong></p><p>The simplest deployment option is using web console.</p><p>1- Log in to your AWS account</p><p>2- Search CloudFormation in the search bar and click on it</p><p>3- CloudFormation page will be open</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5L0AG2vnfdm5JzSYKhp-A.png" /><figcaption>CloudFormation page</figcaption></figure><p>4- Click on Create stack button at the top left corner (choose “with new resources” option)</p><p>5- Create stack page will show many options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30wEOsFO6NZCjEb2pe6WQQ.png" /></figure><ul><li>Template is ready: we will choose this option as we already created a template file</li><li>Use a sample template: AWS provides a couple of ready-to-use samples such as Ruby on Rails stack, WordPress blog stack ..etc</li><li>Create template in Designer: AWS provides CloudFormation Designer service to graphically create your template</li></ul><p>6- Choose “Template is ready”</p><p>7- Choose “Upload a template file” option and upload template file that we created</p><p>8- Click Next</p><p>9- Specify stack details page will open, enter a name for the stack. Note: your stack name should be unique, you cannot have two stacks projects with the same name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7VxGAkwqPb-bZ5Ho2YsH2Q.png" /></figure><p>10- Configure stack options page will show, it has advanced settings for the stack, at this point, we don’t need to change anything, just click Next</p><p>11- Review page will show, click Create stack button</p><p>12- WAIT patiently</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMbYp8zUPcYp15E_1HS-hg.png" /></figure><p>13- after a couple of seconds or minutes -depending on your template specification- your resource is created and ready</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqFXtCUpH0JD0PP1t8AXFw.png" /></figure><p>you can notice Logical ID column from the above image, if you want to check Physical ID, go to the Resources tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzx5fh1WerrIA3EBT-2VOA.png" /></figure><p>If you go to S3 buckets page, you will find our new S3 bucket</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mctkvU-Y5uM3G1CIZ8oY2Q.png" /></figure><p>CloudFormation will use stack name-resource logical id-random string generated to create resource physical ID</p><p><strong>AWS CLI:</strong></p><p>prerequisites:</p><ul><li>you should have AWS CLI installed</li><li>you should configure your AWS account, by running</li></ul><pre>aws configure</pre><p>then enter your AWS Access Key ID and AWS Secret Access Key</p><p>All you have to do run the below command in a folder that has template.yaml. You can name your stack anything, I named mine “Rock-Bands-2”</p><pre>aws cloudformation deploy --template-file template.yaml --stack-name Rock-Bands-2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dT0Vs7xSrbrf_rM_tnjvgA.png" /></figure><p>and <strong>Voila</strong> your stack is deployed and your resource is created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wslN7hSujirNNnOhhdnlCQ.png" /></figure><h3>Update CloudFormation Stack</h3><p>for the update, we have 3 cases, either we want:</p><ul><li>add new resource</li><li>remove existing resource</li><li>update existing resource configuration</li></ul><p><strong>Add New Resource:</strong></p><p>adding a new resource is almost the same process as creating a new one, you need to modify the template file, then upload it. Here, I will create a new S3 bucket and name it “LedZeppelin”</p><pre>AWSTemplateFormatVersion: &quot;2010-09-09&quot;</pre><pre>Description:<br>  this template create S3 bucket for my fav band</pre><pre>Resources:<br>  Metallica:<br>    Type: &quot;AWS::S3::Bucket&quot;<br>    <br>  LedZeppelin:<br>    Type: &quot;AWS::S3::Bucket&quot;</pre><p>1- Go to CloudFormation page, choose the stack you want to update then click on Update button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nN_L1CMaVUCkliHuSYQjVg.png" /></figure><p>2- update stack page will open, choose “Replace current template” option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYAN-2CVoujt83BVs2xBQA.png" /></figure><p>3- choose “Upload a template file” and upload file then click Next</p><p>4- Specify stack details page will open, click Next</p><p>5- Configure stack options page will open, click Next</p><p>6- Review page will open, go to the bottom of the page, you will see “Change set preview” double-check your change then click “Update stack” button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZByIbnYXE33IEbr5wMSyw.png" /></figure><p>7- wait a little while AWS create the resource for you and update stack status</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9OioVIygGMK-7K-eqRqrw.png" /></figure><p><strong>Remove Existing Resource:</strong></p><p>You can remove any resource from your stack by simply edit template file and remove that resource then update CloudFormation. For example, I want to remove LedZeppelin resource, so template file will be like this</p><pre>AWSTemplateFormatVersion: &quot;2010-09-09&quot;</pre><pre>Description:<br>  this template create S3 bucket for my fav band</pre><pre>Resources:<br>  Metallica:<br>    Type: &quot;AWS::S3::Bucket&quot;</pre><p><strong>update existing resource configuration:</strong></p><p>To update an existing resource configuration, you need to modify it in the template then upload it as mentioned in Add New Resource section.</p><pre>AWSTemplateFormatVersion: &quot;2010-09-09&quot;</pre><pre>Description:<br>  this template create S3 bucket for my fav band</pre><pre>Resources:<br>  Metallica:<br>    Type: &quot;AWS::S3::Bucket&quot;<br>    Properties:<br>      BucketName: MetallicaAlbums</pre><pre>LedZeppelin:<br>    Type: &quot;AWS::S3::Bucket&quot;</pre><p>In the template above, I wanted to specify a physical name for the bucket resource instead of letting AWS generate that for me. We can do that by setting BucketName key. Now, we need to deploy the template as Add New Resource section.</p><p>Note: when we provide BucketName for already existed bucket resource, AWS CloudFormation will delete the old bucket completely and create a new one! so be careful</p><h3>Delete CloudFormation Stack:</h3><p>When you delete CloudFormation, it will delete all of its resources and configuration.</p><p>1-Choose stack to delete then click on the Delete button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZ1mqEGdSmHrq4W5d9F8xg.png" /></figure><p>2- pop-up confirmation will show, click on Delete stack button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0c2gOmEhaxmKi5JBTG2tw.png" /></figure><p>3- and wait. That’s it</p><p>Ok, that was my QuickStart guide for AWS CloudFormation. I hope it would help someone</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl1J9xQS40rDsHuC3K%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl1J9xQS40rDsHuC3K%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl1J9xQS40rDsHuC3K%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/8120bcf48977cd9796033a458ea6fc26/href">https://medium.com/media/8120bcf48977cd9796033a458ea6fc26/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f036afc1d4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>