<?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 Sau-rav Adhikari on Medium]]></title>
        <description><![CDATA[Stories by Sau-rav Adhikari on Medium]]></description>
        <link>https://medium.com/@saurav-adhikari?source=rss-2db942015095------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ttnAWJXBZWp6DDGEvii1NA.jpeg</url>
            <title>Stories by Sau-rav Adhikari on Medium</title>
            <link>https://medium.com/@saurav-adhikari?source=rss-2db942015095------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:57:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saurav-adhikari/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[Multi-Project(Account) service account in GCP]]></title>
            <link>https://articles.wesionary.team/multi-project-account-service-account-in-gcp-ba8f8821347e?source=rss-2db942015095------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba8f8821347e</guid>
            <category><![CDATA[identity-management]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Sau-rav Adhikari]]></dc:creator>
            <pubDate>Wed, 27 Jul 2022 05:22:22 GMT</pubDate>
            <atom:updated>2022-07-27T05:22:22.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PhFgw8ZHZ5XiETUu.png" /></figure><p>Do you use multiple projects in <strong>Google Cloud Platform(GCP) </strong>for different environments ( dev, staging, UAT, production)? If yes, sometimes you might find yourself in situations where one service needs to communicate with other services in different accounts/projects.</p><p>In this article, we will explore how we can utilize service accounts in GCP to access multiple projects; within the same or different accounts and organizations.</p><h3>Problem Statement</h3><p>( This is just an example, no need to complicate stuff like this 😝)</p><p>We have two projects where we are currently deploying our API, Project-Staging and Project-Release for our staging and release environments.</p><p>Let&#39;s say they share the same Firebase Authentication. So, in Project-Staging we will use the Firebase Admin SDK service account of Project-Release.</p><p>Thus far, it’s all fun because everything is working all right.</p><p>But what if your API needs to use Cloud Storage to store some files?<br>Well, since the service account from Project-Release doesn’t have any permissions, it won’t be able to do so; suddenly errors, errors, and errors!!!</p><h3>Getting started (Creating Service Account in GCP)</h3><p>Let’s start by creating a service account in Project-Release with the necessary permissions.</p><blockquote>** If you’re serious about above example you might already have something like this firebase-adminsdk-22@project-release.iam.gserviceaccount.com . <br>You can use the same service account or create a new one.</blockquote><p><strong>Step 1: </strong>Go to<strong> </strong><strong>IAM and Admin </strong>and click on <strong>Service Accounts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfgWb23rT7v5IgApnyuPLw.png" /></figure><p><strong>Step 2: </strong>Click on <strong>+Create Service Account</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCOQQJ-1e6NHQMOaItLXtg.png" /></figure><p><strong>Step 3: </strong>Fill in the service account details as per your needs. Then press <strong>CREATE AND CONTINUE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eA82JYyCBLEGcEcwofiAUw.jpeg" /></figure><p><strong>Step 4:</strong> Grant the required permissions in <strong>Project-release </strong>and then <strong>CONTINUE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLXAJM33t7MGxwZvyauyOg.png" /></figure><p><strong>Step 5:(Optional) </strong>If you want to grant specific users access to this service account, you can do so. Finally press <strong>DONE</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYxZJeupOC7gekQDLXbUVQ.png" /></figure><p><strong>Step 6: </strong>You should be able to see your service account in the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12CWMC4_16zuIzovJ2wjJA.jpeg" /></figure><h3>Granting access to other projects</h3><p>Once we have a working service account configured, we can go to Project-Staging<br><strong>Step 1:</strong> Navigate to <strong>IAM and Admin</strong>again, then click on <strong>IAM </strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ti74TMFCX1X-kvRePLxDg.png" /></figure><p><strong>Step 2: </strong>Click on <strong>+ADD</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAv2RwN18HOyOk62v7-4JA.png" /></figure><p><strong>Step 3: </strong>In the New Principals section add the email of the service account we created in Project-Release . Then, assign the necessary roles required for the service account in Project-Stagingas per your need.</p><blockquote>* Notice how we are assigning the service account from a project roles in a different project.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rp5zjFZngoxkGkY62v8aJQ.jpeg" /></figure><p><strong>Step 4: </strong>Press on <strong>SAVE</strong> . Then you should be able to see the service account listed in the <strong>IAM</strong> list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dngr3_qgzjP2ObZVP_hgtA.jpeg" /></figure><p>Now the service account you created in one project can access services in both projects.</p><p>Thank you for reading this article. Keep Learning 📝</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba8f8821347e" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/multi-project-account-service-account-in-gcp-ba8f8821347e">Multi-Project(Account) service account in GCP</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate adding Github environments/repository secrets]]></title>
            <link>https://articles.wesionary.team/automate-adding-github-environments-repository-secrets-64de7d1235e7?source=rss-2db942015095------2</link>
            <guid isPermaLink="false">https://medium.com/p/64de7d1235e7</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[github-api]]></category>
            <dc:creator><![CDATA[Sau-rav Adhikari]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 03:00:13 GMT</pubDate>
            <atom:updated>2022-02-22T03:00:13.189Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automate Adding Github Environments/Repository Secrets</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x-PjdlBp2J1-zOmF.png" /></figure><p>In this article, we will be exploring how we can automate adding Environments/Repository secrets to GitHub using <a href="https://github.com/fastai/ghapi">fastai/ghapi</a> (Python). You can use any other language or library that best meets your needs.</p><p>List of all available <a href="https://docs.github.com/en/rest/overview/libraries">libraries</a>.</p><blockquote><strong>We are working with </strong><strong>secrets 🤫 , if it ever got out, the world could turn upside down depending on what you’re storing. Be sure to protect it as if your life depends on it.</strong></blockquote><p>If you want to jump right in and test out the code first you can refer to my repository.</p><p><a href="https://github.com/n3rdkid/medium-github-secrets">GitHub - n3rdkid/medium-github-secrets: Secrets; for things that should never get out</a></p><h3>Authentication</h3><p>Let’s start by generating a Personal Access Token (PAT), which we will use to authenticate to GitHub. In GitHub, click on your avatar and go to “<strong>Settings</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*qJuVagdlJHAxOHB8jKL95g.png" /></figure><p>After that navigate to “<strong>Developer Settings</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*NEzb-_QLxfWF2sYpmY5Wtw.png" /></figure><p>Inside “<strong>Developer setting</strong>” click on “<strong>Generate new token”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAJ1EG1tFiYy1I9ItPic0Q.png" /></figure><p>Add a “<strong>Note</strong>” update “<strong>Expiration</strong>” and set therepo scope as per your need. While doing this we should provide the least scope possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgTKUVhoeJcSssI8sHctmQ.png" /></figure><p>For a <strong>public</strong> repository, we can just set public_repo scope as shown above.<br>For a <strong>private</strong> repository, we need to provide repo scope Full control of private repositories</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*UknkLaUf2KR8Jv37-tjRdQ.png" /></figure><p>After defining the scope for the access token “<strong>Generate new token</strong>” and store it somewhere safe 🔒.</p><h3>Configuring the playground</h3><h4>Create a virtual environment</h4><p>First, we will create a virtual environment called venv. Go to your terminal and type the following command. Depending upon your installation use python or python3.</p><pre>$ python3 -m venv venv</pre><h4>Activate the virtual environment</h4><p>To activate the virtual environment we just created, go to your terminal and type the following command.</p><pre>$ source ./venv/bin/activate</pre><p>After running the command you should see the name of your virtual environment in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*UeIgo8CwxgLMQb867sZVPw.png" /></figure><h4>Installing dependencies</h4><p>I have already created a <a href="https://github.com/n3rdkid/medium-github-secrets/blob/main/requirements.txt">requirements.txt</a>, so you can just install all the required dependencies from there. In the terminal type the following command.</p><pre>$ pip3 install -r requirements.txt</pre><h4>Creating env files</h4><p>Finally, let’s create env files which we will use to populate the secrets in GitHub.</p><p>Create a git.env where we will store our GitHub Personal Access Token (PAT) and repository information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0176c0bcfccc65631cfaa776cec7bf50/href">https://medium.com/media/0176c0bcfccc65631cfaa776cec7bf50/href</a></iframe><p>We will use repo.env for creating Repository Secrets. Use this to store secrets that are common to all of your environments such as notification webhooks, alert channels, etc.</p><p>We will use dev.env , prod.env for Development and Production, you can add as many files as per your need to create Environment Secrets.They will be used to store secrets that differ according to the environment they run on.</p><pre>KEY=value<br>KEY_1=value</pre><p>Make sure the secrets in each of the .env file appears in a key-valuepair separated by = .</p><p>Now, let’s start with writing the actual script to add/update secrets.</p><p>By now, your folder structure should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*_E-5uKIusrBo9zNnXvLuxA.png" /></figure><blockquote>Be sure to <strong>ignore</strong> all your .env</blockquote><h3>Scripting</h3><p>Create a main.py file. This is where we will write all the code for this simple script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/680acf58d73cd3848279b42c70ca514c/href">https://medium.com/media/680acf58d73cd3848279b42c70ca514c/href</a></iframe><p>[9–13]: We load our git.env using dotenv.</p><p>[15]: We initialize GhApi using our PAT and repository information.</p><p>[17–23]: We define a function that uses pynacl to encrypt our secrets as suggested by GitHub ( <a href="http://Example encrypting a secret using Python">Example encrypting a secret using Python</a>).</p><p>[27–31]: We define a function that reads environment secrets from the env file path provided and returns a dictionary.</p><p>We use context manager to open the file in read mode and iterate through each line replacing \nand splitting them at =.</p><p>[32–41]: Select the .env path as per our ENVRIONMENT and read our env data.</p><p>[43]: Here we determine if we need to create envrionment or repository secrets and carry out operations accordingly.</p><p><strong>If we are trying to create </strong><strong>envrionment secrets.</strong><br>[45]: First, we fetch the repository id.</p><p>[47]: Create or update the environment.</p><p>[51]: Get an environment public key that will be used to encrypt our secrets.</p><p>[52–56]: Iterate over each secret, encrypt its value, and then create_or_update the environment secret.</p><p><strong>If we are trying to create </strong><strong>repository secrets.</strong></p><p>[59]: Get a repository public key that will be used to encrypt our secrets.</p><p>[60–64]: Iterate over each secret, encrypt its value, and then create_or_update the environment secret.</p><h3>Run the Script</h3><p>Finally, now we can run the script and store our secrets.</p><pre>$ python main.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9J6gf7ndCBPLHI1V3CO5g.png" /></figure><p>You should get something similar to what is shown above, depending upon what secrets you have stored in your .env file. If you go over to GitHub “<strong>Action/Secrets</strong>” you should see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHSc-F5yTEfjbLHOpFRB5w.png" /></figure><p>Congratulations 🎉! Now you can run a script, kick back and relax. 🧘</p><h3>Taking it to next level</h3><p>Let’s be honest, going through the above steps every time manually is not what we want to do. We want to push a button and 💥!</p><blockquote><em>perfectly balanced as all things should be</em></blockquote><p>Let’s also write a small shell script “<strong>run.sh</strong>” to do everything with a push of a few buttons.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d5973635c4fc260e3d5c867670c758c/href">https://medium.com/media/3d5973635c4fc260e3d5c867670c758c/href</a></iframe><p>Make the script executable.</p><pre>$ chmod +x ./run.sh</pre><p>And now execute the script.</p><pre>$ ./run.sh</pre><p>Thank you for reading this article. We still have a long way to go for fully automating our secret management. So, where to next? <br>Here’s a fun challenge.</p><h4><strong>Sync secrets from your env</strong></h4><p>Let’s say you remove secrets from .env the changes that should be reflected on GitHub when you run the script next time. Or say, someone added new secrets in GitHub directly that don’t exist in your .env file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64de7d1235e7" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/automate-adding-github-environments-repository-secrets-64de7d1235e7">Automate adding Github environments/repository secrets</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Provision AWS resources using Terraform — IaC]]></title>
            <link>https://articles.wesionary.team/provision-aws-resources-using-terraform-iac-a263dca48059?source=rss-2db942015095------2</link>
            <guid isPermaLink="false">https://medium.com/p/a263dca48059</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sau-rav Adhikari]]></dc:creator>
            <pubDate>Thu, 19 Aug 2021 08:31:25 GMT</pubDate>
            <atom:updated>2021-08-19T08:31:25.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>Provision AWS resources using Terraform — IaC</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_gNF1DzEubvaQJEV.png" /><figcaption>Image Source: HashiCrop</figcaption></figure><p>Hello everyone, in our DevOps journey, we will now actually provision resources from a Cloud provider where we can deploy our applications.</p><p>In this article, we will be exploring how we can provision AWS resources for our application using Terraform. We will be creating anElastic Beanstalk application and an Elastic BeanStalk environment.</p><p>You can use the same architecture and patterns that you will see in this article and add any other resources that you require. To get started you do need to do some work.</p><p><strong>Prerequisites:</strong></p><ol><li>Setup an AWS Account</li><li>Generate AWS access keys (<a href="https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-your-credentials.html">Getting Your Credentials — AWS SDK for JavaScript</a> ) and setup AWS profile (<a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html">Named profiles — AWS Command Line Interface</a>)</li><li>Have a basic understanding of Terraform</li></ol><p>If you are new to Terraform you can check out my article on the fundamentals of Terraform.</p><p><a href="https://medium.com/wesionary-team/getting-started-with-terraform-for-aspiring-devops-engineer-99b413239bb">Getting started with Terraform — For aspiring DevOps Engineer</a></p><p>If you get stuck at any point or want a glimpse of what the final configurations look like, you can visit the following repo.</p><p><a href="https://github.com/n3rdkid/medium-terraform-aws">GitHub - n3rdkid/medium-terraform-aws: Demo repo for my Medium article</a></p><h3>1. Setup an S3 bucket to store Terraform state</h3><blockquote>Note : You can skip this step and use your local state as well.</blockquote><p>Before we get started, we will create a S3 bucket where we can store our Terraform state this will ensure that other individuals who collaborate with you on the project have a single source of truth for the infrastructure.</p><ul><li>Go to S3 dashboard and create a new bucket.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6pCsErxcKTzrIdiMy-U-w.png" /></figure><ul><li>You can configure the bucket as per your need, but I will go with the default configurations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oI7bP-np9NfbNzIlunE0Bg.png" /></figure><ul><li>After the bucket is successfully created, it will be available in the S3 Buckets dashboard.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_0aMRLb-1t1Yx8neygPag.png" /></figure><h3>2. Configuring the Terraform backend</h3><p>Backend in Terraform defines various configurations such as where our state snapshots are stored, where and how the operations are performed etc. Our backend configuration will look something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/225b153d2eaca72194baab4669731c90/href">https://medium.com/media/225b153d2eaca72194baab4669731c90/href</a></iframe><p>Here, I have specified the S3 bucket we created as the backend to store our state snapshot, along with the region and my AWS named profile. Be sure to replace them with your own region and named profile. Let’s also create a provider.tf to specify our provider.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fd7e189338052aa7b0243de7309da10/href">https://medium.com/media/5fd7e189338052aa7b0243de7309da10/href</a></iframe><h3>3. Creating modules</h3><p>Terraform has concepts of modules that allow us to re-use our configuration files. We will be modularizing our configuration files so that we can reduce the amount of configuration we have to write and maintain.</p><p>Each module has its own configuration file to provision some resources and input and output variables. Each of our modules will contain the following three files.</p><ul><li>terraform.tf → Contains all our input for the module ( You can name it any other name supported by Terraform, I will be adding variables.tf to .gitignore so I decided to go with this name)</li><li>main.tf → Contains our actual configuration for resources</li><li>outputs.tf → Contains output that will be exposed to other resources that will use this module</li></ul><h4>3.1 Creating the Elastic Beanstalk Application Module</h4><p>First, let’s start by creating the main.tf file inside modules/beanstalk_application folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96564ce106fdda0e73db56c9eff8fd15/href">https://medium.com/media/96564ce106fdda0e73db56c9eff8fd15/href</a></iframe><p>Here, we are creating Elastic Beanstalk Application, configuring its application version lifecycle to maintain a maximum of 3 versions, and to delete the source of version from the Elastic Beanstalk S3 bucket when the version is deleted.</p><p>To configure appversion_lifecycle in Terraform, we need to provide the service_role argument. So, we create an IAM role with permission for the Elastic Beanstalk.</p><blockquote>You can read more about this here : <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-servicerole.html">https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-servicerole.html</a></blockquote><p>You can completely skip the appversion_lifecyle if you don’t need it. In such a scenario the main.tf will look like this.</p><pre>resource &quot;aws_elastic_beanstalk_application&quot; &quot;beanstalk_app&quot; <br>{  <br>     name        = var.aws_elastic_beanstalk_application_name<br>     description = var.aws_elastic_beanstalk_application_description<br>}</pre><p>Now, let’s write a configuration file named terraform.tfthat will act as the input for our module. You can use input variables even where I have hard-coded my values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d08d114dc40cad066994796ac9d1703/href">https://medium.com/media/2d08d114dc40cad066994796ac9d1703/href</a></iframe><p>We will be taking just three inputs, the name of the Application and Description and one for the IAM role (You can add more inputs here if needed to configure the Beanstalk Application)</p><p>And finally for the outputs from our beanstalk_applicaiton module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fce21d5c3c1130014c922822abd1604/href">https://medium.com/media/7fce21d5c3c1130014c922822abd1604/href</a></iframe><blockquote>If you noticed, our output is the same value provided by input variable aws_elastic_beanstalk_application_name . We can output other values as well, I am doing this to create an implicit dependency later on.</blockquote><blockquote>However, you can also make use of depends_on to create an explicit dependency.</blockquote><p>We are now done with our beanstalk_application module.</p><h4>3.2 Creating the Elastic Beanstalk Environment Module</h4><p>We will be repeating the same steps for this module as well. Inside the folder modules/beanstalk_environment create our three files as below:</p><p>Our main.tf file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0e89cb67ed241bf20d26814f2d57182/href">https://medium.com/media/b0e89cb67ed241bf20d26814f2d57182/href</a></iframe><p>Here, we have specified the application in which the environment where it will be created and the name of the environment along with its solution stack and some settings to configure our environment instance as an example.</p><p>solution_stack_name: Select the platform; (<a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.nodejs">Visit here for solution stack reference</a>)</p><p>setting: Block contains additional configurations we can make to our environments. (<a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/elastic_beanstalk_environment">Read More about Settings</a>)</p><p>For inputs to this module our terraform.tf will be as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72b201b6b5ec5ef3102981b8327784ff/href">https://medium.com/media/72b201b6b5ec5ef3102981b8327784ff/href</a></iframe><p>We will output only the endpoint_url, using which we can access our application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1d4ae73134b363635f766820da5eb69/href">https://medium.com/media/b1d4ae73134b363635f766820da5eb69/href</a></iframe><p>Now we are done with creating our modules, now it’s time to use these modules to actually provision the required resources.</p><h3>4. Using the modules</h3><p>Now, let&#39;s get started by creating a main.tf file at the root working directory(./main.tf). This is the configuration file where we will actually define the architecture of our infrastructure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84c83b1a4562e0d3252c260cb873c21b/href">https://medium.com/media/84c83b1a4562e0d3252c260cb873c21b/href</a></iframe><p>As you can we, to use modules we use the module keyword and specify the source ; the path to our module. We also provide any input variables that we specified in the terraform.tf .</p><p>Here, For demonstration, I am creating an Elastic Beanstalk Application with Two Environment for DEV and PROD .</p><p>Let’s output the two endpoints to our respective environments as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08018daef078319172a17fdf4f0d21e3/href">https://medium.com/media/08018daef078319172a17fdf4f0d21e3/href</a></iframe><p>You can initialize the variables as per your need. For demonstration, I will be using a variables.tf</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65b754e4e07211510c448684799232e4/href">https://medium.com/media/65b754e4e07211510c448684799232e4/href</a></iframe><p>We are now all done. Let’s apply these configuration files.</p><h3>5. Applying the configuration files</h3><p>Let’s start by initializing the configuration directory and installing the provider plugins. Run terraform init from your root module.</p><pre>$ terraform init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqJWoDZ7ylEGW2jNbxd5YQ.png" /><figcaption>Initializing Terraform configuration directory</figcaption></figure><p>Let’s also run terraform plan to check out the action plan.</p><pre>$ terraform plan</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03QUCoEICIllQpxptxZ2_g.png" /><figcaption>Terraform plan</figcaption></figure><p>And finally, let’s apply our configuration files.</p><pre>$ terraform apply</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6orzJRUHpVs7_nChcLdI_Q.png" /></figure><p>After successful completion, you should get the Success message along with two endpoints to your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYG3j2KiSa0f3_MGw0KaNg.png" /></figure><p>If you visit the URL, you will see the default page for our environment.</p><p>Congratulations, You can now deploy your application manually or by using CI/CD pipelines to this infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsKBmBgY9p055miPQVVtOw.png" /></figure><p>If you want to look at more of Terraform with AWS check out my following Repo.</p><p><a href="https://github.com/n3rdkid/monorepo-nextjs-aws-beanstalk-terraform">GitHub - n3rdkid/monorepo-nextjs-aws-beanstalk-terraform: Deploying NextJS MonoRepo to AWS Beanstalk (Created using Terrform) using Github Actions</a></p><p>Thank you for reading my article, I look forward to your feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a263dca48059" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/provision-aws-resources-using-terraform-iac-a263dca48059">Provision AWS resources using Terraform — IaC</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Terraform — For aspiring DevOps Engineer]]></title>
            <link>https://articles.wesionary.team/getting-started-with-terraform-for-aspiring-devops-engineer-99b413239bb?source=rss-2db942015095------2</link>
            <guid isPermaLink="false">https://medium.com/p/99b413239bb</guid>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sau-rav Adhikari]]></dc:creator>
            <pubDate>Mon, 28 Jun 2021 10:06:55 GMT</pubDate>
            <atom:updated>2022-02-10T15:20:28.877Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting started with Terraform — For aspiring DevOps Engineer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s3rGmcBOil_nP-A8.png" /></figure><p>Hello aspiring DevOps Engineer, in this article we will be exploring <strong>Terraform</strong> one of the many <strong>Infrastructure as Code(IaC)</strong> tools out there.</p><p>In this article, we will be covering the fundamentals of working with Terraform. This article is for an <strong>absolute beginner </strong>who knows nothing about Terraform, this article doesn’t make use of any cloud providers but in the future, we will be working with cloud providers so be sure to grasp the concepts well.</p><h4>What to expect from this article?</h4><ol><li>HCL configuration files</li><li>Terraform Workflow (Creating, Updating and Destroying resources)</li><li>Resource attribute reference</li><li>Resource dependencies</li></ol><h3><strong>Let’s start with “What is IaC?”</strong></h3><p>IaC in the simplest term means managing our IT infrastructure(i.e. servers and other resources)using configuration files. We write configuration files that specify our infrastructure needs, which are then met by IaC tools by provisioning the required resources (such as compute instance, an EC2 instance, database instance, file, etc).</p><p>This helps to automate most of the things that we used to be done manually. IaC also helps to achieve a stable and predictable environment where we can deploy and run our applications.</p><p>For example, to host and deploy our applications to GCP or AWS, we need to provision an instance, which we create manually from the UI or using scripts.</p><p>On the other hand, with IaC, we would write a configuration file for such resources that will be provisioned by IaC tools. We can also test to make sure the infrastructure is configured just as we specified.</p><h3>What is Terraform?</h3><blockquote>Terraform is an open-source infrastructure as code software tool created by HashiCorp.</blockquote><p>Terraform helps us to build, change, and version infrastructure safely and efficiently in a declarative manner ( we only specify “<strong>what is expected” </strong>not <strong>“how to achieve it</strong>”). To achieve this, Terraform uses the HashiCorp Configuration Language (HCL) or optionally JSON configuration files.</p><h4><strong>Why use Terraform?</strong></h4><p>Let’s look at some benefits of using Terraform:</p><ol><li>It <strong>supports many cloud providers</strong> such as (AWS, GCP, Alibaba Cloud, etc) and <strong>even our local data centers</strong>. Thus, we can also use the same tool to manage our infrastructure across various providers.</li><li><strong>Automates infrastructure</strong> <strong>provisioning</strong> in a stable, repeatable, and predictable environment. We can use the same configuration file to create our dev, test, and production environments.</li><li>We can <strong>reduce costs</strong> by creating <strong>on-demand</strong> development and deployment environments. When we need a particular environment we just apply the configuration file and the resources are provisioned for our environment.</li><li>Finally, we can <strong>reduce time to provision </strong>resources since we don’t have to go to multiple pages/sites `Clicking on buttons`, such manual work not only takes time but can also be erroneous.</li></ol><h3>Getting started with Terraform</h3><blockquote>You can download and install Terraform by following this article by HashiCorp.</blockquote><blockquote><a href="https://learn.hashicorp.com/tutorials/terraform/install-cli">https://learn.hashicorp.com/tutorials/terraform/install-cli</a></blockquote><p>After installation, you can run any Terraform command to verify that Terraform is installed correctly. I will be using the version command.</p><pre>$ terraform version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVG3a4Hb_Sud9SwTFtN75Q.png" /></figure><p>Now, we are ready to start writing our first configuration file.</p><h4>HashiCorp Configuration Language (HCL)</h4><p>HashiCorp Configuration Language (HCL) is a configuration language used with the HashiCorp set of tools, notably Terraform. The main purpose of the HCL is to declare resources, which represent infrastructure objects (such as compute instance, an EC2 instance, an app engine instance, etc).</p><p>The syntax for writing configuration files consists of few basic elements.</p><pre><strong>&lt;</strong>BLOCK TYPE<strong>&gt;</strong> &quot;&lt;BLOCK LABEL&gt;&quot; &quot;&lt;BLOCK LABEL&gt;&quot; {<br>  # Block body<br>  <strong>&lt;</strong>IDENTIFIER<strong>&gt;</strong> <strong>=</strong> <strong>&lt;</strong>EXPRESSION<strong>&gt;</strong> # Argument<br>}</pre><ul><li><strong>Blocks</strong>: They act as containers for other contents. Each block has its own <strong>type</strong> and can have zero or more <strong><em>labels</em></strong> and a <strong>body</strong> containing any number of <strong>arguments</strong> and nested blocks.</li><li><strong><em>Arguments</em></strong><em>: Used to </em>assign a value to a name.</li><li><strong>Expressions</strong>: This represents a value, either literally like (22, “This is some value”) or by referencing (Resource attribute reference which we will look at later) and combining other values.</li></ul><p>The following configuration file (<strong>main.tf</strong>) allows us to create a new file named “my_first_config.txt” with the content “This is my first HCL config file.”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71ed838190849f9d96de94781d54e180/href">https://medium.com/media/71ed838190849f9d96de94781d54e180/href</a></iframe><p>Here we are making use of the “<strong>resource” </strong>block type, there are also various block types each with its own arguments and labels.</p><p>We have a configuration file ready, now let&#39;s create our first resource.</p><h3>Terraform Workflow</h3><p>We have done our job of writing the configuration file, now it&#39;s time for Terraform to step in and provision resources for us. First, let&#39;s look at the Terraform workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gK4KLyEo699MjcKhzNP8Qg.jpeg" /><figcaption>Terraform Workflow</figcaption></figure><p>A Terraform workflow consists of the following steps:</p><ol><li>init</li><li>plan</li><li>apply</li></ol><p>Let’s look at each of these steps in detail.</p><h4>1. init</h4><p>After we have written our configuration file, we need to initialize the configuration directory to be used by Terraform. By initializing the configuration directory, what we mean is we will be downloading &amp; installing all the required providers defined in the configuration file for our desired environment.</p><blockquote>Terraform makes use of Plugin based architecture. This is how it is able to support multiple providers. Want to add a new provider, well just download and install the required plugin and your ready to go.</blockquote><p>You initialize your configuration directory by using the following command in the directory where you have your configuration files.</p><pre>$ terraform init</pre><p>Let’s use our `<strong>main.tf</strong>` configuration from above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTuCMP7CCvzB5EeanF0_vA.png" /><figcaption>Configuration directory initialization</figcaption></figure><p>You can see that it started downloading and installing provider plugin for local .</p><blockquote>There are Offical , Verified and Community providers.</blockquote><blockquote>Offical: Owned and maintained by HashiCorp</blockquote><blockquote>Verified: Owned and maintained by 3rd party company that has partnered with HashiCorp</blockquote><blockquote>Community: Maintained and published by community members.</blockquote><p>You can see it is installing the plugin hashicorp/local version 2.1.0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TR1LhIErKh6tS1sdSqp22g.jpeg" /><figcaption>Plugin’s name breakdown</figcaption></figure><blockquote>Quick Tip : You can run the terraform init multiple times in the same directory without affecting your infrastructure.</blockquote><p>We can locate the plugin inside the hidden directory `.terraform` or type the following command to list our current plugins.</p><pre>$ terraform providers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l74Rs8dRvGZ-G_9fd7Cuyw.png" /></figure><h4>2. plan</h4><p>In this step, Terraform generates an execution plan i.e what needs to be done and how to do it. Since Terraform is declarative we don’t need to specify the how.</p><p>This will also validate the configuration file, and throws errors if something is wrong for example a typo, missing or unsupported arguments, etc.</p><blockquote>Quick Tip: You can use terraform validate command to validate your configuration file at any time.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuI1YFy17ODf2ToZQf0lSw.png" /><figcaption>Plan phase validation</figcaption></figure><p>If the configuration file is valid, you will be shown what actions will be taken.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOwlgN6pvst6fo85Rx3PLA.png" /></figure><h4>3. apply</h4><p>This is the step where the actual magic happens. Based on the execution plan Terraform provisions the resources to achieve the desired state. This might include creating new instances or making changes, destroying old resources and re-creating new resources, etc.</p><p>To apply the changes you use the terraform apply command. You will be prompted to enter yes if actually intend to execute the plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwD0_Teh5ilI_kPT29Goxg.png" /></figure><p>If you type yes the resources will be provisioned, in our example our local file names my_first_config.txt has been created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLrcSrjyHaOG-H74_TpwvA.png" /></figure><h3><strong>Updating resources &amp; Resource attribute reference and dependencies</strong></h3><p>Once a resource has been created, you also update it using the same terraform applycommand.</p><p>For example, I updated the content and performed apply again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lehqEbVRc-rOFCg9obAvgA.png" /></figure><p>You can always verify the changes that are going to occur by using the terraform plan command.<a href="https://medium.com/p/99b413239bb/edit">https://medium.com/p/99b413239bb/edit</a></p><p>However, updating resources is not that simple. If we have introduced new providers, we haven’t installed them yet so we cannot use them. So, we have to run the `init` command again to download and install the plugin.</p><p>For example, if we introduce a new resource to get the current timestamp and run terraform apply it again, an error will be thrown. It couldn&#39;t load the plugin because we haven&#39;t installed it yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5bHQ-re6E5MlN4xqcNosg.png" /><figcaption>Terraform Update Error</figcaption></figure><p>How do we install plugins in Terraform, again?</p><p>Oh, terraform init .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bax_QvbHOL8vgkPFZwgD-A.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40cefc5d675627d57440a4ea51d4d76f/href">https://medium.com/media/40cefc5d675627d57440a4ea51d4d76f/href</a></iframe><p>You can see that I’m using the attribute of another resource (a.k.a <strong>Resource attribute reference</strong>) of type “<strong>time_static</strong>” in “<strong>local_file</strong>” to set its content. To do this, we interpolate the content using <strong>${YOUR_VALUE}</strong>. Thus it depends on “<strong>time_static</strong>”. This type of dependency is called <strong>“Implicit Dependency”.</strong> This type of dependency is created by reference expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6XoEZ6BAEKvVev9xf32Dhw.jpeg" /></figure><p>There is also another type of dependency known as <strong>“Explicit Dependency” </strong>When we don’t have any resource attribute reference but have dependencies on other resources we make use of the depends_on meta-argument and pass a list of dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e3ed66e24ef624b2af503b9a9214b9a/href">https://medium.com/media/1e3ed66e24ef624b2af503b9a9214b9a/href</a></iframe><blockquote>Dependencies affect the order in which resources are <strong>created</strong> and <strong>destroyed</strong>. First the time_static.now will be created because in order to create local_file.my_first_config we need access the attribute of “time_static.now”.</blockquote><blockquote>During deletion, <em>local_file.my_first_config will be deleted and then </em><em>time_static.now because if we deleted </em><em>time_static.now our </em><em>local_file.my_first_config would reference a resource that no longer exists.</em></blockquote><p>If you hit the apply command again you can see the content change every time you hit apply.</p><h4>Destroying resources</h4><p>What if we want to destroy resources, you can do so by running the terraform destroycommand.</p><blockquote>If you intend to permanently remove resources completely from the infrastructure remove the resource from the configuration file and apply the changes. The destroy commands will only remove the resource until it is applied again.</blockquote><pre>$ terraform destroy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIUThlpwJTcDtHR6PXr_kQ.png" /><figcaption>Terraform destroy</figcaption></figure><p>You can see that local_file.my_first_config was deleted first.</p><p>But, be aware it will destroy our entire resources. So, how to delete a specific resource?</p><p>Well, you specify the target argument and provide the resource you want to delete as “<strong>resource_type.name_of_resource”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hyfZBReqDlBwxSrfWEm8kw.png" /><figcaption>Target destroy</figcaption></figure><p>We can see that this time it only deleted a single resource that we specified. However, be very careful of <strong>dependencies</strong> when deleting resources. If we delete a resource upon which many other resources <strong>depends_on </strong>all of those will be deleted as well. You can verify this by trying to delete time_static.now with the target argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZjUNvxRL7oQ6QbrpHZajA.png" /><figcaption>Destroying with dependencies</figcaption></figure><p>Now, focusing on your DevOps journey I have skipped some important concepts and basics in this article since its already a long one. So, if you want to explore more I would recommend you exploring the following concepts.</p><ul><li>Mutable and immutable infrastructure</li><li>Variables, since we will not be always hard coding our values. Esp. in cases like these configuration files which might be contain sensitive information.</li><li>Terraform State and its consideration</li><li>Terraform Modules</li><li>Other meta-arguments</li></ul><p>I hope this article has been helpful to you. If you completely read this article, Thank you.</p><p>Keep learning and growing. In future article we will be working with a cloud provider. Stay tuned.</p><p>Additional Resources ( Evergrowing list)</p><ul><li><a href="https://spacelift.io/blog/how-to-destroy-terraform-resources">How to Destroy Resources from Terraform: Tutorial</a> by SpaceLift</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99b413239bb" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/getting-started-with-terraform-for-aspiring-devops-engineer-99b413239bb">Getting started with Terraform — For aspiring DevOps Engineer</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD with GitHub Actions — React Monorepo to Firebase Hosting]]></title>
            <link>https://articles.wesionary.team/ci-cd-with-github-actions-react-monorepo-to-firebase-hosting-14e02e30ca90?source=rss-2db942015095------2</link>
            <guid isPermaLink="false">https://medium.com/p/14e02e30ca90</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[deployment-pipelines]]></category>
            <dc:creator><![CDATA[Sau-rav Adhikari]]></dc:creator>
            <pubDate>Tue, 04 May 2021 09:46:54 GMT</pubDate>
            <atom:updated>2021-05-04T09:46:54.021Z</atom:updated>
            <content:encoded><![CDATA[<h3>CI/CD with GitHub Actions — React Monorepo to Firebase Hosting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJw8th1ag-N69nO8jpFF_A.png" /><figcaption>React Mono Repo -&gt; Firebase using GitHub Actions</figcaption></figure><p>In this article, we will be exploring how to deploy and host our React app (Monorepo) to Firebase hosting with different sites for each package using targets.</p><blockquote>I am writing for Monorepo, however, you can follow the exact same procedures for a monolithic repo too, with some changes in the configuration.</blockquote><p>Well, things don’t end there, we will also set up CI/CD (Continuous Integration/ Continuous Deployment) pipeline using GitHub actions to automate the process. So, for simplicity, I am breaking this entire article into 3 sections.</p><ol><li>Setup React Monorepo app (Optional)</li><li>Setup Firebase Project</li><li>Setup GitHub Actions</li></ol><h3>Setup React Monorepo app (Optional)</h3><p>If you already have a Monorepo app you can skip this section. However, if you want to jump right in and get started then you can use my repo for ease. I have already set up a basic barebone Monorepo for this.</p><p><a href="https://github.com/n3rdkid/devops-guide-react-monorepo-firebase">n3rdkid/devops-guide-react-monorepo-firebase</a></p><p>Clone the repo and install the dependencies, after that everything should be set up for you.</p><blockquote>You can delete <em>firebase.json</em> <em>.firebaserc</em> and <em>.github/workflows</em> if you want a complete fresh start.</blockquote><pre># To install dependencies or you can use &quot;npm&quot; as well<br>yarn install</pre><p>To make sure the app is working correctly run it using the following command in your terminal.</p><pre>yarn start</pre><p>This will run 2 simple packages, “admin” &amp; “user” and you should see the following tabs open in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkunP_sUKU72CFjo6vtWKg.png" /><figcaption>User Package</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHTRwpZO4jrg_YMn9fiedQ.png" /><figcaption>Admin Package</figcaption></figure><p>Our Monorepo app is now set up and is running, let’s move on to the next section.</p><h3>Setup Firebase Project</h3><p>Let’s set up and configure our firebase project so that we can later deploy and host our app. For this, sign in to your Firebase console and set up a new project.</p><p><a href="https://firebase.google.com/">Firebase | Google&#39;s Mobile and Web App Development Platform</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDk_vtmQdzXCmAu6VracGA.png" /><figcaption>Step 1: Create a project</figcaption></figure><p>You can choose to set up analytics or not, it&#39;s up to you. After successfully creating your project, you will be redirected to “Project overview”. Go to hosting and press “Get Started”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9mDvt0C13FhAwxu-TApuA.png" /><figcaption>Step 2.1: Setup Hosting</figcaption></figure><p>You will be shown the setup guide for Firebase hosting.</p><blockquote>We will automate the deployment using CI/CD pipeline in the next section. For now let’s make sure we are able to deploy.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E480648o7zGWgAX_Yqtm4w.png" /><figcaption>Setup 2.2: Setup Firebase CLI</figcaption></figure><p>After installing “firebase-tools”, login to your firebase console from the CLI and then initialize your project using the commands shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQfuXmhuG4TrOXpB_ewYbQ.png" /><figcaption>Setup 2.3: Initialize your project</figcaption></figure><p>After you enter firebase init you will be shown the following menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qohCSqvc9VKBErmM5bVDmA.png" /><figcaption>`firebase init` menu</figcaption></figure><p>Currently, I am only going to use “<strong>Hosting”</strong> only, but you can select all the features that apply to your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltAJR_u1x-0EOPv7t3jE2w.png" /><figcaption>Firebase Project Setup</figcaption></figure><p>Since we have already set up a project, go with “<strong>Use an existing project</strong>” and select your project. Also, for “<strong>Hosting setup”</strong> you can configure as per your requirements since we will be re-writing most of it so I just entered random info.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjPInpliJduaaoSiXyhwjg.png" /><figcaption>Firebase Hosting Setup</figcaption></figure><p>The configuration info that is generated will look like the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4475d9c9c60267fbd14f12d0718b43bc/href">https://medium.com/media/4475d9c9c60267fbd14f12d0718b43bc/href</a></iframe><p>public : This is the folder from which files will be served.</p><p>rewrites : We are redirecting every route to ./index because we are creating a single-page app.</p><p>And our project information will look something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27a3413266c4bbba4f7ca7dcc51eccaa/href">https://medium.com/media/27a3413266c4bbba4f7ca7dcc51eccaa/href</a></iframe><p>However, things do not end here for us. Since we are trying to deploy our two different packages to different sites we will need to modify these configuration files. For this, let’s go back to the <strong>“Firebase console” </strong>and set up sites. In the “<strong>Hosting</strong>”, scroll down and go to the advanced section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whx0QjxIc47zgCkP7-Nyfw.png" /><figcaption>Hosting advanced</figcaption></figure><p>Let’s add two sites for the “admin” and “user” package.</p><blockquote>“{{SITE_NAME}}.web.app” be used to access your package/app.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxaYitckqbAfFQC-pGBUPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nKP4G1X5BjNXuuyQXhCyA.png" /><figcaption>Adding sites for the packages</figcaption></figure><p>Now let’s update our configuration file to link our packages with these sites.</p><pre>$ firebase target:apply hosting admin monorepo—admin<br>$ firebase target:apply hosting user monorepo—user<br></pre><p>This will update the .firebaserc file with the following contents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba29092e11f667db83b6fca2846bd92d/href">https://medium.com/media/ba29092e11f667db83b6fca2846bd92d/href</a></iframe><p>Here “<strong>targets</strong>” refers to “<strong>Deploy targets</strong>” which are identifiers for Firebase resources in our Firebase project.</p><p>“<strong>admin</strong>” &amp; “<strong>user</strong>” is the target name, which we will specify in our firebase.json . “<strong>monorepo — admin</strong>” &amp; “<strong>monorepo — user</strong>” are the names that we gave to our sites in the “<strong>Firebase console</strong>”.</p><p>Now let’s update our firebase.json to serve their respective build files to their sites. We will update the “<strong>hosting</strong>” attribute to an array of objects rather than an object since we are trying to host multiple sites. Notice, here we have added a new “<strong>target</strong>” property that matches the target name in .firebaserc , also we have updated our public directory to the respective build folder of the projects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3a68f0704e72d74743e8a951f6c1a31/href">https://medium.com/media/e3a68f0704e72d74743e8a951f6c1a31/href</a></iframe><p>Now, we can finally deploy our app to Firebase hosting. In your console, type the following command and your app should be up and running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*en5RUxvM2GTfOYRuP1jPCQ.png" /><figcaption>Step 2.4 Firebase deploy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bf_UM3yVep2HlCzgiRPd6w.png" /></figure><p>Congratulations, you have finally deployed your React Monorepo app to Firebase hosting with multiple sites.</p><h3>Setup GitHub Actions</h3><p>Well, now it’s time to set up our CI/CD pipeline.</p><p>You can do this directly from your GitHub repo’s actions tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHkbnAWCYmJ6XsuqZBRqZA.png" /><figcaption>Setting up Actions form GitHub</figcaption></figure><p>Another way to set up actions is to manually create the “<strong>workflows</strong>” folder inside the “<strong>.github</strong>” folder in your root directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*9Qz5cQYXN1qdsyL77XpHcQ.png" /></figure><p>Inside workflows, we specify our CI/CD pipeline workflows. Let’s look at an action generated by GitHub. GitHub contains many actions for us to use, this is the most basic one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eea17350362c5f5dcd995670541a9be/href">https://medium.com/media/6eea17350362c5f5dcd995670541a9be/href</a></iframe><p>[3] <strong>name: </strong>The name of our workflow which GitHub displays on our repository’s actions page. If we omit this field, GitHub sets the name to the workflow’s filename.</p><p>[6] <strong>on: </strong>This contains the name of the GitHub events that trigger our workflow. Currently, we trigger this workflow when new commits are pushed or pull request is opened on “<strong>master</strong>” or “<strong>main</strong>” whichever is your default branch.</p><blockquote>[workflow_dispatch] You can manually trigger workflows with the new <strong>workflow_dispatch</strong> event. You will then see a ‘<strong>Run workflow</strong>’ button on the Actions tab, enabling you to easily trigger a run.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ClkfFQyR4LltGu70w0_viw.png" /><figcaption>The manual trigger for workflow</figcaption></figure><p>[17] <strong>jobs</strong>: A workflow run is made up of one or more jobs that run in parallel by default. To run jobs sequentially, you can define dependencies on other jobs using the job’s id and <strong>needs</strong> keyword.</p><p>Here we have specified a “<strong>build” </strong>job that runs on Ubuntu and follows the “<strong>steps</strong>”. You can run your job on multiple OS environments as well.</p><p>In each step, we can reuse existing actions or write our own commands.</p><p>[26] <strong>uses: </strong>Selects an action to run as part of a step in your job. We can pass parameters to the actions using with which we will see later.</p><blockquote>“You can use an action defined in the same repository as the workflow, a public repository, or in a published Docker container image.”</blockquote><p>[29,33] Here you can see how you can run a one-line script or multi-line script in your workflow.</p><p>If you commit and push then you should see the workflow running in your GitHub repo’s action tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hyYk-EJbnHlLf5sPSTTzmQ.png" /><figcaption>GitHub Actions Tab</figcaption></figure><p>You can get detailed information about each step of the job as well, just click on the commit message and select the job, you will be shown logs of all the steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ia7-Fx4ci-q3_ZQRdqlRJA.png" /></figure><p>Now, let’s set up our own workflow to build and deploy to Firebase. We will be setting up the following workflow for our project to build &amp; deploy. You can add more steps like “linting”, “removing other files except for ./build” etc. as per your needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*bTglW_optL_g11uyf81zng.png" /><figcaption>Workflow example</figcaption></figure><p>Currently, we will trigger our workflow for any push on the “<strong>master” </strong>branch but you can set up workflows to be triggered as per your project needs. For example: Run only build on other branches except for “<strong>master” </strong>since we won’t deploy just any branch.</p><p>Your project might require <strong>env</strong> variables to run first let’s add them to our repo. Go to the “<strong>settings</strong>” tab and select <strong>“Secrets”</strong>.</p><p>If you are deploying for multiple environments like “Production”, “Staging”, “Development” etc. you can also use <strong>“Environments” </strong>to manage such scenarios. However, if you are using private repo “Environments” is only available for the GitHub enterprise plan only.</p><p>We will just be setting up repo secrets for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GE3b4Jq_C9mUqJaFyWYd4w.png" /><figcaption>GitHub repo’s Settings Tab</figcaption></figure><p>In the secrets section, click the “<strong>New repository secret</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9D0swPd2mMiVvCZn4kHSng.png" /><figcaption>GitHub repo’s Secrets</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbP1lZxkagvJM6nco1d2ZQ.png" /><figcaption>Adding GitHub repo secrets</figcaption></figure><p>Also, we need to add a <strong>“ServiceAccount”</strong> with permission to deploy to firebase hosting, you can set that up manually, or let’s do it from Firebase CLI. Since we have already set up hosting for our project we need to set up only the GitHub actions part for this type the following command in your root directory.</p><pre>$ firebase init hosting:github</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*485mtlbNckiHA-ZthlUAaA.png" /><figcaption>Firebase Hosting with GitHub actions</figcaption></figure><p>Delete any workflow files generated by this since we will have our own workflow file to deploy to Firebase hosting. Now, you should see the following secret added to your repo secrets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNhPlDBaLs6dbI65aCsWFw.png" /></figure><p>After you’ve set up your “<strong>Secrets</strong>” let’s start configuring our workflow file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c357bb08ab2215775ede24bda09961f6/href">https://medium.com/media/c357bb08ab2215775ede24bda09961f6/href</a></iframe><p>[ #One]: We are checking out our repo. This will also set the working directory to our project&#39;s root directory.</p><p>[#Two]: We set up a cache directory for our yarn dependencies and keys for restoring them if there is no difference between previous dependencies and current ones by comparing the yarn.lockfile. This action will Post check dependencies to our cache when the job runs successfully. This will reduce our build time since we will not need to install dependencies every time.</p><blockquote>You can see here I am reusing actions/cache@v2 , one good thing about GitHub&#39;s Actions is that there are numerous actions written and shared by the community. You can see I am providing various input parameters using with.</blockquote><p>[#Three]: Check-in cache if dependencies exist, if it does not exist install the dependencies otherwise do nothing. Your first build will usually be slower, but your subsequent builds should be comparatively faster because of this.</p><p>[#Four]: We create .env files for both our packages. Notice how we are changing the directory before creating files and also using ${{secets.SECRET_NAME}} to access secrets we previously added to our repo.</p><p>[#Five]: Currently I don’t have any tests written for these packages but you can write some tests and update the scripts and run them. We should always make sure our tests are running successfully before building our project. No point in deploying faulty code to production.</p><p>[#Six]: Here, we build the project. This will generate /build for both of our packages which we have already specified as our public folder in firebase.json file. Now, our project is ready to be deployed.</p><p>[#Seven]: We deploy our code to Firebase hosting’s live channel. You can also host your code to the preview channels if you want.</p><p>Now make some change and push your commit to the masteror main branch whichever you have configured. If everything is working fine, your code will be deployed to Firebase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fo2XS_U6TmuI24sxnzBt3w.png" /><figcaption>Build &amp; Deploy workflow</figcaption></figure><p>I hope this article has been helpful to you. Keep learning &amp; Stay Safe. 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14e02e30ca90" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/ci-cd-with-github-actions-react-monorepo-to-firebase-hosting-14e02e30ca90">CI/CD with GitHub Actions — React Monorepo to Firebase Hosting</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making sense of Kubernetes configuration files (YAML)]]></title>
            <link>https://articles.wesionary.team/making-sense-of-kubernetes-configuration-files-yaml-f90b033d5ad1?source=rss-2db942015095------2</link>
            <guid isPermaLink="false">https://medium.com/p/f90b033d5ad1</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sau-rav Adhikari]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 05:29:13 GMT</pubDate>
            <atom:updated>2021-02-12T11:14:21.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*tpXVfQRKLNdMfeF8.png" /></figure><p>Hello everyone! In this article, we will be taking a deep dive into understanding the configuration files (YAML) that we write for Kubernetes objects. If you’re someone who is learning or working with Kubernetes, you will definitely be writing configuration files for Pods, Deployments, Services, Ingress, and other Kubernetes objects.</p><p>Being someone who had no actual understanding of what those well-formatted YAML lines in the configuration files meant when learning Kubernetes, all I was doing was making sure my applications were up and running without fully understanding the how and why?</p><p>I decided to write this article to help anyone starting to learn Kubernetes so that those well-formatted lines do not scare you, and you can write them right off the top of your head.</p><p>Before you get started, make sure you have “<strong>minikube”</strong> and “<strong>kubectl”</strong> installed and ready to go.</p><blockquote>Installation guide: <a href="https://phoenixnap.com/kb/install-minikube-on-ubuntu">https://phoenixnap.com/kb/install-minikube-on-ubuntu</a></blockquote><ul><li><strong>minikube</strong> is a tool that allows us to run a single-node Kubernetes cluster locally. This is a great tool to try out Kubernetes.</li><li><strong>kubectl </strong>is a command-line tool that allows us to run commands against our Kubernetes cluster.</li></ul><p>After installation, start your <strong>minikube</strong> cluster and make sure <strong>kubectl</strong> is working properly as well.</p><pre>$ minikube start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhT8KhrlFPMXrGd08Ks7XA.png" /><figcaption>minikube start</figcaption></figure><p>Let’s get started by looking at the required fields for every configuration file regardless of the Kubernetes object type.</p><ul><li><strong>apiVersion:</strong> Specifies the version of the Kubernetes API, we will be using to create our Kubernetes object</li><li><strong>kind: </strong>Specifies the type of Kubernetes object we are trying to create</li><li><strong>metadata: </strong>Contains information that helps us to uniquely identify our Kubernetes object</li><li><strong>spec: </strong>Specifies the desired state of our object</li></ul><p>What do we mean by “<strong>the</strong> <strong>desired state</strong>”?</p><blockquote>A description of the characteristics we want the resource/object to have. For example,image you want run on the object, ports, memory &amp; CPU limitations etc.</blockquote><h3>Bonus Tip</h3><p>If you use VS Code, install the Kubernetes extension, among the many features, it provides us with snippets that we can use to generate our Kubernetes objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pd1KHUXjyCBUR_CpR-gecg.png" /><figcaption>Kubernetes Extension</figcaption></figure><p>So, let’s get started with writing a configuration file that will help us to create Pods in the Kubernetes cluster.</p><h3><strong>Pods</strong></h3><p>Pods are the smallest deployable objects in Kubernetes, they contain one or more of our containers, such as Docker containers.</p><p>A Pod is meant to run a single instance of our application on the Kubernetes cluster. However, we will not be creating individual pods directly in Kubernetes when working rather we will be creating “<strong>deployments</strong>” to manage our pods. We will look at this in more detail when talking about “<strong>deployments</strong>”. For now, let’s look at the template for creating a basic pod in Kubernetes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c6b1177aa9ac4ff66dc143d7d05613a/href">https://medium.com/media/6c6b1177aa9ac4ff66dc143d7d05613a/href</a></iframe><blockquote>Be sure to format your document properly with indentation.</blockquote><p>Here, line 1 and 2 specifies that we are trying to create a <strong>Pod </strong>object<strong> </strong>using version one (v1) of Kubernetes API.</p><p>From line 3 we start specifying the <strong>“metadata” </strong>for our pod.</p><ul><li><strong>name: </strong>Specifies the name that will be applied to our pod</li></ul><p>This is the name that will be displayed when you run the following command.</p><pre>$ kubectl get pods</pre><p>From line 7 we start specifying the “<strong>desired state</strong>” for our pod.</p><blockquote>Pods are capable of running multiple containers, we have to specify the containers in an lists format.</blockquote><p>You can configure your pods even more by specifying the resource limits, container ports, etc. if you want to in the <strong>spec </strong>section.</p><p>Let’s create a simple pod that will run the “<strong>nginx</strong>” docker image. Create a new “<strong>app-pod.yaml” </strong>file and write the following content. (Make sure to give proper indentation)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/642116d413e1544e0187f3fc381f9a62/href">https://medium.com/media/642116d413e1544e0187f3fc381f9a62/href</a></iframe><p>Now we are ready to actually create our pod in the cluster. To create a pod go to the terminal and type the following command.</p><pre>// If you are in the directory where you have saved your file<br>$ kubectl apply -f app-pod.yaml</pre><p>My “<strong>app-pod.yaml</strong>” file is inside the “/infra/k8s” folder so I will create the pod by specifying the path to the configuration file.</p><blockquote>You can use “.” to apply all the files.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBpdFYKhML5L83XlYKCIbw.png" /></figure><p>Congrats, our pod is now created. Let&#39;s get details about our pod. Type the following command:</p><pre>$ kubectl get pods -o wide</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-_HfGOloirRJtr2Htr1fQ.png" /></figure><blockquote>“<strong>-o wide</strong>” is not mandatory. O stands for output, and I did “-o wide” here just log additional information</blockquote><p>If you want more information about your pod you can type the following command in your terminal:</p><pre>$ kubectl describe pod myapp-pod</pre><p>Congratulations, you are now capable of creating a Kubernetes pod right off your mind.</p><h3>Deployments</h3><p>Now, let’s continue and checkout “<strong>deployments</strong>”. Most of the time we will be writing deployments to manage pods since pods are not directly deployed to the cluster.</p><p>Deployments make our life easier as we do not have to manually deal with pods. Deployments will automatically manage the application lifecycle, run the requested number of pods/replicas, monitor them, and if a pod dies it will automatically re-create it. This is where “<strong>scalability</strong>” and “<strong>availability</strong>” are achieved.</p><p>Let’s start with a template for creating “<strong>deployments</strong>”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c59e8cfcc392c7904aee8e3e5511181f/href">https://medium.com/media/c59e8cfcc392c7904aee8e3e5511181f/href</a></iframe><p>Here you can see we have the same <strong>4 mandatory fields</strong> just the contents have been slightly changed.</p><p>We are trying to create a deployment, so we specify that in line 2 and the Kubernetes API version in line 1. Nothing much has changed until now.</p><p>Starting from line 3 we specify “<strong>metadata” </strong>for the deployments. You can see a new field called “<strong>labels</strong>” has been added here.</p><ul><li><strong>labels: </strong>Labels are key-value pairs attached to the object that helps to organize and to select subsets of objects.</li></ul><blockquote><strong>Labels &amp; Selectors</strong> is how we connect different Kubernetes objects. The <strong>metadata</strong> <strong>section</strong> contains “<strong>labels</strong>” and the <strong>spec section</strong> contains the “<strong>selectors</strong>”.</blockquote><p>Here the label specified in line 5 is attached to our “<strong>deployment</strong>” which will be used to connect it to other Kubernetes objects like “<strong>services</strong>”. We will be talking about this in more detail in the “<strong>spec</strong>” section, where we connect our deployment to the pods.</p><p>In the “<strong>spec”</strong> section you can see new fields as well.</p><ul><li><strong>replicas: </strong>Specifies the number of pods to run</li><li><strong>template: </strong>Specifies the desired state of our pod<br>[ Here we write the configuration for our pod. See how its just missing “<strong>apiVersion</strong>” and “<strong>kind</strong>” field]</li></ul><blockquote>Notice how we are also giving our pod a label of “<strong>app: myapp</strong>” this label will be matched by the selector</blockquote><ul><li><strong>selector: </strong>Defines how the Deployment finds which Pods to manage<br>** The key-value pair specified in <strong>matchLabels</strong>, must be the same as the key-value pair specified in the <strong>labels </strong>of the pod (inside <strong>template</strong>)</li></ul><p>Congrats! Now you know about deployments too. Just remember the <strong>four mandatory fields</strong> and do not try to memorize each line, just connect the dots.</p><p>Now, let&#39;s create our deployment. Just like before we will create a configuration file for the deployment and apply it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23e33c6f39930906d7801980dc092cdb/href">https://medium.com/media/23e33c6f39930906d7801980dc092cdb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pndrKbgfhqo_pHCqNM8AOA.png" /></figure><p>Let’s get our deployment details.</p><pre>$ kubectl get deployments -o wide</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kz9liZk8OkFK1OlDVIJVbQ.png" /></figure><p>Great all of our 3 replicas are up and running.</p><h3>Services</h3><p>Service is the Kubernetes object that enables network access to a set of Pods in Kubernetes, by defining a logical set of Pods and a policy to access them such as IP, ports, protocol, etc.</p><p>When we make a request to the service, it matches the service’s selector and selects all the pods in the cluster matching it, chooses one of the pods, and forwards the request to it.</p><p>Services provide us with permanent IP addresses that can be attached to a pod.</p><blockquote>It is important to know that the <strong>lifecycle of a pod</strong> and s<strong>ervice</strong> are not connected, so even if the pod dies the IP address and service will stay.</blockquote><p>Creating <strong>services</strong> is simple in Kubernetes for you since you can already create <strong>pods</strong> and <strong>deployments</strong>. Look at the template below and try to guess what every line does.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5bfe79c9a51ade9744d6714058e85c5/href">https://medium.com/media/e5bfe79c9a51ade9744d6714058e85c5/href</a></iframe><p>The <strong>selector</strong> in line 6 matches labels for deployments or their pods. This helps to connect the deployments to the service.</p><p>Here we can see two new fields called “<strong>type” </strong>and<strong> “ports”</strong>.</p><ul><li><strong>type: </strong>Specifies the type of service we want to create</li></ul><blockquote>Read more about different types of services: <a href="https://www.bmc.com/blogs/kubernetes-services/">https://www.bmc.com/blogs/kubernetes-services/</a></blockquote><ul><li><strong>ports: </strong>Specifies the protocol, the port on which the service is accessible, the port of the pod where it should forward its requests (targetPort)</li></ul><p>Let’s create our service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/469d1a7b4752df2dd72f3ea6467cfd51/href">https://medium.com/media/469d1a7b4752df2dd72f3ea6467cfd51/href</a></iframe><pre>$ kubectl apply -f infra/k8s/.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkMfI9aNUtj4oVKHjImV6Q.png" /></figure><p>Let’s get the details of our service.</p><pre>$ kubectl get services -o wide</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZif0B7dCFpNfW2WE_UufA.png" /></figure><p>Well done, out of many Kubernetes objects you now know about pods, deployments, and services. Though I am ending this article here, your journey to learn Kubernetes has not ended yet. Keep learning and stay safe!</p><p>What to do next?</p><ul><li>Check out other Kubernetes objects like Ingress, Statefulset, EndPoints, etc.</li><li>Check out various types of Kubernetes services</li><li><a href="https://skaffold.dev/docs/install/">Skaffold</a>, an awesome tool that simplifies the build and deployment processes. Do check it out once.</li></ul><p>🙏🏻 Thank you for reading this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f90b033d5ad1" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/making-sense-of-kubernetes-configuration-files-yaml-f90b033d5ad1">Making sense of Kubernetes configuration files (YAML)</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Road to becoming a JavaScript Ninja: Creating your own simple JavaScript playground -Part II]]></title>
            <link>https://articles.wesionary.team/road-to-becoming-a-javascript-ninja-creating-your-own-simple-javascript-playground-part-ii-1f185c6c99f2?source=rss-2db942015095------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f185c6c99f2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sau-rav Adhikari]]></dc:creator>
            <pubDate>Mon, 25 Jan 2021 14:04:44 GMT</pubDate>
            <atom:updated>2022-08-05T05:57:58.412Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*MGHqDtvvaDCkvb1PZCoBjQ.png" /><figcaption>Source: <a href="https://commons.wikimedia.org/wiki/File:JavaScript-logo.png">JavaScript Logo</a></figcaption></figure><p>(* The code in this article is written in React.js but do not let that stop you from learning to build a fun application, even if you don’t know React challenge yourself)</p><p>Hello and welcome to Part-II of building our simple playground. In this article, we are going to build the User Interface for our playground API, where the user will be able to type the code and send it to the server and see the response after running the code.</p><p>If you are coming straight to this article and do not know what I am talking about, please check out my previous article.</p><p><a href="https://medium.com/wesionary-team/road-to-becoming-a-javascript-ninja-creating-your-own-simple-javascript-playground-part-i-38a931ebf752">Road to becoming a JavaScript Ninja: Creating your own simple JavaScript playground -Part I</a></p><p>If you want to get started with the UI first, you can clone my repo for the API and get started on your journey immediately.</p><p><a href="https://github.com/n3rdkid/nodejs-playground">n3rdkid/nodejs-playground</a></p><p>If you get stuck at any point, you can take reference from my repo.</p><p><a href="https://github.com/n3rdkid/nodejs-playground-webapp">n3rdkid/nodejs-playground-webapp</a></p><p>I will be using React to build our web app, you can use any framework of your choice or go hardcore and follow the path of “vanilla JS” to challenge yourself.</p><p>Let’s get started by creating a new folder <strong>“nodejs-playground-webapp” </strong>for our project. Let’s use “create-react-app” to get the show started quickly. We will be using TypeScript in the web app as well, just like in the API.</p><pre>npx create-react-app nodejs-playground-webapp --template typescript</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FfSAzydlc3jXRRFrfZr%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FfSAzydlc3jXRRFrfZr%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FfSAzydlc3jXRRFrfZr%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/bc28f8dd78ac37dffdc00d47c4b6ee17/href">https://medium.com/media/bc28f8dd78ac37dffdc00d47c4b6ee17/href</a></iframe><p>(***While the installation is on the way, go put in some cardio)</p><p>This command will create a new folder called “node-js-playground-webapp” that contains all your files for the React app. You can check if the installation has been done correctly by running the <strong>“start”</strong> script.</p><pre>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*685oduHG5-AsaNQH7NIuxg.png" /><figcaption>Initialized Project: Succesful</figcaption></figure><p>Let’s start by deleting all the unnecessary files in the folder. You can keep the files as it is and get started. I will be removing <strong>“app.css”</strong>, <strong>“app.test.tsx”,</strong> <strong>“index.css”</strong>, <strong>“logo.svg”</strong>.</p><p>After removing the files your app will crash because we are still using them in our <strong>“App.tsx”</strong> and <strong>“index.tsx”</strong>. Let’s update our files so that we do not have any issues left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VvAJvS0VOJdhvjuBlr5PFA.png" /><figcaption>index.tsx</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txquXhDBlJFQFRmQ4keEWQ.png" /><figcaption>app.tsx</figcaption></figure><p>Now we can get started by creating our own components. Inside <strong>“/src”</strong> create a components folder and a file <strong>“editor.tsx”</strong>. I am not going to organize our components and files since we just want to get up, running fast, If you want to organize your components better, do check out <strong>“</strong><a href="https://bradfrost.com/blog/post/atomic-web-design/"><strong>Atomic Design</strong></a><strong>”.</strong></p><pre>//components/editor.tsx<br>import React,{useState} from &quot;react&quot;;</pre><pre>const CodeEditor =()=&gt;{<br>    return &lt;h1&gt;Hello&lt;/h1&gt;<br>}</pre><pre>export { CodeEditor};</pre><p>Also inside “/components” create a “index.tsx” file from which we will export our components, by following this approach we can exports all of our components from a single source with consistency.</p><pre>//components/index.tsx<br>export {CodeEditor} from &quot;./editor&quot;;</pre><p>Now, let&#39;s import the &lt;Editor/&gt; component into our “app.tsx” file.</p><pre>//app.tsx<br>import React from &#39;react&#39;;</pre><pre>import {CodeEditor} from &quot;./components&quot;;</pre><pre>function App() {</pre><pre>    return (<br>        &lt;div className=&quot;App&quot;&gt;<br>            &lt;Editor/&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><pre>export default App;</pre><p>In your browser, you should see the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWoRNFAmEta16hRCGiLgvw.png" /><figcaption>App running successfully</figcaption></figure><p>Now, time to get to business we need an editor where we can write our code. For this, we will be using “<a href="https://www.npmjs.com/package/monaco-editor">monaco-editor</a>”, which provides us with an awesome editor with a lot of features.</p><pre>npm i monaco-editor @monaco-editor/react</pre><p>After installing it, let&#39;s import the “monaco-editor” in “editor.tsx” and configure the editor. For now, we will be configuring to with the default language set to “JavaScript”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eec4b4c2bb62c4bde8cec1deffaa6f12/href">https://medium.com/media/eec4b4c2bb62c4bde8cec1deffaa6f12/href</a></iframe><p>Now, you will see the editor ready to be used. Currently, we have not applied any styling so it might look plain but once you click on line 1 and start typing you will see the magic happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vcYzbybjR-M1pV3yLtrISQ.png" /></figure><p>I have already wired our editor’s value to a state variable called <strong>“code” </strong>and attached a change listener on it, so any changes made should be stored in our state.</p><p>We now need a way to send the data to the server and display the result. Let’s use “<a href="https://github.com/axios/axios">axios</a>” to make the requests.</p><pre>npm i axios</pre><p>Time to add a button that will initiate the request to the server when clicked, and define a function to handle the click and initiate the request using “axios”.</p><pre>//components/ediotr.tsx<br>const handleSubmit =async ()=&gt;{<br>    try{<br>      const {data} = await axios.post(&quot;localhost:5000/javascript&quot;);<br>      console.log(data);<br>    }catch(e){<br>      alert(&quot;OOPS error occured&quot;);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYV49G7vtVXxvAC_P8JuvQ.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ohzdYJK1wAdPWVk88%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3ohzdYJK1wAdPWVk88%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3ohzdYJK1wAdPWVk88%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/9f85548a6fc5cf537155470be65427c3/href">https://medium.com/media/9f85548a6fc5cf537155470be65427c3/href</a></iframe><p>Congrats, you faced your first “<strong>CORS</strong>” error. If you do not know what CORS is you can read about it here.</p><blockquote><em>Read: </em><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"><em>https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS</em></a></blockquote><p>I wanted to make you aware of <strong>CORS</strong> too, so I willingly let this happen so that you can learn something new and be a stronger <strong>Ninja</strong>.</p><p>Now, to fix this we need to make 2 lines of changes for now. We already have installed the “<a href="https://www.npmjs.com/package/cors">cors</a>” package in the “<strong>nodejs-playground</strong>” API app if you followed my previous article. If not, navigate to your API folder and install “cors”.</p><pre>npm i cors</pre><p>Now import and use the “<strong>cors</strong>” module as a middleware, you can configure it to your specific need if you like, but for now, let&#39;s just add the following.</p><pre>//in our playground API<br>//app.tsx<br>import cors from &quot;cors&quot;;<br>const app = express();<br>app.use(cors());</pre><p>Now let&#39;s try to run the code again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWUUs6LjNSVGK88qz6kBAg.png" /><figcaption>Response from our API</figcaption></figure><p>Check your console, if everything went well you should see the response from the server. [ * Make sure your API is running as well ]</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FJqDeI2yjpSRgdh35oe%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FJqDeI2yjpSRgdh35oe%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExdWM5bng0NWo5c2FjYXE4M2hzYWJldG95b3lhM2hhYnBmNm0ydWF2NSZlcD12MV9naWZzX2dpZklkJmN0PWc%2FJqDeI2yjpSRgdh35oe%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="363" frameborder="0" scrolling="no"><a href="https://medium.com/media/03ec133fd758cb482b7d4b9ee557fdae/href">https://medium.com/media/03ec133fd758cb482b7d4b9ee557fdae/href</a></iframe><p>We now have the response from the server too, let&#39;s display it to the user and our simple UI is done. Let’s take the response from the server and save it to a state variable so that every time we get a response from the server our UI will re-render and display the latest result.</p><pre>// components/editor.tsx<br>const [result,setResult]=useState(&quot;&quot;);</pre><pre>//inside handleSubmit()<br>setResult(data.data);</pre><p>Now to display the result, add the following container before the run button inside the &lt;CodeEditor/&gt; component, write some code and you are good.</p><pre>&lt;div style={{border:&quot;1px solid black&quot;,padding:&quot;16px&quot;,margin:&quot;16px auto&quot;}}&gt;<br>    {result}<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dubsBDlhigOKiCdB3V7iTA.png" /></figure><p>Now, this application is so simple and the UI sucks right? Be honest.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FW6o4vDYdNcKiVT0zVv%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FW6o4vDYdNcKiVT0zVv%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FW6o4vDYdNcKiVT0zVv%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/484a2dd4b4587b71bb00214985e7c568/href">https://medium.com/media/484a2dd4b4587b71bb00214985e7c568/href</a></iframe><p>That is where you come in my friend, I want to challenge you to do the following to our application. <strong>You cannot be a Ninja if you do not practice. </strong>I want you to try the following:</p><ol><li>Make sure the editor is already focused when the user opens the application( so that we do not have to click in every time)</li><li>Improve the UI, let your creativity run wild.</li><li>We are displaying the result without any formatting, you can display the result in another editor or format it.</li><li>Add a dropdown to change the language on the editor</li></ol><p>Finally, you might be wondering why I went with the trouble of making “editor.tsx” exporting it with from “index.tsx”, I could have just done all of this inside of “App.tsx” and got away with it. Well, my goal was to introduce you to some patterns that you will likely see when working on React applications.</p><p>I will also try to refactor the code and UI as a challenge to make sure it looks good and works well.</p><p>Thank you, for reading this article. Please feel free to give feedback and suggestions. In the next article, we will try to extend our API and make sure we can run “Python” and “Go” codes with our API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f185c6c99f2" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/road-to-becoming-a-javascript-ninja-creating-your-own-simple-javascript-playground-part-ii-1f185c6c99f2">Road to becoming a JavaScript Ninja: Creating your own simple JavaScript playground -Part II</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Road to becoming a JavaScript Ninja: Creating your own simple JavaScript playground -Part I]]></title>
            <link>https://articles.wesionary.team/road-to-becoming-a-javascript-ninja-creating-your-own-simple-javascript-playground-part-i-38a931ebf752?source=rss-2db942015095------2</link>
            <guid isPermaLink="false">https://medium.com/p/38a931ebf752</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Sau-rav Adhikari]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 12:24:52 GMT</pubDate>
            <atom:updated>2021-01-21T02:14:28.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image Source : https://commons.wikimedia.org/wiki/File:JavaScript-logo.png" src="https://cdn-images-1.medium.com/max/1021/1*MGHqDtvvaDCkvb1PZCoBjQ.png" /><figcaption>Source: <a href="https://commons.wikimedia.org/wiki/File:JavaScript-logo.png">JavaScript Logo</a></figcaption></figure><p>In this article, we are going to build a simple playground API for JavaScript; where you can run JavaScript code on a server and return the output to the client. You can modify the code to run any other language such as Python as well just make sure you have installed it on the server on which the API will be running.</p><p>I assume you already have Node.js installed and not required but it will be great if you have some previous experience working with <a href="https://expressjs.com/">Express.js</a> since I will not be explaining all the parts of the code that will be used for developing the API.</p><p>If you get stuck at any point you can reference my repository:</p><p><a href="https://github.com/n3rdkid/nodejs-playground">n3rdkid/nodejs-playground</a></p><h4>Initializing our project</h4><p>I will be using <strong>npm</strong> for installing dependencies you can use <strong>yarn</strong> as well. So, let’s get started by initializing our project. Create a folder named <br>“<strong>nodejs-playground”</strong> and navigate to the folder in your terminal, in the terminal type the following code.</p><pre>npm init -y</pre><p>This will create a filename <strong>“package.json”</strong> which will contain various information about our application, such as dependency requirements, scripts, and much more information about the project.</p><p>I am using git to track the changes in this project so I had already initialized it as a git repository so you can see GitHub info as well. It is not a necessity but if you want your life to be much easier, just use any version control tool.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf42a9e540fac00db95b7dbd318b6f0a/href">https://medium.com/media/bf42a9e540fac00db95b7dbd318b6f0a/href</a></iframe><p>Now, let’s install the required dependencies. Navigate to your project folder in the terminal (I am using ubuntu so, I will be at <strong>/home/nodejs-playground/</strong> in the terminal), and install the following dependencies.</p><pre>npm i --save @types/express express typescript ts-node-dev cors @types/cors express-validator</pre><p>We will be developing this app using TypeScript, so let’s also initialize our project as a TypeScript project.</p><blockquote><em>Read the benefits of TypeScript : </em><a href="https://medium.com/swlh/the-major-benefits-of-using-typescript-aa8553f5e2ed"><em>https://medium.com/swlh/the-major-benefits-of-using-typescript-aa8553f5e2ed</em></a></blockquote><pre>npx tsc --init</pre><p>You should see a new TypeScript configuration file “<a href="https://gist.github.com/n3rdkid/fec646b6ffb466978370a851ecc7e016"><strong>tsconfig.json</strong></a><strong>”</strong> created for the project, you can change any configurations to match your personal preference I will not be making any changes.</p><p>After that let’s set up the scripts in the <strong>“package.json” </strong>that will allow us to run the application. “<a href="https://www.npmjs.com/package/ts-node-dev"><strong>ts-node-dev</strong></a><strong>”</strong> is a handy tool that compiles the TypeScript files for us and runs it. In the scripts section of the “package.json” file add the following script.</p><pre>&quot;start&quot;: &quot;ts-node-dev index.ts&quot;</pre><h4>Setting up the server</h4><p>Now all of our configurations are done, let’s get started by setting up a basic server. I will create 2 files <strong>“index.ts”</strong> and <strong>“app.ts”</strong>. Our entry point will be “index.ts” but all of our main logic will be written in “app.ts” so that later we can test the app independently using testing libraries like <strong>“</strong><a href="https://www.npmjs.com/package/supertest"><strong>supertest</strong></a><strong>”</strong>.If you want to create a single file and put all your code in it, you can do so.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab1490f6f5bf1c3639ef1d9f4f056f8e/href">https://medium.com/media/ab1490f6f5bf1c3639ef1d9f4f056f8e/href</a></iframe><p>Now let’s start the app by running the start script in the package.json file.</p><pre>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCLIVEb2L5bdkLHHmtgZ2Q.png" /><figcaption>Starting nodejs-playground</figcaption></figure><p>Let’s check if our app is currently working as expected or not. I will be using <strong>“</strong><a href="https://www.postman.com/"><strong>Postman</strong></a><strong>”</strong> to check if the requests are being handled properly or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXSa28nQXe4NWFxlsFufZw.png" /><figcaption>Testing nodejs-playground API</figcaption></figure><h4>Running the code in the server</h4><p>Now the only thing left to do is run the code in the server and send the result back to the user. For this, we will be using the <strong>“</strong><a href="https://www.freecodecamp.org/news/node-js-child-processes-everything-you-need-to-know-e69498fe970a/"><strong>child_process</strong></a><strong>” </strong>module to run our code on the server, handle the output, and send it back to the user. This will be our workflow.</p><ol><li>Get the code from the user</li><li>Create a temporary file and store the code in it</li><li>Run the code</li><li>Get the result</li><li>Send the result back to the user</li><li>Delete the file</li></ol><p>We already have the code from the user now let’s create a new file with a unique name. I will be using the <strong>“uuid” </strong>library to do so, so let’s install it.</p><pre>npm i uuid</pre><p>Import it in your “app.ts” file and generate a unique file name, do not forget to concatenate the extension of the file. We are keeping track of it so that we can later delete the code from the disk. If we do not do this we will generate multiple copies of the same file every time a request is sent.</p><pre>// app.ts<br>import { v4 as uuidv4 } from &#39;uuid&#39;;</pre><pre>//Inside POST /javascript<br>let fileName = uuidv4()+&quot;.js&quot;</pre><p>After that, let’s create a file and write the content of the code in the file.</p><pre>// app.ts</pre><pre>import fs from &quot;fs&quot;;</pre><pre>//Inside POST /javascript<br>fs.writeFileSync(fileName,code)</pre><p>Now every time you perform a POST request to “/javascript” a new file is created with the code sent by the user as the content.</p><p>We can finally start running the code in our server, for this lets import “spawn” from the “child_process” module and run our code.</p><pre>//app.ts<br>import { spawn } from &quot;child_process&quot;;</pre><pre>//Inside POST /javascript after file is created<br>const javaScript = spawn(&quot;node&quot;, [fileName]);</pre><p>This will allow us to run our code on the server, we can now attach listeners to the child process to process various events. Let’s start by listening for any output that will be printed by the code, such as using console.log().</p><pre>// //Inside POST /javascript after creating a child process<br>let result:any;<br>javaScript.stdout.on(&#39;data&#39;, function (data) {<br>    result = { type: &quot;success&quot;, data: data.toString() };<br>});</pre><p>After that is done, we also need to listen for any error that we might get while running the code. For example, a typo such as “<strong>consoel.log()</strong>” will throw “<strong>ReferenceError: consoel is not defined</strong>”. By also listening for errors, we can notify the users if they have any mistakes in the code.</p><pre>javaScript.stderr.on(&quot;data&quot;, function (data) {<br>    result = { type: &quot;error&quot;, data: data.toString() };<br>})</pre><p>Finally, we have the result now which we can send to the user. Now, let’s delete the temporary file and send the result back to the user. We will be using “<strong>unlinkSync()</strong>” from the “fs” module to delete the temporary file. We do inside the <strong>“close” </strong>event handler of the child process because we can be sure that we have our response ready to send to the user when the “stdio” stream of the child process has been closed.</p><pre>javaScript.on(&#39;close&#39;, (code) =&gt; {<br>    fs.unlinkSync(fileName)<br>    res.json(result)<br>});</pre><p>The final code inside “/javascript” looks something like this, be sure to wrap the code inside of a try…catch block to handle any exceptions that might occur.</p><pre>const errors = validationResult(req);<br>if (!errors.isEmpty()) {<br>    return res.status(400).json({ &quot;error&quot;: errors.array()[0].msg });<br>}<br>const { code } = req.body;<br>let result: any;<br>let fileName = uuidv4() + &quot;.js&quot;;<br>try {<br>    fs.writeFileSync(fileName, code);<br>    // spawn a new child process<br>    const javaScript = spawn(&quot;node&quot;, [fileName]);<br>    javaScript.stdout.on(&#39;data&#39;, function (data) {<br>        result = { type: &quot;success&quot;, data: data.toString() };<br>    });<br>    javaScript.stderr.on(&quot;data&quot;, function (data) {<br>        result = { type: &quot;error&quot;, data: data.toString() };<br>    })<br>    javaScript.on(&#39;close&#39;, (code) =&gt; {<br>        fs.unlinkSync(fileName);<br>        res.json(result);<br>    });<br>} catch (e) {<br>    fs.unlinkSync(fileName)<br>    console.log(`Exception occurred!!!`);<br>}</pre><p>Congratulations 🥳🥳🥳, you have built your own little playground for JavaScript. Now to check our little playground. Be sure to send the data in JSON format, you can later integrate API to a frontend framework like React or Vue, also if you like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5Z73p5IR06aZNsl6DZPFA.png" /><figcaption>Testing nodejs-playground — Valid Code Case</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uds0fJykaLVeyeC_L_zvCQ.png" /><figcaption>Testing nodejs-playground — Invalid Code Case</figcaption></figure><p>This playground is by no means absolutely perfect and there are various improvements and additional features that we can add to it to make it more useful and efficient as well. We are just getting started with developing our playground and in future articles, we will continue improving our playground app.</p><p>Thank you for reading this article <a href="https://emojipedia.org/folded-hands/">🙏</a>. I hope this article was helpful to you, and if you got any suggestions or feedback I will be happy to hear it. Be sure to follow for more articles, your journey to becoming a JavaScript Ninja is just starting 🥳🥳🥳.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38a931ebf752" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/road-to-becoming-a-javascript-ninja-creating-your-own-simple-javascript-playground-part-i-38a931ebf752">Road to becoming a JavaScript Ninja: Creating your own simple JavaScript playground -Part I</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>