<?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 Mohd Afzal on Medium]]></title>
        <description><![CDATA[Stories by Mohd Afzal on Medium]]></description>
        <link>https://medium.com/@immohdafzal?source=rss-ab922dddaf86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Dc87XOeNqg7AInMH1SObiA.jpeg</url>
            <title>Stories by Mohd Afzal on Medium</title>
            <link>https://medium.com/@immohdafzal?source=rss-ab922dddaf86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:11:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@immohdafzal/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[How to Host & Update a Static Website on S3 with CloudFront + GoDaddy DNS]]></title>
            <link>https://immohdafzal.medium.com/how-to-host-update-a-static-website-on-s3-with-cloudfront-godaddy-dns-91a5b3bdd03b?source=rss-ab922dddaf86------2</link>
            <guid isPermaLink="false">https://medium.com/p/91a5b3bdd03b</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[website-hosting]]></category>
            <category><![CDATA[cloudfront-and-s3]]></category>
            <category><![CDATA[godaddy]]></category>
            <dc:creator><![CDATA[Mohd Afzal]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 16:57:52 GMT</pubDate>
            <atom:updated>2025-07-03T17:14:55.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xT8ykdxBbeZBGHV3-Sq0uA.png" /></figure><p>If you&#39;re looking for a cost-effective, scalable, and fast way to host your static website, AWS S3 + CloudFront is one of the best options out there. And if your domain is on GoDaddy, connecting the two is surprisingly simple.</p><p>In this guide, I’ll walk you through:</p><p>Hosting your static site on S3</p><p>Setting up CloudFront for CDN and HTTPS</p><p>Mapping your custom domain like static-website.example.com from GoDaddy</p><p>Updating your site with ease</p><p>---</p><p>Step 1: Prepare Your Static Website</p><p>Make sure your website files (HTML, CSS, JS, images) are ready.</p><p>Example folder:</p><pre>index.html  <br>style.css  <br>script.js  <br>/static</pre><p>---</p><p>Step 2: Upload Files to Amazon S3</p><p>1. Log in to AWS Console</p><p>2. Go to S3 &gt; Create Bucket</p><p>Name it something like your-bucket-name</p><p>Uncheck Block all public access</p><p>Acknowledge the warning</p><p>3. Enable static website hosting</p><p>Open your bucket &gt; go to Properties</p><p>Scroll down to Static Website Hosting and Enable it</p><p>Enter index.html in index and error page both options.</p><p>4. Upload your files under the Objects tab</p><p>5. Make files public</p><p>Select all → Actions → Make public</p><p>Or apply a public read-only bucket policy</p><p>---</p><p>🌍 Step 3: Set Up CloudFront (for CDN + HTTPS)</p><p>1. Go to CloudFront &gt; Create Distribution</p><p>2. For Origin Domain, select your S3 bucket</p><p>3. Set viewer protocol to Redirect HTTP to HTTPS</p><p>4. Default root object = index.html</p><p>5. Create the distribution</p><p>You’ll get a domain like this:</p><p>d1234abcdef.cloudfront.net</p><p>Note it down — we’ll point your domain to this.</p><p>---</p><p>🔐 Step 4: Get an SSL Certificate via AWS ACM</p><p>1. Go to Certificate Manager (ACM)</p><p>2. Request a certificate</p><p>Add domain: static-website.example.com</p><p>Choose DNS validation</p><p>3. AWS gives you a CNAME record — save this for the next step</p><p>---</p><p>🌐 Step 5: Update DNS in GoDaddy</p><p>1. Log in to GoDaddy</p><p>2. Go to My Products &gt; DNS &gt; Manage DNS</p><p>3. Add two CNAME Records:</p><p>One for domain mapping:</p><p>Name: static-website</p><p>Type: CNAME</p><p>Value: d1234abcdef.cloudfront.net</p><p>One for ACM validation (provided by AWS)</p><p>Save the changes and wait for DNS propagation (5–60 minutes).</p><p>---</p><p>🔁 Step 6: Update Your Website</p><p>1. Make local changes to your HTML/CSS/JS</p><p>2. Upload them to the S3 bucket (overwrite existing files)</p><p>3. (Optional) Invalidate CloudFront cache, if caching enabled at CloudFront</p><p>Go to CloudFront &gt; Invalidations &gt; Create new</p><p>Enter /* to refresh everything</p><p>---</p><p>Done!</p><p>Now your website is live on:</p><p>https://static-website.example.com</p><p>It’s fast, secure (HTTPS), and globally distributed via CloudFront CDN.</p><p>---</p><p>Other options to deploy on S3:</p><p>Use AWS CLI for faster deployments</p><p>Automate uploads using GitHub Actions</p><p>Turn on S3 versioning to easily rollback</p><p>---</p><p>Want More?</p><p>Need help setting up CI/CD with GitHub? Let me know in the comments!</p><p>---</p><p>Summary:</p><p>You just built a production-ready static website using:</p><p>Amazon S3 (for storage)</p><p>AWS CloudFront (for global delivery + HTTPS)</p><p>GoDaddy (for DNS and custom domain)</p><p>This stack is perfect for portfolios, landing pages, docs, and more.</p><p>It can be apply for any Single Page Application and normal websites or web apps build using HTML, CSS and Javascript</p><p>---</p><p>Quick Checklist</p><p>✅ Static files ready<br>✅ S3 bucket with hosting enabled<br>✅ CloudFront distribution with default root<br>✅ ACM certificate for HTTPS<br>✅ GoDaddy DNS pointing to CloudFront<br>✅ Update process via S3 + optional invalidation</p><p>---</p><p>Have questions or want help setting this up? Drop a comment or message — always happy to help!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91a5b3bdd03b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is DNS and how it works?]]></title>
            <link>https://medium.com/vectoscalar/what-is-dns-and-how-it-works-db3fbfc86912?source=rss-ab922dddaf86------2</link>
            <guid isPermaLink="false">https://medium.com/p/db3fbfc86912</guid>
            <category><![CDATA[domain-name-system]]></category>
            <category><![CDATA[top-level-domain]]></category>
            <category><![CDATA[domain-name-server]]></category>
            <category><![CDATA[dns-servers]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Mohd Afzal]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 01:46:19 GMT</pubDate>
            <atom:updated>2023-06-27T17:22:20.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*Fdbl787RcVoMIvbWqC1XaA.png" /></figure><h3>What is DNS?</h3><p>DNS stands for Domain Name System/Server. It’s a system or process that helps in finding the mapped IP of a domain or hostname that the end-user enters into the web browser to go to a particular website.</p><p>It helps to map the rememberable names of a domain or hostname to the host server IP addresses.</p><p><strong>Every domain has two or more parts, i.e:</strong><br>1. <a href="http://www.medium.com/">www.medium.com:</a> It has three parts, <strong>com</strong> is Top-Level Domain, the <strong>medium</strong> is the Second-Level Domain, and <strong>www</strong> is Sub Domain.<br>2. example.in: It has two parts, <strong>in</strong> is Top-Level Domain, an <strong>example</strong> is Second-Level Domain.</p><h3>Why is it necessary?</h3><p>Let&#39;s assume there is no concept of DNS and websites are accessible via their IP address, then check the below points.</p><ol><li><strong>Remember IP Address:</strong> Every website over the internet has an IP address (like IPv4 — 123.1. 2.123), this IP is nothing but the address of the host server. So, if we need to search a website by its IP address, it’ll be difficult to remember the IP addresses of multiple websites which we use on a daily basis like — google.com, gmail.com, outlook.com, stackoverflow.com, etc, if we need to search these sites by their IP like — 1.2.3.4, etc then, It’ll be difficult to remember.</li><li><strong>Server IP changes due to migration OR disaster-recovery:</strong> let&#39;s assume one business website start and its IP is 1.2.3.4 and lots of users are using it and that business is earning good money, then somehow either he needs to migrate the server from one network to another OR his server got failed or terminated then new server need to create and new servers will have a new IP address, so it’ll be a loss for him.</li><li><strong>Adding new servers:</strong> For example, one business is using one server with IP 1.2.3.4 and it’s used by their customers at some point in time or occasion there could be lots of traffic like —on Festivals, etc, he would require more servers to handler more traffic, but in that case, adding more server means different IP addresses for each server, and those will be new and not handy with their customers.</li></ol><h3><strong>Components of DNS?</strong></h3><p>DNS System is a hierarchy or tree-like system which has different-2 components from top to bottom, see those components below:</p><h4><strong>DNS Resolver:</strong></h4><p>It’s like a middleware or software service or server which receives the DNS domain query from the client (like a web browser) and forwards it to the DNA Root Server to get the associated information for the domain.</p><p>DNS Resolvers are of two types Iterative &amp; recursive. Examples are Google Public DNS Resolver and CloudFlare Resolver.</p><h4><strong>DNS Root Server:</strong></h4><p>It’s the highest-level server in the DNS system hierarchy, that first receives the DNS query request from DNS Resolver or in other words, the DNS Resolver first makes a call/query to Root Server. Globally. there are 13 Root servers available with different IP addresses or names. The number 13 server means that 13 main servers with different names or IP addresses and one/single server can have multiple servers behind the same IP or name.</p><p>Root servers are only iterative. That means when a Resolver makes a query to any Root Server then the Root Server returns a list of other servers/referrals (also called <strong>TLD Server</strong>) which are responsible for handling the next steps for the DNS query.</p><p>Their names start from a-root-servers.net, b-root-servers.net, …. to m-root-servers.net.</p><p>These a, b, c,…., m names are similar to the zones at global level.</p><h4><strong>Top-Level Domain (TLD) Server:</strong></h4><p>TLD stands for Top-Level Domain, it’s a part of a domain name followed by<strong> the last dot (.) </strong>called TLD.<br>For example: medium.com the last <strong>.com</strong> is TLD. Other values are .net, .edu, .in, .uk, etc.</p><p>TLD Server is the second-level server in the DNS system hierarchy which comes after Root Server. They are responsible to identify the domain by its TLD part and returning a list of other servers/referrals (also called <strong>TLD Authoritative Server</strong>) which are responsible for handling the next steps for the DNS query.</p><h4>Types of TLD Servers are:</h4><p>1. <strong>gTLD:</strong> Generic Top-Level Domain, examples are — .com (for commercials), .net (for network), .org(for organizations), .info(for information), .biz(for business), etc.<br>2. <strong>ccTLD:</strong> Country Code Top-Level Domain, examples are — .in (for India),.uk(for United Kingdom), etc.<br>3. <strong>tTLD:</strong> Test Top-Level Domain, examples are — .example, .test, .localhost, etc.<br>4. <strong>sTLD:</strong> Sponsored Top-Level Domain, examples are — .edu, .gov, etc.</p><h4><strong>Authoritative Server:</strong></h4><p>Authoritative servers are the Name Servers that return the final record details related to the DNS queries (domain name). They store zone-specific information about the domains.</p><h3><strong>How DNS works?</strong></h3><p>Let’s understand the process of how DNS query or domain search works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*SwzXjUd1cu7HcZ4-sVKWoA.png" /></figure><ol><li>Firstly, a user enters the URL for a website like- example.com.</li><li>Then, the web browser reads the resolve.conf file to get the address of the DNS Resolver and send a DNS query to the DNS Resolver for example.com.</li><li>DNS Resolver then receives the requests and checks in its cache if the IP for the DNS query exists in its cache then returns the IP to the browser.</li><li>If no cached details are found for the DNS query, then DNS Resolver sends the DNS query to one of the Root Servers, the Root Server returns the list of <strong>TLD Servers</strong> to the DNS Resolver by identifying the TLD of the sent DNS query (in our case it’s <strong>.com</strong>)</li><li>Then, DNS Resolver picks one server from the TLD server list and sends the DNS query to it, in response the TLD Server also returns a list of <strong>Authoritative Servers(AS)</strong> or <strong>Name Servers (NS) </strong>to DNS Resolver. <strong>NS or AS </strong>is a server where the DNS query domain details are stored.</li><li>DNS Server again picks one server from the Authoritative servers list and sends the DNS query to get the DNS record or IP from the Authoritative server.</li><li>Once the DNS Resolver received the IP or DNS record details of the DNS query, then it returns it to the web browser and caches it for the next same DNS query.</li><li>Then, the web browser makes a request to the IP address of the requested domain.</li></ol><blockquote>The above process is also called Recursive DNS Query or Recursive DNS Resolver.</blockquote><h4><strong>Note:</strong></h4><p>DNS Resolver caches the domain value till the TTL(Time to live) value, that’s the reason DNS record update propagation takes time.</p><h4>DNS Record Type:</h4><p>Below is the mainly used record-types are:</p><h4><strong>NS:</strong></h4><p>This is the Authoritative Server(AS) where the domain details are stored. The value of this record type is the address of the Name Server(Authoritative Server).</p><p>TLD Server returns the list of these Authoritative Servers when DNS Resolder passes the DNS Query to TLD Server for DNS record details.</p><h4><strong>A:</strong></h4><p>This record type is used to store the IP4 address mapping of the server.</p><h4>AAAA:</h4><p>This record type is used to store the IP6 address mapping of the server.</p><h4>CNAME(Canonical Name):</h4><p>This record type is mainly used to use to<br> — Create Sub-domain for a website, like — admin.example.com<br> — Configure an alias as a sub-domain to another existing domain or sub-domain(CNAME), like —<br> <a href="http://www.example.com/">www.example.com</a> =&gt; example.com<br>assets.<a href="http://www.example.com/">.example.com</a> =&gt; any-other-cdn.com (it may be AWS CloudFront CDN as well)<br>api.<a href="http://www.example.com/">.example.com</a> =&gt; aws-api-gateway-endpoint.com</p><p>It is also used to validate the SSL certificate via DNS validation. As AWS ACM (AWS Certificate Manager) also gives this DNS validation option for DNS verification.</p><h4>TXT:</h4><p>This is used to define Text record type, it’s mainly used for domain verification, when we configure or create SSL via another vendor they provide a TXT key &amp; TXT value that we use to define a TXT record in our DNS so that they can verify.</p><p>It’s just like a simple Text key-value pair record type.</p><h4>SOA(Start of Authority):</h4><p>It holds the details about the domain, server, email address of the administrator, and DNS zone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db3fbfc86912" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vectoscalar/what-is-dns-and-how-it-works-db3fbfc86912">What is DNS and how it works?</a> was originally published in <a href="https://medium.com/vectoscalar">VectoScalar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Secure Deployment & Access using Security Token Service(STS) :GetSessionToken API.]]></title>
            <link>https://medium.com/vectoscalar/aws-secure-deployment-access-using-security-token-service-sts-getsessiontoken-api-54253a122052?source=rss-ab922dddaf86------2</link>
            <guid isPermaLink="false">https://medium.com/p/54253a122052</guid>
            <category><![CDATA[aws-sts]]></category>
            <category><![CDATA[getsessiontoken]]></category>
            <category><![CDATA[sts-token]]></category>
            <category><![CDATA[aws-session-token]]></category>
            <category><![CDATA[aws-token-service]]></category>
            <dc:creator><![CDATA[Mohd Afzal]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 14:51:41 GMT</pubDate>
            <atom:updated>2023-06-11T15:10:09.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Secure Deployment &amp; Access using Security Token Service(STS): GetSessionToken API.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*Me1RhWZChxtWBF8pd8_0pA.png" /></figure><h4>What is STS?</h4><blockquote>AWS STS is Security Token Service that provides functionality to request temporary credentials like — Access &amp; Secret Keys. They have a limited lifetime; after that, they expire and can’t be reused.</blockquote><h4>Why do we need it?</h4><p>Usually, when we need to create &amp; access AWS resources via — CloudFormation, Serverless, or AWS CLI out of the AWS network on the local system, or 3rd Party CI/CD — GitHub, Gitlab, etc Or need to access S3, SNS, etc from code on client-side (front-end), then we need AWS Access &amp; Secret keys with the required permissions so that we can access or create these services.</p><p>To do so, we create an IAM permissions policy and attach it to an IAM user then, generate the Access &amp; Secret keys for the user and use them.</p><blockquote>These Access &amp; Secret keys are called <strong>Long-Term-Credentials</strong>. And, these are not expirable and can be continued used until we don’t rotate or deactivate them.</blockquote><p>So, if these keys are lost or stolen, there is a risk of misusing them to access or create unnecessary resources in the AWS cloud and increase the account billing.</p><p>AWS STS has different-2 ways/actions to request or generate temporary credentials.</p><p>— AssumeRole<br> — GetSessionToken<br> — AssumeRoleWithSAML<br> — etc.</p><p>In this post, we’ll focus on GetSessionToken.</p><h3>GetSessionToken:</h3><p>When we make a call to GetSessionToken API via SDK, AWS CLI then it returns a set of temporary credentials which contains Access, Secret keys, and a security token. And, these temporary credentials can be used to create &amp; access the resources. And, we can also pass a duration param while generating these temporary credentials which means how long these credentials can be live or used. The default is 1hr.</p><p>The IAM Users should use the <strong>Long-Term Credentials</strong> to invoke the GetSessionToken API.</p><p>The IAM User should be MFA enabled and also pass a valid MFA code with the GetSessionToken API in order to get the temporary credentials.</p><p>The returned temporary credentials would have the same level of permission as the IAM User whose credentials are used to invoke this API. It means that IAM User should have the required permissions to access the other AWS resources.</p><blockquote>These temporary Access &amp; Secret keys are called <strong>Short-Term-Credentials</strong>. And, these expired after the given time(default is 1 hr), so we don’t need to worry about rotating or deactivating them.</blockquote><h4>How does it work?</h4><p>GetSessionToken API required a valid MFA code with the IAM User MFA identifier that it uses to validate the access and if the MFA code and MFA identifier are valid then it returns the temporary credentials. Which can be used to invoke or access the AWS resources. And, these temporary credentials can access only the resources for which the IAM User has permission.</p><h4>Process:</h4><p>Here, is the step-by-step process of creating and using the temporary credentials using GetSessionToken.</p><ol><li>Create an IAM Policy with required permissions to access other resources.</li><li>Create an IAM User and attach the created IAM Policy.</li><li>Generate IAM User keys to invoke the GetSessionToken API.</li><li>Enable MFA for IAM User.</li><li>Enable MFA in all APIs.</li><li>Generate the temporary credentials and access other resources.</li></ol><p>Let’s go step by step as mentioned above.</p><h4>Create an IAM Policy with required permissions to access other resources:</h4><ol><li>Login to AWS Console.</li><li>Search the IAM service and go to Policies on the left sidebar.</li><li>Click on <strong>Create policy</strong> button.</li><li>For demo purposes, let’s give them Full access to S3, copy &amp; paste the below permission JSON in the JSON Policy tab, and click on the <strong>Next </strong>button.</li></ol><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;s3:*&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><ol><li>In the Next screen, enter the name of the policy — <strong>PolicySTS</strong> and click on <strong>Create Policy </strong>button.</li><li>Note down the ARN of this created policy.</li></ol><h4>Create an IAM User and attach the created IAM Policy:</h4><ol><li>Go to Users on the left sidebar.</li><li>Click on <strong>Add Users</strong> button. Below screen will open.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8SRskgTAPE-kR4OAG9ak7Q.png" /></figure><p>4. Enter username — <strong>UserSTS</strong> and click on the <strong>Next</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9ayBGc12GR4Bd8oUgncUg.png" /></figure><p>5. The above screen will open, click on the <strong>Attach policies directly</strong> and search for the recently created policy, select it, and click on the <strong>Next</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GizZSP_JDAw825-vPV7pLA.png" /></figure><p>6. The above screen will open, just click on <strong>Create user </strong>button.<br>7. Note down the ARN of this created user.</p><h4>Generate IAM User keys to invoke the GetSessionToken API:</h4><ol><li>Go to the newly created user named UserSTS profile screen.</li><li>Click on the <strong>Security credentials</strong> tab, then screen down to the <strong>Access keys</strong> section.</li><li>Click on <strong>Create access key</strong> button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Os4IISeCkQk4-K34sJF7Xw.png" /></figure><p>4. Select the <strong>Other</strong> option and click on the <strong>Next</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZJBaG6yztRZTas3whJJig.png" /></figure><p>5. Enter the description and click on <strong>Create access key </strong>button and copy or download the Access &amp; Secret keys.</p><h4>Enable MFA for IAM User:</h4><p>Follow this <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_virtual.html?icmpid=docs_iam_console#enable-virt-mfa-for-own-iam-user">AWS Official documentation</a> to enable the MFA for IAM Users.</p><h4>AWS CLI Configure:</h4><p>Now, we’ll configure the AWS CLI with the <strong>Long-Tem Credentials</strong> Access &amp; Secret keys generated in the above steps.</p><ol><li>Install AWS CLI from <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html</a></li><li>To set up CLI run the command, we’re configuring a profile name sts-demo.</li></ol><pre>aws configure --profile sts-demo</pre><p>AWS CLI will ask for the credentials, then enter the Access, Secret, and Region values step by step</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dt_L-afgCQ7HLiekOWD3DA.png" /></figure><h4>Practical:</h4><ol><li>Once, the credentials are configured, try to access the S3 by using the below command</li></ol><pre>aws s3 ls --profile sts-demo</pre><p>You should be able to view the list of S3 buckets that are under your AWS Account. Because currently there is no restriction for this IAM User even if we have enabled the MFA.</p><h4>Enable MFA in all APIs:</h4><p>2. Now, let&#39;s go back to the <strong>PolicySTS</strong> which we have created recently<strong>,<br>&gt; </strong>Go to Policies<br>&gt; Search Policy by name <strong>PolicySTS<br></strong>&gt; Open it and Edit the permissions<br>&gt; Then, replace the existing JSON policy with the below one and <strong>Save</strong> it.</p><blockquote><strong>aws:MultiFactorAuthPresent: </strong>[value should be true or false]</blockquote><blockquote>This time we have added condition <strong>aws:MultiFactorAuthPresent</strong> as <strong>true</strong> which means the keys that will access the resources should be authenticated by MFA. And, it presents only with Short-Term credentials. Long-term Credentials do not include this key.</blockquote><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;s3:*&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;Bool&quot;: {<br>                    &quot;aws:MultiFactorAuthPresent&quot;: &quot;true&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><blockquote><strong>aws:MultiFactorAuthAge: </strong>[values should be numeric in seconds]</blockquote><blockquote>We can also include <strong>aws:MultiFactorAuthAge</strong> in <strong>Condition</strong> to specify time after which the temporary credentials won’t be accepted even if they are generated with more lifetime than the value of <strong>aws:MultiFactorAuthAge</strong>.<br>i.e: <br>If the temporary credentials are created with 10hr and Admin has configured aws:MultiFactorAuthAge: 3600 (value should be in seconds) in Policy then the temporary credentials will not be accepted after 1hr</blockquote><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;s3:*&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;Bool&quot;: {<br>                    &quot;aws:MultiFactorAuthPresent&quot;: &quot;true&quot;<br>                },<br>                &quot;NumericLessThan&quot;: {<br>                    &quot;aws:MultiFactorAuthAge&quot;: &quot;300&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>3. Now, again run the same command.</p><pre>aws s3 ls --profile sts-demo</pre><p>You should see the below error message:</p><blockquote>An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied</blockquote><p>Cool!! that means the MFA has been enabled in the APIs, now we need to request the temporary credentials with the valid MFA code.</p><h4>Generate the temporary credentials and access other resources:</h4><p>2. Run the below command to request the temporary credentials using the MFA code</p><pre>aws sts get-session-token --serial-number arn:aws:iam::{Account-ID}:mfa/{IAM-UserName} --token-code {Valid-MFA-COde} --profile sts-demo</pre><p><strong>Command Parameters:</strong></p><p><strong>— serial-number:</strong> This is the <strong>Identifier </strong>of the attached MFA device with the IAM User. To find it follow the steps:<br>&gt; Go to the IAM User profile<br>&gt; Click on the Security credentials tab<br>&gt; Go to the <strong>MFA </strong>section<br>&gt; Copy the <strong>Identifier </strong>the format will be</p><pre>arn:aws:iam::{Account-ID}:mfa/{IAM-UserName}</pre><p><strong>— token-code:</strong> A valid MFA code from the attached MFA device which could be valid for 30 seconds.</p><p><strong>— profile:</strong> It’s the name of the AWS profile, which means which user/profile AWS CLi should use to invoke this command.</p><blockquote>It also supports other parameters as well — Duration, MFA related, etc.<br>For more details see the <a href="https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html">AWS Official Documentation</a></blockquote><p>You should see a below similar response.</p><pre>{<br>    &quot;Credentials&quot;: {<br>        &quot;AccessKeyId&quot;: &quot;&quot;,<br>        &quot;SecretAccessKey&quot;: &quot;&quot;,<br>        &quot;SessionToken&quot;: &quot;&quot;,<br>        &quot;Expiration&quot;: &quot;2023-06-11T12:11:21+00:00&quot;<br>    }<br>}</pre><p>3. Now, we’ll use the keys from the above temporary credentials JSON and export them to AWS CLI environment variables and try to access the S3 service.</p><p><strong>For Mac:</strong></p><pre>export AWS_ACCESS_KEY_ID={Credentials.AccessKeyId}<br>export AWS_SECRET_ACCESS_KEY={Credentials.SecretAccessKey}<br>export AWS_SESSION_TOKEN={Credentials.SessionToken}</pre><p><strong>For Windows:</strong></p><pre>set AWS_ACCESS_KEY_ID={Credentials.AccessKeyId}<br>set AWS_SECRET_ACCESS_KEY={Credentials.SecretAccessKey}<br>set AWS_SESSION_TOKEN={Credentials.SessionToken}</pre><p>4. Now, let’s try to access the S3 again, run the below command, this time we don’t need to pass the profile name ( — profile sts-demo), because keys are exported as a default profile.</p><pre>aws s3 ls</pre><p>This time, you should be able to view the list of the S3 buckets in your AWS account.</p><p>5. <strong>Note:</strong></p><p>If still see an <strong>AccessDenied</strong> error that means keys are not exported or set properly, then open the ~/.aws/credentials file on Mac/Linux OR C:\Users\USERNAME\.aws\credentials file on Windows.</p><p>And add the below entries at the end of the file:</p><pre>[default]<br>aws_access_key_id = {Credentials.AccessKeyId}<br>aws_secret_access_key = {Credentials.SecretAccessKey}<br>aws_session_token = {Credentials.SessionToken}</pre><p>Now, try to run the S3 ls command again it, should work fine and should be able to list the S3 bucket’s name.</p><h4>When should we use GetSessionToken?</h4><p>If we’re using the AWS Access keys in a less-secure environment and we want to make sure the proper security then we enabled the MFA in all the APIs which need to be accessed. So, the IAM User <strong>Long-Term Credentials</strong> won’t be working instead user needs to pass the valid <strong>MFA code</strong> and request for the temporary credentials to access the APIs or resources.</p><h4>Best practice:</h4><blockquote>If we create AWS resources from inside the AWS network like via AWS Pipeline, or Codebuild, etc.</blockquote><blockquote>OR</blockquote><blockquote>If we need to access resources like S3, SNS, SQS, SES, etc, from other services like — Lambda, EC2, Containers etc.</blockquote><blockquote>Then, it’s a best practice to use <strong>AWS IAM Role</strong> with required permissions instead of using AWS Access &amp; Secret Keys.</blockquote><p>You can also use the shell script from <a href="https://gist.github.com/mohd-afzal-vs/d8c059ce70c182bfe2b357e9dc63e6ef">Gist</a> to generate and set up the temporary credentials instead of invoking the API command and exporting variables manually.</p><p>For more details, check out the AWS official documentation.</p><p><a href="https://docs.aws.amazon.com/STS/latest/APIReference/welcome.html">Welcome to the AWS Security Token Service API Reference</a></p><p>We can also use <a href="https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html">AWS SDK</a> for GetSessionToken API, available for Programming languages. Check <strong>See Also</strong> section.</p><p>Read About AssumeRole API:</p><p><a href="https://immohdafzal.medium.com/aws-secure-deployment-access-using-security-token-service-sts-part-1-assumerole-f5a9cf36916f">AWS Secure Deployment &amp; Access using Security Token Service(STS). Part-1 (AssumeRole]</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54253a122052" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vectoscalar/aws-secure-deployment-access-using-security-token-service-sts-getsessiontoken-api-54253a122052">AWS Secure Deployment &amp; Access using Security Token Service(STS) :GetSessionToken API.</a> was originally published in <a href="https://medium.com/vectoscalar">VectoScalar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Secure Deployment & Access using Security Token Service(STS). Part-1 (AssumeRole]]]></title>
            <link>https://medium.com/vectoscalar/aws-secure-deployment-access-using-security-token-service-sts-part-1-assumerole-f5a9cf36916f?source=rss-ab922dddaf86------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5a9cf36916f</guid>
            <category><![CDATA[secure-devops]]></category>
            <category><![CDATA[sts-token]]></category>
            <category><![CDATA[secure-deployment]]></category>
            <category><![CDATA[assume-role]]></category>
            <category><![CDATA[aws-sts]]></category>
            <dc:creator><![CDATA[Mohd Afzal]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 12:59:22 GMT</pubDate>
            <atom:updated>2023-06-11T15:08:27.497Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Secure Deployment &amp; Access using Security Token Service(STS): AssumeRole API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*5swFUZ5J-jZAFJBZr7cHtw.png" /></figure><h4><strong>What is STS?</strong></h4><blockquote>AWS STS is Security Token Service that provides functionality to request temporary credentials like — Access &amp; Secret Keys. They have a limited lifetime; after that, they expire and can’t be reused.</blockquote><h4><strong>Why do we need it?</strong></h4><p>Usually, when we need to create &amp; access AWS resources via — CloudFormation, Serverless, or AWS CLI out of the AWS network on the local system, or 3rd Party CI/CD — GitHub, Gitlab, etc Or need to access S3, SNS, etc from code on client-side (front-end) then, we need AWS Access &amp; Secret keys with the required permissions so that we can access or create these services.</p><p>To do so, we create an IAM permissions policy and attach it to an IAM user then, generate the Access &amp; Secret keys for the user and use them.</p><blockquote>These Access &amp; Secret keys are called <strong>Long-Term-Credentials</strong>. And, these are not expirable and can be continued used until we don’t rotate or deactivate them.</blockquote><p>So, if these keys are lost or stolen, there is a risk of misusing them to access or create unnecessary resources in the AWS cloud and increase the account billing.</p><p>AWS STS has different-2 ways/actions to request or generate temporary credentials.</p><p>— AssumeRole<br> — GetSessionToken<br> — AssumeRoleWithSAML<br> — etc.</p><p>In this post, we’ll talk about AssumeRole.</p><h3><strong>AssumeRole:</strong></h3><p>When we make a call to AssumeRole API via SDK, AWS CLI then it returns a set of temporary credentials which contains Access, Secret keys, and a security token. And, these temporary credentials can be used to create &amp; access the resources. And, we can also pass a duration param while generating these temporary credentials which means how long these credentials can be live or used. The default is 1hr.</p><blockquote>These temporary Access &amp; Secret keys are called <strong>Short-Term-Credentials</strong>. And, these expired after the given time(default is 1 hr), so we don’t need to worry about rotating or deactivating them.</blockquote><h4><strong>How does it work?</strong></h4><p>In a nutshell, only the user(name <strong>UserSTS</strong>) who is whitelisted in Assume Role of an IAM Role (name <strong>RoleSTS</strong>), is able to access the resources according to the IAM Policy(name <strong>PolicySTS</strong>) attached to the IAM Role(name <strong>RoleSTS</strong>).</p><p>And, if the <strong>UserSTS</strong> tries to access the resources by generating and using their own <strong>Long-Term Credentials</strong>, it won’t be able to access the same resources which are allowed by <strong>PolicyOne</strong>. Because no permission policy is directly assigned to the user.</p><p>It means that <strong>UserSTS</strong> needs to assume <strong>RoleSTS</strong> in order to access those resources. And, it’s possible by using the <strong>AssumeRole API</strong> by passing the <strong>RoleSTS</strong> ARN while requesting the temporary credentials, and those credentials will be having the permissions allowed by <strong>PolicySTS</strong>.</p><h4>Process:</h4><p>Here, is the step-by-step process of creating and using the temporary credentials using AssumeRole.</p><ol><li>Create an IAM User without attaching any IAM Role or Policy.</li><li>Create an IAM Policy with required permissions to access other resources.</li><li>Create an IAM Role and add assume role policy and allow the above user into assume role policy.</li><li>Generate IAM User keys to invoke the AssumeRole API. (We’ll discuss it in detail later)</li><li>Generate the temporary credentials and access other resources.</li></ol><p>Let’s go step by step as mentioned above.</p><h4><strong>Create an IAM User without attaching any IAM Role or Policy:</strong></h4><ol><li>Login to AWS Console.</li><li>Search the IAM service and go to Users on the left sidebar.</li><li>Click on <strong>Add Users</strong> button. Below screen will open.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8SRskgTAPE-kR4OAG9ak7Q.png" /></figure><p>4. Enter username — <strong>UserSTS</strong> and click on the <strong>Next</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9ayBGc12GR4Bd8oUgncUg.png" /></figure><p>5. The above screen will open, no need to select any permission then, just click on the <strong>Next</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7Jaghf01ZLd1578eJrtKw.png" /></figure><p>6. The above screen will open, just click on <strong>Create user </strong>button.<br>7. Note down the ARN of this created user.</p><h4><strong>Create an IAM Policy with required permissions to access other resources:</strong></h4><ol><li>Click on Policies in the left sidebar and click on <strong>Create policy</strong> button.</li><li>For demo purposes, let’s give them Full access to S3, click on the <strong>Next </strong>button.</li><li>In the Next screen, enter the name of the policy — <strong>PolicySTS</strong> and click on <strong>Create Policy </strong>button.</li><li>Note down the ARN of this created policy.</li></ol><h4><strong>Create an IAM Role and add assume role policy and allow the above user into assume role policy:</strong></h4><ol><li>Click on the <strong>Roles</strong> on the left sidebar and click on <strong>Create role</strong> button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuOs4k5LicpxI9AKbgiKVg.png" /></figure><p>2. The above screen will open, click on the <strong>Custom trust policy</strong> option. And, replace this {paste-here-arn-of-newly-created-user} with User ARN in the below policy. Then, copy it and paste into the <strong>Custom trust policy</strong> section</p><pre>{<br> &quot;Version&quot;: &quot;2012-10-17&quot;,<br> &quot;Statement&quot;: [<br>  {<br>   &quot;Sid&quot;: &quot;Statement1&quot;,<br>   &quot;Effect&quot;: &quot;Allow&quot;,<br>   &quot;Principal&quot;: {<br>     &quot;AWS&quot;: &quot;{paste-here-arn-of-newly-created-user}&quot;<br>   },<br>   &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>  }<br> ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19D7TGp6_ySKBw6hXljqCw.png" /></figure><p>3. Click on the <strong>Next</strong> button. <br>4. On the Next permissions screen, search the create policy by name PolicySTS and select it and click on the <strong>Next</strong> button.<br>5. In the next screen, enter the name of the Role — <strong>RoleSTS</strong>, and click Create role.</p><h4><strong>Generate IAM User keys to invoke the AssumeRole API:</strong></h4><ol><li>Go to the newly created user named UserSTS profile screen.</li><li>Click on the <strong>Security credentials</strong> tab, then screen down to the <strong>Access keys</strong> section.</li><li>Click on <strong>Create access key</strong> button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Os4IISeCkQk4-K34sJF7Xw.png" /></figure><p>4. Select the <strong>Other</strong> option and click on the <strong>Next</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZJBaG6yztRZTas3whJJig.png" /></figure><p>5. Enter the description and click on <strong>Create access key </strong>button and copy or download the Access &amp; Secret keys.</p><p>Enough theory. Let’s discuss it in more detail with practicals.</p><h4><strong>AWS CLI Configure:</strong></h4><p>Now, we’ll configure the AWS CLI with the <strong>Long-Tem Credentials</strong> Access &amp; Secret keys generated in the above steps.</p><ol><li>Install AWS CLI from <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html</a></li><li>To set up CLI run the command, we’re configuring a profile name sts-demo.</li></ol><pre>aws configure --profile sts-demo</pre><p>AWS CLI will ask for the credentials, then enter the Access, Secret, and Region values step by step</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dt_L-afgCQ7HLiekOWD3DA.png" /></figure><h4>Practical:</h4><ol><li>Once, the credentials are configured, try to access the S3 by using the below command</li></ol><pre>aws s3 ls --profile sts-demo</pre><p>The, above command will give you the below error.</p><blockquote>An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied</blockquote><p>Because this user does not have any S3 permission OR no S3 policy(<strong>PolicySTS</strong>) is directly assigned to it. This <strong>UserSTS</strong> user can access the S3 only by assuming the role(<strong>RoleSTS</strong>) that will provide the temporary credentials and those temporary credentials will have the permissions allowed by <strong>PolicySTS</strong>.</p><p>2. Run the below command to request the temporary credentials using the <strong>RoleSTS</strong></p><pre>aws sts assume-role --role-arn arn:aws:iam::{your-aws-account-id}:role/RoleSTS --role-session-name sts-demo --profile sts-dem</pre><p><strong>Command Parameters:</strong></p><p><strong>— role-arn:</strong> Name of the Role that will be assumed by the user, in our case it’s RoleSTS.</p><p><strong>— role-session-name:</strong> It’s used to uniquely identify the session, just pass any unique value maybe user-name, email, profile name, etc.</p><p><strong>— profile:</strong> It’s the name of the AWS profile, which means which user/profile AWS CLi should use to invoke this command.</p><p>It also supports other parameters as well — Duration, MFA related, etc.<br>For more details see the <a href="https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html">AWS Official Documentation</a></p><p>You should see a below similar response.</p><pre>{<br>    &quot;Credentials&quot;: {<br>        &quot;AccessKeyId&quot;: &quot;&quot;,<br>        &quot;SecretAccessKey&quot;: &quot;&quot;,<br>        &quot;SessionToken&quot;: &quot;&quot;,<br>        &quot;Expiration&quot;: &quot;2023-06-11T12:11:21+00:00&quot;<br>    },<br>    &quot;AssumedRoleUser&quot;: {<br>        &quot;AssumedRoleId&quot;: &quot;&quot;,<br>        &quot;Arn&quot;: &quot;&quot;<br>    }<br>}</pre><p>3. Now, we’ll use the keys from the above temporary credentials JSON and export them to AWS CLI environment variables and try to access the S3 service.</p><p><strong>For Mac:</strong></p><pre>export AWS_ACCESS_KEY_ID={Credentials.AccessKeyId}<br>export AWS_SECRET_ACCESS_KEY={Credentials.SecretAccessKey}<br>export AWS_SESSION_TOKEN={Credentials.SessionToken}</pre><p><strong>For Windows:</strong></p><pre>set AWS_ACCESS_KEY_ID={Credentials.AccessKeyId}<br>set AWS_SECRET_ACCESS_KEY={Credentials.SecretAccessKey}<br>set AWS_SESSION_TOKEN={Credentials.SessionToken}</pre><p>4. Now, let&#39;s try to access the S3 again, run the below command, this time we don’t need to pass the profile name ( — profile sts-demo), because keys are exported as a default profile.</p><pre>aws s3 ls</pre><p>This time, you should be able to view the list of the S3 buckets in your AWS account.</p><p>5. <strong>Note:</strong></p><p>If still see an <strong>AccessDenied</strong> error that means keys are not exported or set properly, then open the ~/.aws/credentials file on Mac/Linux OR C:\Users\USERNAME\.aws\credentials file on Windows.</p><p>And add the below entries at the end of the file:</p><pre>[default]<br>aws_access_key_id = {Credentials.AccessKeyId}<br>aws_secret_access_key = {Credentials.SecretAccessKey}<br>aws_session_token = {Credentials.SessionToken}</pre><p>Now, try to run the S3 ls command again it, should work fine and should be able to list the S3 bucket&#39;s name.</p><h4><strong>When should we use AssumeRole?</strong></h4><ol><li>When you don’t want to grant direct resource permissions to an IAM User, instead use this AssumeRole API, the IAM User will be able to access the resources only by assuming the role.</li><li>If your IAM User already have access to three services and you want to grant him access to a few more critical permissions like —<br> — Terminating EC2,<br> — Reboot RDS, etc, <br>So you won’t like to grant these critical permissions to it directly instead you would prefer that the IAM User should be able to access those permissions more securely with temporary access by assuming the Role.</li></ol><p>3. AssumeRole can we use within the same account &amp; cross-account access.</p><h4><strong>Make it more secure using MFA:</strong></h4><p>We can also enable the MFA in all APIs so that the IAM User needs to configure MFA at the User level and pass a valid MFA code while requesting the temporary credentials.</p><h4><strong>Best practice:</strong></h4><blockquote>If we create AWS resources from inside the AWS network like via AWS Pipeline, or Codebuild, etc.</blockquote><blockquote>OR</blockquote><blockquote>If we need to access resources like S3, SNS, SQS, SES, etc, from other services like — Lambda, EC2, Containers etc.</blockquote><blockquote>Then, it’s a best practice to use <strong>AWS IAM Role</strong> with required permissions instead of using AWS Access &amp; Secret Keys.</blockquote><p>You can also use the shell script from <a href="https://gist.github.com/mohd-afzal-vs/f3045d02d2e5e93aa683d0d4635ea0db">Gist</a> to generate and set up the temporary credentials instead of invoking the API command and exporting variables manually.</p><p>For more details, check out the AWS official documentation.</p><p><a href="https://docs.aws.amazon.com/STS/latest/APIReference/welcome.html">Welcome to the AWS Security Token Service API Reference</a></p><p>We can also use AWS SDK for AssumeRole API, available for Programming languages. Check <strong>See Also</strong> section.</p><p><a href="https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html">AssumeRole</a></p><p>Read About GetSessionToken API:</p><p><a href="https://immohdafzal.medium.com/aws-secure-deployment-access-using-security-token-service-sts-getsessiontoken-api-54253a122052">AWS Secure Deployment &amp; Access using Security Token Service(STS) :GetSessionToken API.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5a9cf36916f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vectoscalar/aws-secure-deployment-access-using-security-token-service-sts-part-1-assumerole-f5a9cf36916f">AWS Secure Deployment &amp; Access using Security Token Service(STS). Part-1 (AssumeRole]</a> was originally published in <a href="https://medium.com/vectoscalar">VectoScalar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create AWS Elastic Beanstalk using Serverless Framework]]></title>
            <link>https://medium.com/vectoscalar/create-aws-elastic-beanstalk-using-serverless-framework-4bf5885a90b6?source=rss-ab922dddaf86------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bf5885a90b6</guid>
            <category><![CDATA[elastic-beanstalk]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[beanstalk]]></category>
            <dc:creator><![CDATA[Mohd Afzal]]></dc:creator>
            <pubDate>Tue, 09 Nov 2021 15:35:59 GMT</pubDate>
            <atom:updated>2022-02-12T12:48:35.974Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*wD1rYcq08LqJ2cAMqkchig.png" /></figure><p>In this article, we will create a demo Elastic Beanstalk application with a dev environment using Serverless Framework</p><p>Elastic Beanstalk according AWS documentation,</p><blockquote>With Elastic Beanstalk, you can quickly deploy and manage applications in the AWS Cloud without having to learn about the infrastructure that runs those applications. Elastic Beanstalk reduces management complexity without restricting choice or control. You simply upload your application, and Elastic Beanstalk automatically handles the details of capacity provisioning, load balancing, scaling, and application health monitoring.</blockquote><p>First of all create a <strong>serverless.yml</strong> file in the root of the project.</p><pre>app: my-app<br>service: my-service</pre><pre>provider:<br>  name: aws<br>  stage: &#39;dev&#39;<br>  region: &#39;ap-south-1&#39;<br>resources:<br>  Resources:<br>    # Create beanstalk app and it&#39;s environment.<br>    BeanstalkApplication:<br>      Type: AWS::ElasticBeanstalk::Application<br>      Properties:<br>        ApplicationName: demo-application<br>        Description: Creating for testing<br>    BeanstalkDevEnv:<br>      Type: AWS::ElasticBeanstalk::Environment<br>      Properties:<br>        ApplicationName:<br>          Ref: BeanstalkApplication<br>        EnvironmentName: demo-env-dev<br>        Description: Demo dev environment<br>        SolutionStackName: &#39;64bit Amazon Linux 2 v5.4.4 running Node.js 14&#39;<br>        Tier:<br>          Name: WebServer<br>          Type: Standard<br>          Version: &#39; &#39;<br>        OptionSettings:<br>          - Namespace: aws:elasticbeanstalk:environment<br>            OptionName: EnvironmentType<br>            Value: SingleInstance<br>          - Namespace: aws:autoscaling:launchconfiguration<br>            OptionName: InstanceType<br>            Value: t2.micro<br>          - Namespace: aws:ec2:vpc<br>            OptionName: Subnets<br>            Value: !Join<br>              - &#39;,&#39;<br>              - - &lt;&lt;public-subnet-id-1&gt;&gt;<br>                - &lt;&lt;public-subnet-id-2&gt;&gt;<br>          - Namespace: aws:autoscaling:launchconfiguration<br>            OptionName: IamInstanceProfile<br>            Value: aws-elasticbeanstalk-ec2-role<br>          - Namespace: aws:elasticbeanstalk:environment<br>            OptionName: ServiceRole<br>            Value: aws-elasticbeanstalk-service-role<br>          - Namespace: aws:ec2:vpc<br>            OptionName: VPCId<br>            Value: &lt;&lt;vpc-id&gt;&gt;<br>          - Namespace: aws:elasticbeanstalk:application:environment<br>            OptionName: DATABASE_PASSWORD<br>            Value: &lt;&lt;database-password-value-here&gt;&gt;<br>          - Namespace: aws:elasticbeanstalk:application:environment<br>            OptionName: DATABASE_USER<br>            Value: &lt;&lt;database-user-value-here&gt;&gt;<br>          - Namespace: aws:elasticbeanstalk:application:environment<br>            OptionName: ENV_NAME<br>            Value: ${self:provider.stage}<br>        Tags:<br>          - Key: environment<br>            Value: ${self:provider.stage}</pre><p><strong>Note: </strong>The indentation should be proper of the yml file otherwise Serverless gives error while start deployment.</p><p>Few settings defination from above script.</p><ol><li><strong>provider:</strong> This section contains information for the provider name (aws, azure etc) and region and we can also define the common settings here like environment variables, role, stack-name, api-name memory, timeout etc.</li><li><strong>BeanstalkApplication:</strong> This is a custom logical name, we are defining a Beanstalk application, in properties section, providing application name &amp; description.</li><li><strong>BeanstalkDevEnv:</strong> This is a custom logical name, we are defining a Beanstalk environment, in properties section,</li><li><strong>ApplicationName:</strong> Define a mapping between this environment and the Beanstalk app.</li><li><strong>EnvironmentName:</strong> Provide a name for the environment.</li><li><strong>SolutionStackName:</strong> Provide the platform information in this section, for this demo app we are choosing a NodeJS platform. <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html">Check the available stack names &amp; platforms.</a></li><li><strong>OptionSettings:</strong> In this section, we are defining the environment specific settings like VPC configugarion, setting environment variables, EC2 machine size for environment, etc.</li><li><strong>aws:elasticbeanstalk:environment:</strong> This is a namespace and it has various options like environment type (single-instance or load-balanced), service role for the Beanstalk environment, etc.</li><li><strong>aws:autoscaling:launchconfiguration:</strong> This namespace has various options like instance type/size (t2.micro, t3.small etc), IAM instance profile role for EC2, etc.</li><li><strong>aws:ec2:vpc:</strong> This namespace is using for configuring the VPC related settings like which VPC &amp; what subnets will associate with environment. For single-instance type environment add the public subnets in configuration.</li><li><strong>aws:elasticbeanstalk:application:environment:</strong> Using this namespace we can define the environment variables and their values for Beanstalk environment.</li><li><strong>Tags:</strong> We can define the custom tags.</li></ol><blockquote>Replace all the values under <strong>&lt;&lt;&gt;&gt; </strong>symbols in the above script according your account.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bf5885a90b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vectoscalar/create-aws-elastic-beanstalk-using-serverless-framework-4bf5885a90b6">Create AWS Elastic Beanstalk using Serverless Framework</a> was originally published in <a href="https://medium.com/vectoscalar">VectoScalar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use CloudFront for API Gateway & S3 both]]></title>
            <link>https://medium.com/vectoscalar/use-cloudfront-for-api-gateway-s3-both-cc0e30e0962a?source=rss-ab922dddaf86------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc0e30e0962a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[distribution]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Mohd Afzal]]></dc:creator>
            <pubDate>Tue, 09 Nov 2021 10:38:09 GMT</pubDate>
            <atom:updated>2022-02-12T12:49:07.846Z</atom:updated>
            <content:encoded><![CDATA[<h3>Use CloudFront for API Gateway &amp; S3</h3><p>When we set up a cloud-based web application using CloudFront &amp; S3 with serverless backend using API Gateway and Lambda. Then, AWS provides a default domain for your CloudFront distribution like <em>xyz.cloudfront.net </em>that you can either directly use or use as a CNAME in your purchased domain. Similarly, API Gateway also provides an API endpoint that we can use to access our backend APIs.</p><p>But, sometimes it feels weird to use the two domains first CloudFront domain for web app and second API Gateway domain for backend APIs whereas we should use only one domain for both.</p><blockquote>If you are using a path parameter <strong>/api/ </strong>or<strong> something else </strong>in each APIs that you can use to identify the APIs in web URL like</blockquote><blockquote>https://example.com/api/users</blockquote><blockquote><a href="https://example.com/api/posts">https://example.com/api/posts</a></blockquote><blockquote><a href="https://example.com/api/posts">https://example.com/api/posts</a>?post=1&amp;status=active</blockquote><blockquote><strong>Then yes, we can use a single domain to access the web app and APIs.</strong></blockquote><p>We can use the same CloudFront domain (or custom domain if you are using your purchased domain as CNAME for CloudFront) to access the web app and APIs both. To achieve this we will have to configure our CloudFront distribution settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*whNX4Q2fyf7YlMDZN0p0mw.png" /></figure><p>Creating a new API Gateway &amp; CloudFront is out of this post, if you wish to create a new please follow the below official document.</p><ul><li><a href="https://aws.amazon.com/cloudfront/getting-started/S3/">Content Delivery Network Tutorials | CDN, Setting up Amazon S3 Distribution| Amazon CloudFront</a></li><li><a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html">Tutorial: Build a Hello World REST API with Lambda proxy integration</a></li></ul><p>Let’s start now, login into your AWS account and go to the API Gateway console and click on your API name then click on the sidebar option <strong>Stages</strong> and if you have stages created click on stage name then copy the <strong>Invoke URL</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGiSf2KYPU9d6qB-2K1WQg.png" /></figure><p>Now, go to the CloudFront console and click on your distribution name once the distribution settings are opened then click on the <strong>Origins</strong> tab and click on <strong>Create origin</strong> then a screen will open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*niOVGMh0BaUBEegIiGyS0A.png" /></figure><p><strong>Origin domain</strong>: In this field just paste the copied API Gateway invoke URL. Then, AWS will auto-fill the other fields based on your pasted URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*h6j-MgfS7vaNBNFWr0CzgQ.png" /></figure><p>If you want you can give a name to this custom origin in the <strong>Name</strong> field. Then click on <strong>Create origin</strong> button.</p><p>Now, go to another tab named <strong>Behaviors</strong> and create a new behavior and fill the below option with correct values.</p><p><strong>Path pattern:</strong> Enter the path parameter that CloudFront can use to identify the APIs and redirect all requests to the API Gateway, let say if you are using the <strong>/api/</strong> then enter the <strong>/api/*</strong> in this field, <strong>*</strong> will you for all further query string/params.</p><blockquote>Now, CloudFront will redirect all the requests to API Gateway that includes the <strong>/api/</strong> in CloudFront URL.</blockquote><p><strong>Origin and origin groups:</strong> Select the origin name that we have recently created.</p><p><strong>Compress objects automatically:</strong> Yes.</p><p><strong>Viewer protocol policy:</strong> HTTPS only.</p><p><strong>Allowed HTTP methods:</strong> GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE.</p><p><strong>Restrict viewer access:</strong> No.</p><p><strong>Cache key and origin requests:</strong></p><p>— Choose the <strong><em>Cache policy and origin request policy (recommended) </em></strong>and in the <strong><em>Cache policy</em></strong> options list choose the <strong>CachingDisabled</strong> option.</p><blockquote>We are disabling the cache to not cache the API response otherwise when you will deploy a new change to your API, then CloudFront will still return the previous cached result. And you have to invalidate the cache.</blockquote><p>All required fields are filled just click on <strong>Save changes</strong>. Now, you can use the same CloudFront URL to access all your APIs.</p><p><strong>With API Gateway:</strong></p><p><a href="https://awnhlvqlxi.execute-api.us-east-1.amazonaws.com/test">https://test.execute-api.us-east-1.amazonaws.com/test</a>/api/users</p><p><a href="https://awnhlvqlxi.execute-api.us-east-1.amazonaws.com/test">https://test.execute-api.us-east-1.amazonaws.com/test</a>/api/posts</p><p><a href="https://awnhlvqlxi.execute-api.us-east-1.amazonaws.com/test">https://test.execute-api.us-east-1.amazonaws.com/test</a>/api/posts?post=1&amp;status=active</p><p><strong>With CloudFront:</strong></p><p><a href="https://xyz.cloudfront.net/api/users">https://xyz.cloudfront.net</a> [Web app home]</p><p><a href="https://xyz.cloudfront.net/api/users">https://xyz.cloudfront.net/api/users</a> [Users API]</p><p><a href="https://xyz.cloudfront.net/api/users">https://xyz.cloudfront.net/api/p</a>osts [Posts API]</p><p><a href="https://xyz.cloudfront.net/api/users">https://xyz.cloudfront.net/api/p</a>osts?post=1&amp;status=active [Posts API with params]</p><blockquote>Now, CloudFront will redirect all your request to the API Gateway that has the <strong>/api/</strong> in URL.</blockquote><blockquote><strong>Did you notice one thing here, now you don’t need to use the “stage name” in your API request URL as you were using in API Gateway request URL like “/test” or “/prod” etc.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc0e30e0962a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vectoscalar/use-cloudfront-for-api-gateway-s3-both-cc0e30e0962a">Use CloudFront for API Gateway &amp; S3 both</a> was originally published in <a href="https://medium.com/vectoscalar">VectoScalar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access Secrets-Manager values in Serverless Framework script.]]></title>
            <link>https://medium.com/vectoscalar/access-secrets-manager-values-in-serverless-framework-script-4eb6361f3c50?source=rss-ab922dddaf86------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eb6361f3c50</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-secrets-manager]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <dc:creator><![CDATA[Mohd Afzal]]></dc:creator>
            <pubDate>Tue, 07 Sep 2021 09:10:57 GMT</pubDate>
            <atom:updated>2022-02-12T12:49:09.254Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*4NqZ_XKme1xP1v7d4_QE3w.png" /></figure><p>While deploying the application using the Serverless script, we want to access some confidential values like- AWS &amp; encryption/decryption keys, Database details, etc which we don’t want to expose or commit into the codebase.</p><p>To achieve this, we will use the AWS JavaScript SDK to access the Secrets-Manager service.</p><blockquote>Install the aws-sdk using <a href="https://www.npmjs.com/package/aws-sdk">npm</a>.</blockquote><p>Let’s get started. First, create a <strong>secrets.js</strong> file in the root of your project. [Or at any other place you want to create]. Add the below code in this file.</p><pre>const AWS = require(&quot;aws-sdk&quot;);</pre><pre>// Create a Secrets Manager client<br>const client = new AWS.SecretsManager({<br>    region: &#39;your_aws_region&#39;<br>});</pre><pre>const getAllSecret = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        let secrets = {};<br>        const secretName = &#39;&lt;your_aws_secret_manager_name&gt;&#39;;<br>        client.getSecretValue({ SecretId: secretName }, function (err, data) {<br>            if (err) {<br>                console.error(&#39;getAllSecret - error: &#39;, err);<br>                reject(err);<br>            }<br>            else {<br>                // Depending on whether the secret is a string or binary, one of these fields will be populated.<br>                if (&#39;SecretString&#39; in data) {<br>                    secrets = data.SecretString;<br>                }<br>                else {<br>                    let buff = new Buffer(data.SecretBinary, &#39;base64&#39;);<br>                    secrets = buff.toString(&#39;ascii&#39;);<br>                }<br>                secrets = JSON.parse(secrets);<br>                resolve(secrets);<br>            }<br>        });<br>    });<br>};</pre><pre>module.exports.getSecrets = async () =&gt; {<br>    const keys = await getAllSecret();<br>    return {<br>        DB_HOSTNAME: keys.DB_HOSTNAME,<br>        DB_USERNAME: keys.DB_USERNAME,<br>        DB_PASSWORD: keys.DB_PASSWORD,<br>        DB_PORT:     keys.DB_PORT<br>    }<br>}</pre><p>In above code:</p><ol><li>Firstly, we have imported the AWS SDK.</li><li>Created an object of Secrets-Manager service.</li><li>Define a <strong>getAllSecret()</strong> function that will use the Secrets-Manager’s <strong>getSecretValue()</strong> function to get the secrets and it takes the secret name [which you have created in AWS Console] as parameter.</li><li>Once the secrets are received, parse them and resolve the promise.</li><li>We put this function inside <strong>Promise</strong>, so that we can invoke it using the async/await pattern.</li><li>At end, we have exported a function called <strong>getSecrets</strong>. It will invoke the <strong>getAllSecret() </strong>and map the result in key-value pairs.</li></ol><p>Now, create a <strong>serverless.yml</strong> file in the root of the project.</p><pre>app: my-app<br>service: my-service<br>custom:<br>  SECRETS: ${file(./secrets.js):getSecrets}<br>provider:<br>  name: aws<br>  runtime: nodejs14.x<br>functions:<br>  my-function:<br>    name: my-lambda-function<br>    handler: index.handler<br>    description: Test lambda<br>    memorySize: 128<br>    timeout: 30<br>    environment:<br>      DB_HOSTNAME: ${self:custom.SECRETS.DB_HOSTNAME}<br>      DB_USERNAME: ${self:custom.SECRETS.DB_USERNAME}<br>      DB_PASSWORD: ${self:custom.SECRETS.DB_PASSWORD}<br>      DB_PORT: ${self:custom.SECRETS.DB_PORT}</pre><p><strong>Note: </strong>The indentation should be proper of the yml file otherwise Serverless gives error while start deployment.</p><p>It is a simple serverless.yml script that deploy a lambda function. [<em>we made it simple for example purpose</em>]</p><p>But, few things, need to be note there are:</p><ol><li>Inside the <strong>custom</strong> section of the above script, we have defined a custom variable called <strong>SECRETS</strong> and we have passed the path of our <strong>secrets.js </strong>to<strong> </strong>Serverless <strong>${file()}</strong> function. Please make sure file path should be correct.</li><li>Using it, Serverless will include the JavaScript file and we can invoke the exported <strong>getSecrets()</strong> function on the same [this function is accessible because we have exported it] using <strong>:</strong> symbol in Serverless script.</li><li>No need to worry about async <strong>getSecrets()</strong> function invocation, Serverless will take care of it before starting the deployment and the coming result will assign to <strong>SECRETS</strong> custom variable.</li><li>Now, we can use those received secrets from Secrets-Manager and assign their values to the lambda’s environment variables.</li><li>The syntax/way of using the custom variables in script is:</li></ol><pre>${self:custom.SECRETS.DB_HOSTNAME}</pre><blockquote><strong>self:</strong> Refers to the <strong>current</strong> script.</blockquote><blockquote><strong>custom:</strong> Refers to the <strong>custom</strong> section of the script.</blockquote><blockquote><strong>SECRETS:</strong> Refers to the <strong>SECRETS</strong> variable in the custom section.</blockquote><blockquote><strong>DB_HOSTNAME:</strong> Refers to the <strong>key</strong> name that we have mapped with the coming value from the AWS Secrets-Manager.</blockquote><p><strong>Note: </strong>Your <strong>IAM</strong> user that you will use to deploy the script should have atleast the following permissions to access the AWS Secrets-Manager.</p><blockquote>secretsmanager:GetSecretValue</blockquote><blockquote>secretsmanager:DescribeSecret</blockquote><blockquote>secretsmanager:ListSecrets</blockquote><p>That’s it, we have done here, now just go ahead and deploy your Serverless script and you should see the AWS Secrets-Manager values are assigned to your lambda’s environment variables.</p><p>To create the secret in Secrets-Manager, please refer to the official AWS documentation: <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/tutorials_basic.html#tutorial-basic-step1">https://docs.aws.amazon.com/secretsmanager/latest/userguide/tutorials_basic.html#tutorial-basic-step1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eb6361f3c50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vectoscalar/access-secrets-manager-values-in-serverless-framework-script-4eb6361f3c50">Access Secrets-Manager values in Serverless Framework script.</a> was originally published in <a href="https://medium.com/vectoscalar">VectoScalar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>