# Aim

## All content published is intended as Linux Primer for IT professionals with a special focus for Security Professionals


# History

Linux was created by Linus Torvalds. The main component of Linux after which it is named is the kernel i.e., Linux Kernel. Initially, Torvalds wanted to call the kernel as *Freax (to resemble Unix-like),* but his friend suggested the name as Linux.

Linux was given as open-source project with minimal distribution for hobbyists&#x20;

Linus holds the "Linux" trademark to monitor its use. He has the highest contribution in writing of Linux kernel. He is the main person which is responsible for committing changes onto the standard Linux kernel.

As per Wikipedia, the Linux Foundation currently sponsors Torvalds so he can work full-time on improving Linux.

There are mainly three family of distributions:

* Debian family of Distributions - Ubuntu, Kali, and ParrotOS
* RPM family of Distributions - Fedora, CentOS, and RedHat
* ARCH family of Distributions - ARCH, Alpine and CRUX


# Components of Linux OS

Linux is made up of the following components:

* BootLoader - It is the first thing that runs on startup
* Linux Kernel - Explained on next page
* Background Services - such as networking services
* OS Shell (also known as Terminal) - way to interact with OS with the help of commands&#x20;
  1. sh - short form of Shell. Had major limitations like typing commands again if user makes a mistake while typing.
  2. bash (Bourne Again Shell ) - default shell in most distros
  3. ash and dash (Debian Almquist Shell) - lightweight clones of sh shell
  4. zsh (Z shell) - Better than bash. Default on Kali Linux
  5. csh (Cshell) & Tcsh - Allow for use of C++ syntax for scripting.
  6. ksh (Korn shell)
  7. rbash (Restricted bash)
* Graphics Server (X) - The service responsible for GUI and Desktop Environment (XFCE, KDE, GNOME) which actually uses this service. i.e. Graphical server is the middleware between desktop environment to pass the user input captured by desktop environment to the operating systems.
* Applications.
* File System - Linux OS uses Filesystem Hierarchy Standard (FHS) and the hierarchy is as follows:

  1. Volumes - Partitions on physical or virtual storage devices. (usually the best practice is to keep the OS and user data on separate volumes). Volumes are usually mounted (way to connect and interact on the same) which are then presented as directories known as mount points.
  2. Directories - Unlike Windows OS, these are just files which show the indexing of file within.
  3. Files - Actual building block. In Linux everything is just like a file. Note that hidden files are usually indicated as .\<filename> or dot files

  Note: A disk’s file system has a number of control blocks called *inodes (index nodes).* These are basically metadata that describe the details of files and other objects, including where on the disk any associated data is stored. Entries in a Linux directory associate a name, with an inode number. As per [this ](https://www.site24x7.com/learn/linux/inode.html)site,&#x20;

> On a Linux system, files are stored in the form of blocks of a certain size. If a file is larger than this predetermined size, it’s broken down into chunks and stored in empty blocks wherever they’re available on the disk. With an increase in the number of files, this can easily get confusing. Inodes help the system organize data

* [x] Overview of FHS Structure

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FhmxYwdrTXqsk2N3ORhPS%2FDirectory-Filesystem-Hierarchy-Standard.avif?alt=media&amp;token=994e489c-8196-42a6-93e3-3cc58dc38be3" alt=""><figcaption><p>Source: <a href="https://linuxconfig.org/wp-content/uploads/2013/03/Directory-Filesystem-Hierarchy-Standard.avif">https://linuxconfig.org/wp-content/uploads/2013/03/Directory-Filesystem-Hierarchy-Standard.avif</a></p></figcaption></figure>

Note: /dev which is a short-hand notation for devices as it usually contains drivers and /var which contains variable files is because the files inside /var are constantly changing


# Linux Kernel

Linux is the core of the Operating system i.e., it is the kernel. It is the closest thing that runs to the underling hardware such as CPU, Memory and I/O devices i.e.&#x20;

• It controls CPU&#x20;

• It controls Memory&#x20;

• It controls Devices

![](https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Fiyd9tuSz6dBbCeSWJ0C0%2Fimage.png?alt=media\&token=e42a7015-593d-424a-a2f6-ab818a25e0d5)

Note it is possible to change the Linux Kernel i.e., basically one can install or update the Linux kernel since it is open source, but the same cannot be done with Windows since NT kernel is closed source.


# Linux Commands

This page sheds light on commands which may not be known to newbies of Linux OS

Just like apt (the package manager) is used to install services, "apt purge" can be used to remove the same.

> **If a space is typed before the command, the bash history won’t log it.**

> Recursive search on the bash history enables. On Pressing Ctrl+R, the prompt enters into\
> reverse search mode. Typing any character makes the search to suggest commands from the history. The user needs to press ENTER once the desired command is found.

### nl

Just like cat command is used to display the contents of the file, if suppose line number is also required against the content, then nl is the command for it

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FYWaLPXwcj6uCDjTi99gp%2Fimage.png?alt=media&amp;token=5c79baa8-ccd6-4ad5-9243-f4a60bc9d65c" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
cat /dev/null > filename is used to empty a given file
{% endhint %}

### tac

It is simply reverse of cat.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FUF0z3YAJYEDlcGr7X4x3%2Fimage.png?alt=media&amp;token=48e8203f-0475-4bd9-bb90-19d1b4966556" alt=""><figcaption></figcaption></figure>

### bat

One needs to install it using apt. In Debian based distros, it is executed as batcat. To put it simply, bat is like cat but on steroids. It has nl like feature which shows about line number and it also, formats text in nice and readable manner. It is especially useful for reading scripts and code based files.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FNxHZdRk2LJugAb2eWWCF%2Fimage.png?alt=media&amp;token=a0951966-feb6-446f-b99f-5a17546de5fb" alt=""><figcaption></figcaption></figure>

### Wildcards

?, \*, \[], \[!] are some of the wildcards that can be used in linux. The ? wildcard represents one character, the \* represents any number of characters, the list of characters contained in the \[] represents one character, but the character must be a member of the list, and the list of characters contained in \[!] represents one character, but the character cannot be a member of the list.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FcJ268N0nMmVdIMU8cyow%2Fimage.png?alt=media&amp;token=f0da81b4-56f1-4e58-9127-7d6002cafe59" alt=""><figcaption></figcaption></figure>

### sort and uniq

As per help section, sort has the following options:

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F2NHenJSigJLg4nBe0XCZ%2Fimage.png?alt=media&amp;token=14651562-c70e-471a-9db0-37d73e01e5b5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F1568WVJBmewCxSCIpgrr%2Fimage.png?alt=media&amp;token=da78ceb5-1e2a-42a4-a3c0-3e5c177b2072" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FoxXQXBGfbG7vQbo3Jisw%2Fimage.png?alt=media&amp;token=ac170eea-36a7-49d4-8d1b-1fcd883b120d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FNBEUJxTuxPCvttX7otaI%2Fimage.png?alt=media&amp;token=270f2b2a-022f-4bb6-bf30-3e23b0129f97" alt=""><figcaption></figcaption></figure>

Uniq is useful for finding unique entries in a set of data

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Fxu7euRujeQSlcosRQ87o%2Fimage.png?alt=media&amp;token=90a4b76f-9e76-4cf7-830e-08213010637c" alt=""><figcaption></figcaption></figure>

One of the use cases can be used to find unique entries in your history. So for example, history command. First get rid of the history line item number using awk and then to place identical commands together, we can sort it and then we can get a unique count and lastly we can get that output in descending order using sort -nr&#x20;

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Fkl5x4Zqde0yuR4RQWcNf%2Fimage.png?alt=media&amp;token=0289836e-2083-424d-a0d6-183789b34a67" alt=""><figcaption></figcaption></figure>

### who, w and last

who is the command which is equivalent of "query user" or "qwinsta" in Windows, which basically tells the currently logged in users. Similarly, last is used to check the last logged on users, basically the login history. Lastly w tells the same information as who but with more details.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FCSb9fJl6Om6jVxqlRTkB%2Fimage.png?alt=media&amp;token=8af9a32b-5f0b-4a88-857b-b18664527310" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note, in Debian/Ubuntu login logs (equivalent of WIndows Event Viewer -> Security Logs) are stored in information is stored in /var/log/auth.log, while for Redhat/CentOS, it is stored in /var/log/secure and for Debian/Ubuntu system logs (equivalent of WIndows Event Viewer -> System Logs) are stored at /var/log/syslog while for RHEL/CentOS machine, the output is stored in /var/log/messages
{% endhint %}

{% hint style="info" %}
Note: A user in sudoers group can switch to profile of other user . Command is: sudo su - \<username>
{% endhint %}

{% hint style="info" %}
To check which user is in sudoers group, one can simply do a \
cat /etc/group | grep sudo\
\
However there is a separate file called as /etc/sudoers for check information as shown below:\
\
![](https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FBWL8FXnErkorHZTz62wM%2Fimage.png?alt=media\&token=a12c2fcb-8055-494b-b9c2-444f8545d325)
{% endhint %}

{% hint style="info" %}
In Fedora Distributions, the sudoers group is called wheel
{% endhint %}

### cut

The cut command helps to extract data from input with the help of a delimiter and determining whether to cut by byte position, field, or character.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FuunGmF91AFaz7TO2FVov%2Fimage.png?alt=media&amp;token=14f71cf1-2dab-469d-ac50-dbaac8cdb345" alt=""><figcaption></figcaption></figure>

-d " " is used for delimiting and -f1 or f2 is used for selecting column

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FZcz2jHCqcNXeVJcsVqL6%2Fimage.png?alt=media&amp;token=ab098a60-75b3-4a1d-815e-86d97a8a7140" alt=""><figcaption></figcaption></figure>

### xargs

Xargs is an utility that can simplify the processing of complex operations, repetitive tasks, batch processing, and large data manipulation. Xargs reads data from stdin, and then executes the command supplied to it as an argument. By default, xargs reads data separated by blanks because it treats spaces as delimiter, and then executes a command once for each argument. Note that blank lines are ignored.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Fud13ForxYFnq4qAfv7Xt%2Fimage.png?alt=media&amp;token=36f1929f-33bf-4243-8dc0-241a82ab4e73" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FwmHqAXeB0CqNVNojOa4e%2Fimage.png?alt=media&amp;token=9f93409e-4c17-425e-a387-3887f34afbee" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FoDpLd2UuqdjnAH6sJpDJ%2Fimage.png?alt=media&amp;token=4bbc1aaa-d789-4a8b-b1c7-d0fac66e469c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FhBGdAtwnNC0RA66TuzLH%2Fimage.png?alt=media&amp;token=81a3084f-5188-4605-b8ad-b49aa659d98d" alt=""><figcaption></figcaption></figure>

### test, expr and let

These commands can use the following operands:

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F8FSJcWEVzZdwxEzkdIhG%2Fimage.png?alt=media&amp;token=fdefb1fa-f4d2-455a-8e74-952bc7d75039" alt=""><figcaption></figcaption></figure>

*test* is used to check file types and compare values and returns true or false. Another way to use test is to use the construct `[...]`

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FLt9DGoYRMJO1fLoP2x8G%2Fimage.png?alt=media&amp;token=3ef13e05-868f-4468-9181-edbdb25bd8aa" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note that test would return 0 if true and 1 if false. this can be demonstrated using echo $? which tells the op of last command

![](https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FLqyV4Tp4xkQDK1rABz9o%2Fimage.png?alt=media\&token=f01acd3a-abd5-4bb8-bc36-a002d00628fc)
{% endhint %}

*expr* command evaluates arithmetic or string expressions and sends the result to stdout. When one use the *expr* command to perform multiplication in an expression, one must use a backslash as an escape character before the multiplication operator, as the *\** character is recognized by the shell as a special character. This is as shown below. The construct for expr is `$((...))`

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FMTVl4JjPSrZCI3dOMWKh%2Fimage.png?alt=media&amp;token=9e6ea00d-1f62-4432-a25b-34a08d29604e" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note, to substitute a variable, use $variable-name
{% endhint %}

*let* command is equivalent to enclosing an arithmetic expression in double parentheses. The construct for *let* is `((...))`

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FlK9zMpnddNapZEzX6iiH%2Fimage.png?alt=media&amp;token=667c3dc0-ea1f-4ee8-9a33-dc322f170db3" alt=""><figcaption></figcaption></figure>

### tree

This is equivalent of the following command but displays files in form of branches of a tree:

```bash
ls -R 
```

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FIuBmGUm6w3zmavKcfpZ0%2Fimage.png?alt=media&amp;token=e80d3285-2460-4f6e-9bc2-9df452df8d72" alt=""><figcaption></figcaption></figure>

### ln

It is used for creating hard links and symlinks (soft links) in linux.&#x20;

Note: Symlinks are file-system objects used for creating symbolic links which are just pointers pointing to a file or directory, where as Hard links creates a direct association with the target file by acting as its mirror (because a hard link creates an alias, or an *associated* name with the same inode number)

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F9Ivgjh1WYJTRBFWpx1Pk%2Fimage.png?alt=media&amp;token=368e59ad-9931-420b-83c7-543600396878" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note, to revoke permissions in linux, one can simply use chmod with zero i.e., chmod 700 will only take permissions from group and others and will keep rwx with owner.
{% endhint %}

### head and tail

head lets user view only the top 10 lines of data in a file. one can also pass the argument n to mention how much lines should the head command display. tail is the exact opposite which displays the last 10 lines of a file.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FPS4ADS1uCIKAicBbfRqF%2Fimage.png?alt=media&amp;token=1ab44304-5b05-440d-9ba8-fca595cf40a7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F6c1AtAG3Ef3IPYyGs64U%2Fimage.png?alt=media&amp;token=ebdaf56c-14e8-4579-9633-bb91ab495afb" alt=""><figcaption></figcaption></figure>

### wc

wc or word count simply tells the number of lines, word count, byte and characters count

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F5oHzEg5SbOLFnXLomK9W%2Fimage.png?alt=media&amp;token=10101efd-6b20-4ab9-b2ca-123ef9aa5d47" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FLAjfAVGT5YWKF6FWbR0O%2Fimage.png?alt=media&amp;token=b6658fb2-48b5-40a0-a913-fdf191f7f348" alt=""><figcaption></figcaption></figure>

### more and less

These are cat-like commands with a scrollbar to avoid displaying the entire file at once.   Both the command can be used to read the contents of a text file one page (one screen) at a time. This askubuntu [ans ](https://askubuntu.com/questions/1191862/what-is-the-difference-between-more-and-less-commands)summarizes the commands very easily:

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FRZGqObnPkxVjttTAZ9Fg%2Fimage.png?alt=media&amp;token=5e7e117b-c310-4c44-81a2-f7659ba0c200" alt=""><figcaption></figcaption></figure>

### diff

This is used to compare two files.&#x20;

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FCUQERUmMhdl9U5D4h71U%2Fimage.png?alt=media&amp;token=7087c4e3-2c19-4f51-aa2e-8b333392ac90" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note: zless and zdiff are basically commands used to the same operations as less and diff but for files in an compressed archive.
{% endhint %}

### which and whereis

which is a tool for locating the path to a command while whereis also does the same but also returns the location of manpage

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FLsKW3hwm9GQT1Hw7sQjZ%2Fimage.png?alt=media&amp;token=4c39c722-0888-46ca-a1b8-31149de1b977" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FtB5e8Xr7qMSNX3V0u8zm%2Fimage.png?alt=media&amp;token=851fe1eb-5b0c-4a68-8fc5-84567989bec0" alt=""><figcaption></figcaption></figure>

### locate and find

locate and find - both are used to search a file by its name. The key difference is that locate uses a previously built database while file searches in the filesystem. While locate is faster, find is more aggressive with options such as -name, -type and -exec

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Fqt56nzPPGBaa5RFplGwk%2Fimage.png?alt=media&amp;token=6e277fc2-76bf-49af-9be7-cd0e8d13ece2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F6Z0oaDEhhCPOaoSzZDcE%2Fimage.png?alt=media&amp;token=6535d458-7666-4671-b07b-0e7d7c693c7d" alt=""><figcaption></figcaption></figure>

### file

It is used to know more about the type of file to the user. please note that file commands reports on the basis of the contents inside the file and not based on file extension.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F3poai0xJiqt88rSOmqjA%2Fimage.png?alt=media&amp;token=2c6fba76-283a-4513-a812-6b552f9bfb6b" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Just like the Sysinternals utility strings64.exe, in linux, there is a command called as strings which dumps printable character sequences in any file regardless of its type
{% endhint %}

### apropos

This command is used to find other commands based on the keyword that has been passed as an argument

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F9WEywLRtkw8MRNwgmrXa%2Fimage.png?alt=media&amp;token=7c8cd7bf-aca4-4235-817f-390199e0400f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Fzc08xEF8y0NHgz4iqC7l%2Fimage.png?alt=media&amp;token=1d62485a-be7e-4d49-9fd2-e11bc75adf98" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
sha1sum /bin/bash gives sha1 hash

md5sum /bin/bash gives md5 hash
{% endhint %}

### top, htop, atop, and iotop

top is similar to task manager of windows i.e., to see the running processes. htop unlike top is interactive process viewer with functionality such as searching, tree view and capability to use a mouse with it

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FibKHXJYEmXPl6EZWPQit%2Fimage.png?alt=media&amp;token=3416c91c-a9f3-4e91-b3b6-7a7bd4fd069e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FxjUYHSawSs77rBKGqduz%2Fimage.png?alt=media&amp;token=cb9e35e2-c486-4c25-ba2c-2489cbb0a87b" alt=""><figcaption></figcaption></figure>

atop

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F0IxtCC9EdoGQ9gFp1jUF%2Fimage.png?alt=media&amp;token=f5153685-e434-4222-9ca7-d65c38ca268f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Fs1xvhJpIU1h2iQC7vFqn%2Fimage.png?alt=media&amp;token=aaa3d226-3e2c-459f-bb0e-353d29d0f866" alt=""><figcaption></figcaption></figure>

iotop

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FsqFeLGoG6Qx5Kjz0g6KE%2Fimage.png?alt=media&amp;token=6d448b45-e0ac-4bbf-b2ee-d8518ab125e1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FXvGVwt3uF5PqMgsWjOV0%2Fimage.png?alt=media&amp;token=3b7832ba-a9b4-4f34-97d7-739723f9a270" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
ps lists a snapshot of the running processes. By default, it only shows processes owned by the user executing the command. The -a flag shows processes of all owners. The -u flag provides verbose o/p. The -x flag includes processes i.e., services started by the host on startup.
{% endhint %}

### ss

To list running services, one can use the ss command

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F3UmBYfiYTASUnD5XUkqc%2Fimage.png?alt=media&amp;token=6b97b93e-92a4-4a79-9dd9-6e83d60c68fb" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FADjOZfhvv1ZDqLMIn6mA%2Fimage.png?alt=media&amp;token=ebda7b5f-27d4-41c9-8c74-64272c5e62b5" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**useradd, usermod** and **userdel** are used for creating, modifying and deleting a user.
{% endhint %}

### lsof

lsof command stands for **List Open Files.** Since Linux sees every object as a file, such as devices, directories, etc., unidentified open files prevent users from modifying them.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FwZseyLNIi43nyDrXyDjU%2Fimage.png?alt=media&amp;token=e23ad01c-5952-4fa7-b6c8-e1adafa601dd" alt=""><figcaption></figcaption></figure>

### sed

It is stream editor. It brings the contents of a file into a stream, where modification operations such as text substitution or other text manipulation operations like insert, delete, search, and more. Please note that it doesn't change the actual file but in the stream. To change in the actual file, one can use re-director (>) to ultimately save the content in new file.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Fi8mS2k1mNp04TH2iaFWB%2Fimage.png?alt=media&amp;token=2c5e57aa-7c29-4b12-a6d7-97b0b1fc4c5f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FDPid2hnDvH5ur0dT2DZ3%2Fimage.png?alt=media&amp;token=c6c784c7-fb4d-4192-97b2-9ba8bbc9cfdc" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FXLSjtT1BhD5qTrzrlPJn%2Fimage.png?alt=media&amp;token=aab7047f-612b-46c2-9bc1-73583332a2e1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FN46vI1uvBxFWidKoMvn1%2Fimage.png?alt=media&amp;token=f691df10-c396-43eb-a448-7c3eba180bc3" alt=""><figcaption></figcaption></figure>

### Redirector&#x20;

{% hint style="info" %}
In the world of Linux and Unix, there is something called as file descriptors. File descriptors are used to represent and manage input and output streams between processes and files, sockets, pipes, and other sources or destinations of data. A file descriptor is a unique non-negative integer that serves as a handle or identifier for an open file or communication channel. At least one file descriptor exists for every open file on the system. When a program asks to open a file — or another data resource, like a network socket — the kernel grants access, creates an entry in the global file table and provides the software with the location of that entry i.e., the global file table has entries pointing to inode number where a particular stream of a file is sent.
{% endhint %}

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FXWV5UtBC0bHTd31WY5NO%2Fimage.png?alt=media&amp;token=59bd0197-1ede-4f64-91ef-7bc6db567608" alt=""><figcaption><p>Source: <a href="https://www.computerhope.com/jargon/f/file-descriptor.htm">https://www.computerhope.com/jargon/f/file-descriptor.htm</a></p></figcaption></figure>

Usually there are two out streams: one is main o/p and one is error. When only > is used, only o/p is redirected to a file or process but when both needs to be redirected, then 2>&1 has to be used

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FigsCeTAfQqyW7jxICkfm%2Fimage.png?alt=media&amp;token=91a6860c-3512-490a-8d09-411c61146065" alt=""><figcaption><p>Source: <a href="https://catonmat.net/bash-one-liners-explained-part-three">https://catonmat.net/bash-one-liners-explained-part-three</a></p></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FW5Bxw579RnwzWIu2qngj%2Fimage.png?alt=media&amp;token=218d92cd-4149-4f1d-9a18-faeef4842609" alt=""><figcaption></figcaption></figure>

### tee

It is used to take the stdin and write to stdout or files. It is similar to Out-File of powershell

example: ps -ef | tee file1&#x20;

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FYIhr80C5ESY7Y0Rk7dBV%2Fimage.png?alt=media&amp;token=fc8e2ffb-8eb6-4fae-9f0a-43ecb311e2a6" alt=""><figcaption></figcaption></figure>

### screen

Use screen to preserve the console output and running tasks in case of connection\
break (mostly useful while working on remote machines).

List the running screen sessions: screen -list

Attach to the screen: screen -r

### gpg and gpgtar

gpg (GNU Privacy Guard) is used for creating encrypted keys and actually encrypting a file. As part of encryption for data at rest, gpgtar is used for encrypting files or directories using tar for compression of the said file.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FSsjZnFCY7bdYYahEQF5I%2Fimage.png?alt=media&amp;token=5027bff0-636f-40db-a5d9-e2f22aece6e9" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F4HJxhQrFDhwWYl4qOSZb%2Fimage.png?alt=media&amp;token=b86083f0-9ca8-49ee-86f9-0527200ace7a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FNwZVBArt0FuwOyUFQGiW%2Fimage.png?alt=media&amp;token=c91725ed-caca-47ac-9aaa-303d276d41f3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FuQo4PtsAuXffKzS0w4xa%2Fimage.png?alt=media&amp;token=597dbcc3-eeb1-45da-b28e-76487c91f0b7" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note, **encfs** is usually used for mounting or creating an encrypted virtual filesystem. **cryptsetup** is used for encryption of entire volume.
{% endhint %}

{% hint style="info" %}
/dev/null - Whatever is written to this file vanishes, and reading from the file outputs nothing. So one can use this file is used to eliminate the standard output or error of a shell command, by redirecting it to this file.

/dev/zero - Upon reading, this file provides an endless stream of zeros and anything written to the file vanishes.
{% endhint %}

### dd, du and df&#x20;

dd is also known as disk/data duplicator. As per manpage, dd can be explained as follows:

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FvxqYU7XUEnPU8mQ5SuIE%2Fimage.png?alt=media&amp;token=084204ff-f002-49d1-bdd9-45b79c444c8d" alt=""><figcaption></figcaption></figure>

```bash
// To take backup of entire disk by copy pasting using dd
dd if=/dev/sda of=/dev/sdb conv=noerror, sync
```

```bash
// Note, because default bs is 512, a 1.5 kb file will take 3 turns to copy as 1.5 kb=512bytes*3
and if we want to copy 1/3 of a file then we can simply provide count=1, so that only 1st default size of 512 bytes is copied, so command can be:

dd if=/etc/shadow of=realdeal count=1
```

du is used to check the space of an entire directory w\.r.t to what size a particular file or subdirectory has taken while df is used to check the overall disk space.

du -sh <--summarize and human readable and du -sh \* <— for all files in current directory and without \* only gives details of the directory

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Fr4q1W7U7Y0RnJ3Mg1WP8%2Fimage.png?alt=media&amp;token=7811d4bc-bbb4-4a4a-817c-d8183bede3fc" alt=""><figcaption></figcaption></figure>

df&#x20;

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FmJmOuk0mY1rUMhNFUjYn%2Fimage.png?alt=media&amp;token=ab3324ab-dbf3-43e0-8f2c-c7655b1ba1d2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Fm3L6rQOBs5u3iVdQQF7Y%2Fimage.png?alt=media&amp;token=770840c6-48d3-4822-aa0c-60b9d4d48b9f" alt=""><figcaption></figcaption></figure>

> To view only the memory stats, one can use free command. It display the amount of free and used memory in the system.
>
> ![](https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FUly1iksQhYFiNxDFFXLM%2Fimage.png?alt=media\&token=6aae4189-59b5-4ba1-b5a9-ae59a40259b0)

### tmux

Also known as terminal multiplexer. This is particularly used to maintain terminal continuity across sessions. So, let's just say, one person is taking ssh and ran a command which will take, let's just 16 hours and in between, the person closed the terminal, so when he/she comes back, the command that was running needs to be re-run because when the session was closed, the command was also mid-way terminated. To solve, this problem, tmux was brought in. The logic is that once ssh access is taken, one needs to start a tmux session in that terminal and type all commands in that tmux, so even if ssh access is closed, ssh session when regained, can access the tmux to continue the work.

<pre class="language-bash"><code class="lang-bash">// For creating a new named session
tmux new -s &#x3C;name-of-session> 

// For attaching to a named session
tmux attach -t &#x3C;name-of-session>

// For copying from a tmux session
Ctrl + b [

// For increasing the scrollback buffer to 2 lac lines
Ctrl +b
: set -g history-limit 200000

// For deteaching a tmux session
Ctrl + b 
d 
OR
Ctrl + b
: detach

<strong>// For listing a tmux session, one can do the following:
</strong><strong>tmux list-sessions
</strong><strong>
</strong><strong>// For killing a tmux session, once you are inside the session
</strong>Ctrl + b
: kill-session 

// For moving up inside a tmux session,
Ctrl + b
[
Use up arrows to go up and down in copy mode and then press q to come back

// For splitting the screen horizontally in tmux, do the following:
After pressing, Ctrl + b, leave the keyboard and then press "

// For splitting the screen vertically, do the following:
After pressing, Ctrl + b, leave the keyboard and then press %

Note: After splitting, press Ctrl + b, and then use arrow keys to mopve around. 
Lastly, its better to use take ssh from cmd instead of putty for terminal splitting
</code></pre>

### dig

It is the newer alternative for older nslookup.&#x20;

It has following options:

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FJ0lqzWr77Gp6xIRpv7tB%2Fimage.png?alt=media&amp;token=7c8a505e-0ff9-4765-b822-4063d1f3b905" alt=""><figcaption><p>Source: <a href="https://phoenixnap.com/kb/linux-dig-command-examples">https://phoenixnap.com/kb/linux-dig-command-examples</a></p></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FjFLYpUOxrxduueFvgjV0%2Fimage.png?alt=media&amp;token=8c5b42e3-089b-4c1b-9c1d-4b413a80e17c" alt=""><figcaption></figcaption></figure>

### ssh&#x20;

#### Type of Shell

ssh has a switch option called as -t which can be used to specify the shell one wants while ssh'ing

One can also determine the type of shell using the command:

```bash
script_shell="$(readlink /proc/$$/exe | sed "s/.*\///")"; echo $script_shell
```

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F9AXzZKON7lGrB2ZbA4Oz%2Fimage.png?alt=media&amp;token=1f46744e-3424-4cc6-90b9-557dbb102ccf" alt=""><figcaption></figcaption></figure>

#### Local Port Forwarding

Everyone knows ssh, but suppose one is accessing a remote server via ssh and the remote server doesn't have GUI, only terminal then the following commands can use tunnelling using port forwarding to access an application running locally on the remote server from host machine.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FsHJM4yWK0gX0dQE14RT2%2Fimage.png?alt=media&amp;token=30af3651-c690-4e0b-a627-0b4ecb398108" alt=""><figcaption></figcaption></figure>

```bash
ssh <username>@<ip-address> -N -f -o ServerAliveInterval=60 -L <localport>:<hostinterfaceaddress>:<hostport>
```

Here, -N is only for port forwarding and not executing remote commands, -f backgrounds ssh, -o is used for passing configuration values (serveraliveinterval is used to keep the connection alive after every 60 seconds), -L is used to forward a local port to the remote server's port

Note: One can also use -q for quiet mode

For example, to access the python server which is running on localhost of linux server, one can issue the following command: ssh \<username>@\<ip-address> -N -f -o ServerAliveInterval=60 -L 8000:localhost:8000

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FCD87NSnsjRjqhFi0wVs2%2Fimage.png?alt=media&amp;token=a3fd4434-8884-4b0a-8aba-1d27715b47d7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FqoaZEqYreeJ9qrJJ55DM%2Fimage.png?alt=media&amp;token=9f1a7cc8-c12c-48d9-82e6-556d62ebe795" alt=""><figcaption></figcaption></figure>

#### Dynamic Port forwarding

Here, -D is used for the remote linux server to act as socks proxy and -C is used for compression to save bandwidth.&#x20;

```bash
ssh -D <local-port> -f -C -N -q <username>@<ip-address>
```

The operation can be easily understood as shown below:

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FxeBJzhA1gelpPIUoF0G5%2Fimage.png?alt=media&amp;token=07c842f1-b52f-4fd4-9c05-c5c2e534a093" alt=""><figcaption><p>Source: <a href="https://ma.ttias.be/wp-content/uploads/2017/01/socks5_proxy_encryption.png">https://ma.ttias.be/wp-content/uploads/2017/01/socks5_proxy_encryption.png</a></p></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FzGwGAQsEfAf7LDSKfiOF%2Fimage.png?alt=media&amp;token=d31cd026-9852-4e25-9851-15b12955e503" alt=""><figcaption><p>Source: <a href="https://ma.ttias.be/wp-content/uploads/2017/01/socks5_browser_settings.png">https://ma.ttias.be/wp-content/uploads/2017/01/socks5_browser_settings.png</a></p></figcaption></figure>

#### Remote Port forwarding

Now, let's just assume that there is a remote server, where one can ssh into from local machine, but from that remote server, if one wants to access a webserver hosted on local machine, then reverse port forwarding can be quite helpful.

```bash
ssh -N -f -R <local-port>:<remote-server-address>:<remote-server-port> <username>@<ip-address>
```

Let's take the following example:

On local machine, a webserver is hosted on port 8088

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F51vwWADe8wjTXheUh0QY%2Fimage.png?alt=media&amp;token=7abbef6a-09eb-4d23-a6bb-a581f7010646" alt=""><figcaption></figcaption></figure>

Now, for this webserver to be available to linux server, one can open terminals, one for reverse port forwarding (telling that remote server when access webserver locally on 8088, it will connect with webserver hosted on local machine) and other for interaction as shown below:

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FGCPowKJ3Tavhx8utAWdj%2Fimage.png?alt=media&amp;token=9794de10-e739-4b9f-b5aa-6945f04b580b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FjJiyYRBKstl2CzKuZN0L%2Fimage.png?alt=media&amp;token=2d1ec8fd-b7dd-422a-92ec-1bcd2a2d5197" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2Ft77dRSlSwVCPioKxcuzQ%2Fimage.png?alt=media&amp;token=25897fbe-32b2-4ffd-a89e-b0eb0e776f3a" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
One more important option is use of -J which is to specify the jump host, so if a server A is not accessible directly, but via server B only, then ssh -J user\@serverB user\@serverA

This command would work when password authentication is being used on both serverB and serverA

For it to work via pem key, one need to create the following config file under .ssh and access it via the command:&#x20;

ssh remote
{% endhint %}

```keepalived
Host jump
	HostName <jump-box-public-ip>
	IdentityFile .ssh/<pemkeyfile>.pem
	Port 22
	User ec2-user

Host remote
	HostName <remote-server-private-ip>	
	IdentityFile .ssh/<pemfilekey>.pem
	Port 22
	User ec2-user
	ProxyJump jump	
```

### socat

Its purpose is to establish a relationship between two data sources, where each data source can be a file, a Unix socket, UDP, TCP, or standard input.

It can be best described as written below from manpages:

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FkTa40zVBD0FHzW6OFEVO%2Fimage.png?alt=media&amp;token=9c1c0bd0-6649-4966-848a-103dbeff98e9" alt=""><figcaption></figcaption></figure>

One of the most used option is to use socat to connect to two TCP streams on separate streams. As per syntax, socat options \<bi-address> \<bi-address>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FmCILTszOGM0OsmvsyLVh%2Fimage.png?alt=media&amp;token=b7ed9409-74cd-4632-9721-190d1ec9c087" alt=""><figcaption></figcaption></figure>

Note that address can be of any order listen first or connect first also.

Thus the following command can be used to connect two data streams as shown below:

```bash
socat TCP-L:443,reuseaddr,fork TCP:localhost:8088 &
```

Note: **fork -** put every connection into a new process, **reuseaddr -** keeps the port open after a connection is made, **& - b**ackgrounds the application

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FzGaoYlzvFRbShxC02K9j%2Fimage.png?alt=media&amp;token=87ee0127-fd08-43c9-baae-c7d5e52d1fd8" alt=""><figcaption></figcaption></figure>

Note, if one wants to create only listener or only connect, then give the 1st bidirectional address as hypen (-) like directly that tcp stream would be stdout

Examples of usage:

In Machine A, terminal 1 --> socat - TCP4-CONNECT:\<IP>:\<port>

In either Machine A or Machine B terminal --> socat TCP-LISTEN:\<PORT>,reuseaddr,pf=ip4,fork -

The pf=ip4 option explicitly restricts the TCP-LISTEN address to use IPv4 (Internet Protocol version 4) for listening. It ensures that socat will only bind to an IPv4 address and only accept incoming connections that use IPv4, since by default, it often tries to listen on both IPv4 and IPv6 (Internet Protocol version 6) if the system supports it. The fork is crucial for allowing the socat listener to handle multiple incoming connections sequentially or in parallel. When a program like socat (or any server) is shut down, the socket it was using to listen on a port does not immediately become available. The operating system holds the socket in a TIME\_WAIT state. The `reuseaddr` option is a socket option that allows to bind immediately to the same port.

### tr

As per help section, tr is simply used to convert small-case to upper-case or delete characters

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FjdV1ZgpcBncHyaXvpIPq%2Fimage.png?alt=media&amp;token=536b32a8-c4dc-4cf3-96ae-dc56649179fb" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FuAdrvg0iaL81drABNoDr%2Fimage.png?alt=media&amp;token=03421824-a1dc-4620-9f9e-84e1050ef028" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FuLxKQGMnBFFZYpTfaX9d%2Fimage.png?alt=media&amp;token=9223e6d8-568d-4a68-b750-5e98d07e1218" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F0w3ahUPxvduZ8M5IeIO4%2Fimage.png?alt=media&amp;token=c595788b-8e86-4bc1-9075-e262a4f46951" alt=""><figcaption></figcaption></figure>

Print the last 5 lines and replace the space character (' ') with underscore character ('\_')\
using tr utility.\
Command: cat apache\_access.log | tail -5 | tr ' ' '-'

### grep

grep has the following switches which are commonly used:

![](https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FfGcs0J3KGA1G7XnG2v40%2Fimage.png?alt=media\&token=cb16a73f-6b1a-4cad-8b6c-ced339009b84)

grep's -v is used to grep everything in file except the passed argument:

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FBQbYnaFcjZj2I6CEr0Ch%2Fimage.png?alt=media&amp;token=8489083b-5cba-4c7b-84ea-b339e71e3555" alt=""><figcaption></figcaption></figure>

### tldr

Its an alternative to manpages

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FgHOb446UXPNPYQhxffWi%2Fimage.png?alt=media&amp;token=ffd06863-956e-4280-a8d2-add4c4f3b20e" alt=""><figcaption></figcaption></figure>

### at and cronjob

It is like a non-recurring cron job.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FXCfZFR9pk6Id4dOoLXdT%2Fimage.png?alt=media&amp;token=f7bfcb07-f16e-462f-ae75-adc49459b493" alt=""><figcaption></figcaption></figure>

Cronjob: To define the time you can provide concrete values for minute (m), hour (h), day of month (dom), month (mon), and day of week (dow) or use '\*' in these fields (for 'any').  Exact Pattern: minutes hour dom mon dow command

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FJ15tqkjku76RPbuz6SKM%2Fimage.png?alt=media&amp;token=acbb2aa7-e470-49ef-b0c5-eab4bb63827d" alt=""><figcaption></figcaption></figure>

Note that all crontab can be added in single file itself using crontab -e

### timeout

It is used to limit the execution of a command to time in seconds mentioned. example ping is in infinite loop without timeout and with timeout, it is limited as shown below:

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2F1tGvo6fRHGbFBPlw8FdS%2Fimage.png?alt=media&amp;token=b97cb046-67c6-44db-8d6d-9f39a0ac9d91" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
lynx and browsh are terminal based browser, useful for submitting forms
{% endhint %}

&#x20;


# AWK

It is more of a script than an command, which is heavily used for text processing and data manipulation and produce formatted reports. It is typically used as a data extraction and reporting tool. It is a standard feature of most Linux operating systems and is useful when handling text files that are formatted in a predictable way. awk parses and manipulates tabular data on a line-by-line basis, and it iterates through the entire file. By default, awk uses whitespace—for example, spaces and tabs—as a delimiter to separate fields

The syntax is as follows:&#x20;

```awk
awk GNU_OR_POSIX_OPTIONS 'pattern_selection_criteria {action}' input-file
```

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FXbUgjB1cKu9aBEOAciEq%2Fimage.png?alt=media&amp;token=a9e67a0e-237e-496b-a8d5-458b158d94fe" alt=""><figcaption></figcaption></figure>

As shown above, -F is important to tell the delimiter

awk has  built-in variables such as:

* **`$0`**. Used to specify the whole line.
* **`$1`**. Specifies the first field or first column. (example - awk '{print $1}')
* **`$2`**. Specifies the second field.
* NR: Counts the number of input records (usually lines). Awk command performs the pattern/action statements once for each record in a file.&#x20;
* FS: Just like the command line argument -F, the field separator can also be passed via variable FS.
* RS: Stores the current record separator character. Since, by default, an input line is the input record, the default record separator character is a newline.&#x20;
* OFS: Stores the output field separator, which separates the fields when Awk prints them. The default is a blank space. Whenever print has several parameters separated with commas, it will print the value of OFS in between each parameter.&#x20;
* ORS: Stores the output record separator, which separates the output lines when Awk prints them. The default is a newline character. print automatically outputs the contents of ORS at the end of whatever it is given to print.
* FNR: It is the current record number in the current file. For the file, NR is going to be equal to FNR as FNR will reset to 1 for every file but NR will keep increasing.
* NF: Variable whose value is the number of fields in the current record.

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FA7PzjQjCmSZ3B1g1usTk%2Fimage.png?alt=media&amp;token=96db7ead-8cbe-4f48-a815-0697fcc29560" alt=""><figcaption></figcaption></figure>

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FbsquZx98gzZcClxYaOlW%2Fimage.png?alt=media&amp;token=2177c920-8d7b-43b7-b32f-0b1de1c67130" alt=""><figcaption></figcaption></figure>


# Regex

Regex is advanced search pattern which can be used to search non-specific and specific data, as well as enhance the quality of your programming code.

Please note that if one can avoid regex instead of something simpler, one must avoid using it. Sometimes using regex where it is not required can break things.

<https://regexr.com> and [https://regex101.com](https://regex101.com/) are very helpful online tools to build regex queries.

To identify any pattern, different pattern formation elements (regex structures) are used which are as follows:

* **Character Classes**: List of characters that can appear in the pattern. Character classes are defined by square brackets around the list
  * [x] \[a-z] - all small letters
  * [x] \[A-Z] - all capital letters
  * [x] \[a-zA-Z] - both small and capital letters
  * [x] \[0-9] - all digits
  * [x] \[afgh] - elements only from this list of a,f,g and h
  * [x] \[^a-d] - ^ means negative or not when in square brackets, i.e. any character which is not small a, b, c and d
  * [x] \[\[:alnum:]] - All alphanumeric characters
* **Meta Characters, Anchors and Escape characters**: They have special meaning within regex and usually start with \\
  * [x] / - start or end of an expression
  * [x] ^ - Start of the line&#x20;
  * [x] $ - End of the line
  * [x] \w - any word small or capital and \W - not any word
  * [x] \s - whitespace and \S - whitespace
  * [x] \d - digits and \D - not digits
  * [x] \b - backspace character or word boundary and \B - non word boundary
  * [x] a|b - match either a or b. | - means match any character before or after |
  * [x] \N or **.** - matches any character other than newline
  * [x] \\\  - matching \ itself
  * [x] \\\* - matching \*&#x20;
  * [x] \\. - matching dot
  * [x] \n - match newline
  * [x] \t - match a tab character
  * [x] \r - match carriage return
  * [x] \0 - to match null character
* **Occurrences:** They usually tell how much to match with the help of wildcards
  * [x] {1,3} - Define a range—the first digit is the minimum value, and the second is the maximum value&#x20;
  * [x] {4} - Number of times the pattern should be matched
  * [x] \+ - Match one (1) or more of the specified preceding pattern, \* - Match zero (0) or more of the specified preceding pattern&#x20;
  * [x] ? – Match (0) zero or one (1) of the specified preceeding pattern.
* Quantifiers: Combining occurrences with the previous two regex structures can give something as quantifiers.

  <figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FoUGJObuVfKdZaduk4cWS%2Fimage.png?alt=media&amp;token=ec1826f3-8cc9-4b35-a968-cbeda76f1356" alt=""><figcaption><p>Source: <a href="https://regex101.com/">https://regex101.com/</a></p></figcaption></figure>

Note, capture group can be used with (), so if one wants to capture a pattern which has anything in between two words, let's just say, WORD1 aasdkjaslkj WORD2 asdka WORD3, then to capture from word1 to word2, regex can use the capture group as (.\*?) which means match anything except newline which can be any number of times including zero and capture it only once

Examples:

1. To search gmail id of let's just raghav, but if there are many raghavs' (like <raghav1@gmail.co>, <raghav5@gmail.com>) and there may be additional emails such as that of yahoo, outlook etc , then the regex query can be as follows:

```regex
raghav\d*@\w{2,}\.\w{1,}
```

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FUZs2JDFfzOyougSoZCHL%2Fimage.png?alt=media&amp;token=6c327030-c665-4b7d-908d-9e0745aea10e" alt=""><figcaption></figcaption></figure>

Here, raghav is matched and then it can have a digit or not i.e.digits can be 0 or more hence \*,  followed by @ of the email domain and then domain can be be any word greater than 2 characters followed by a dot, which is lastly followed by a word of characters 1 or more to tell root domains

2. To search Aadhaar card number which is a set of 12 digits with spaces in between, the regex query can be:

```regex
/\d{4}\s\d{4}\s\d{4}/g
```

3. To search credit card separated by either spaces or dash, regex query can be:

```regex
\d{4}\s?\-?\d{4}\s?\-?\d{4}\s?\-?\d{4}
```

4. To extract IP address from IIS source file, one can use regex101.com to form a query, grep -Po to extract and awk to print only required information as shown below:

```bash
grep -Po '\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s[GPHOT]' iis-sample-logs | awk '{print $1}'
```

<figure><img src="https://275986271-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPaRFhO7J6sRJrjn8Haee%2Fuploads%2FkAe5JrkAR16JBf8cibXv%2Fimage.png?alt=media&amp;token=25bb0eca-2a90-4e66-87ec-3067fd551ff3" alt=""><figcaption></figcaption></figure>

Note: awk consider field separator as space by default


# Log Scanning

Log Scanning is beneficial for troubleshooting service errors and searching malicious activity

Logwatch is an excellent tool to achieve the above objective. One can refer [this](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-logwatch-log-analyzer-and-reporter-on-a-vps) link to learn the same.

auditd is the daemon that has to be installed to achieve the same. One can refer [this ](https://sematext.com/glossary/auditd/)link to learn more. aureport is used for generation of report and ausearch is used for searching within the logs collected by auditd. auditctl is used for configuring log collection rules

Note: Please check the locale using command date '+%x' and then pass it to ausearch with start and end dates as:

ausearch -ts \<locale-date-format> -te \<locale-date-format>


# SE-Linux


# AIM

## All content published is intended as an AWS Cloud Primer for IT professionals.


# General Stuff about AWS

1. The on demand self-service delivery of compute power, DB, storage, app, and other IT resources through a cloud services platform via the Internet with pay-as-yo-go pricing is the essence of any cloud and AWS is no different. In short, AWS started as a DataCenter as a service.
2. When one uses AWS, they are kind of accepting the shared responsibility model, where **AWS** is responsible for **security of the cloud** and **customers** are responsible for **security in the cloud,** as shown below, and it changes with type of the service:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FV2DEzArU3p9HJ6VrJubD%2Fimage.png?alt=media&amp;token=9187c4e4-ef78-4be4-aae1-d0c556a0f844" alt=""><figcaption><p>Source: <a href="https://aws.amazon.com/blogs/industries/applying-the-aws-shared-responsibility-model-to-your-gxp-solution/">https://aws.amazon.com/blogs/industries/applying-the-aws-shared-responsibility-model-to-your-gxp-solution/</a></p></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FXY44ovXkmawnc3542NY3%2Fimage.png?alt=media&amp;token=d04fed48-28f6-460f-9ad2-59dbbff458a3" alt=""><figcaption><p>Source: <a href="https://aws.amazon.com/blogs/industries/applying-the-aws-shared-responsibility-model-to-your-gxp-solution/">https://aws.amazon.com/blogs/industries/applying-the-aws-shared-responsibility-model-to-your-gxp-solution/</a></p></figcaption></figure>

3. AWS has something called as metadata resource tags, which can be used to segregate workloads across all AWS Services.
4. AWS Pricing Calculator can be used to get an estimated cost before moving workloads into the AWS cloud.
5. AWS Cost Explorer is useful for segregation wise cost by either linked account or linked accounts.
6. AWS Organizations is a simple way to get consolidated billing and apply common policies by having a master account and then creating department wise accounts under that.
7. Whenever events affecting customers of AWS occur, AWS Personal Health Dashboard can provide alerts and guidance related to remediation.
8. **AWS Trusted Advisor** is an automated tool to check AWS usage against best practices. All AWS customers get access to seven core checks. It gives recommendations related to Cost Optimization, Performance, **Security,** Fault Tolerance and Service Limits. For complete Trusted Advisor Checks, it is recommended to opt for AWS Business Support.
9. Where Cloud like AWS shines, is Serverless computing offering. It takes PaaS a step further, by introducing the developers with event driven based architecture, which means whatever code the devs are writing, will get an execution environment when an external event is triggered and they have to pay only for the compute required when the code is executed.&#x20;


# AWS Global Infrastructure

* AWS Regions are the main data centers in a particular geography.
* AWS Regions are further divided into availability zones by default that are there for fail-over and high availability. Example: ap-south-1 is Region Name and ap-south-1a is availability zone.
* AWS Local Zones can be said as an extension of AWS Region. They are just strategically located AWS data center which is well connected with main AWS Region Data Center.
* Outside of AWS Regions, specific points of presence elements exist. They are Edge Locations and Regional Edge Caches. Edge Locations are nodes used by Content Delivery Network service of AWS, named as Amazon CloudFront and their DNS service named as Amazon Route 53.&#x20;

<div data-full-width="true"><figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FBWBjkxKDflqBvqniS9c2%2Fimage.png?alt=media&amp;token=2208bbc7-94b9-41ed-8e00-9f4c6038f226" alt=""><figcaption></figcaption></figure></div>

* To get information about AWS IP ranges, one can get navigate to <https://ip-ranges.amazonaws.com/ip-ranges.json> and get a gist of the same:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FHSPONOVY98zgvrFY5I7x%2Fimage.png?alt=media&amp;token=0a213ef2-5342-45a8-85fb-9602e2f5e0ae" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Many times, Hackers take these IP Ranges and then checks across these ranges using online scanners, if there are any misconfigured or vulnerable AWS Service present on the same
{% endhint %}


# Interacting with AWS

## Accessing AWS Services

* AWS Management Web Console&#x20;
* AWS Mobile Application
* AWS CLI \[Available for Windows/Linux or use **CloudShell**]

> Note: AWS CLI comes preinstalled on AMI Linux. Also,Bundled installations like the one as shown below are difficult to modify default behavior like changing User Agent, so its recommended to passit via Proxy (Shown later)
>
> One can install AWS CLI in Debian based Linux using the following commands:
>
> ```bash
> curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
> unzip awscliv2.zip
> sudo ./aws/install
> aws --version
> aws configure
> aws sts get-caller-identity
> ```

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FV9OHrnxuYgb2IeekLIR6%2Fimage.png?alt=media&amp;token=4baf7f46-cb94-4b9d-a481-7d4fe4985124" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F4VZpvLiGBqsUuliErKm4%2Fimage.png?alt=media&amp;token=c0a264d3-b13a-4c69-93a1-2298cdb1fc14" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FSZwMs0hNrSRJeeDxbYss%2Fimage.png?alt=media&amp;token=e6308743-1897-4d27-843f-2892557d99ca" alt=""><figcaption></figcaption></figure>

* AWS SDK \[Some of the supported languages are Python, C++, Java, .NET, Ruby, Node.js, Javascript (Browser), Kotlin, Swift etc.]


# AWS Identity and Access Management

### Introduction

AWS IAM is one of the foundational services in the cloud, responsible to control access to AWS resources in a particular AWS account across the Internet.

During sign up process on AWS, Root user is created automatically and hence they have unrestricted access to all AWS services in that account. Therefore it is vital to have MFA on root account. In addition to this, following are the best practices:

* Disable Root access key for cli usage
* Rotate credentials
* Don't share root user credentials

Hence, for day to day activities, it is not at all recommended to use root account. So what's the solution? AWS provides IAM (Identity and Access Management) service to create users, groups, roles and policies to provide privileges to the AWS cloud account as required, following the principle of least privilege.&#x20;

As the name suggests, **IAM is responsible for Identity and Access which is cooler way of redefining Authentication and Authorization. Under Authentication, Creation and management of identities happens and under authorization, permissions to identities happens.**

* [x] When the word "Identities" is written, it represents any of the following:
  * IAM User - Can be a User or an Application
  * IAM Group - can be a collection of IAM Users
  * IAM Role - Used to assign temporary credentials that has privileges to perform and access certain AWS resources; so IAM Users, application or external identities can assume the role.&#x20;
* [x] When the word "permissions" is used, it usually refers to permissions inside a policy, which is used to do access control (a way for authorization mechanism) for the above identities.&#x20;

IAM user with Administrative privileges is the 2nd most powerful account that can be used safely instead of root account for day to day privileged operations in the AWS cloud.

*Note by default, AWS IAM Identities don't have access to billing console. It needs to be explicitly permitted.*

AWS IAM can provide secure access, provide granular control over that access and also ensure that access is temporary. This is all facilitated to AWS IAM Identities, which can be a IAM user or IAM Group or even IAM role.

### Account ID and Account Alias

Account ID (which is 12 digit numerical id) is created on its own when one sign-up for AWS. Now, one can simply create account alias which will be bound to account id. Its similar to why DNS is being used. Humans cannot remember numbers, so they need simple names and that is where this comes up.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F5lYamhQLbDyjHhEtz8j9%2Fimage.png?alt=media&amp;token=7dd0528b-cbac-40b7-9c77-86f7c90726f6" alt=""><figcaption></figcaption></figure>

Once created, the new URL for login for IAM Users can be as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FYkNQvagK5OgdGT5bfSQR%2Fimage.png?alt=media&amp;token=779b4002-3591-4877-a8b8-a82bb3ef44be" alt=""><figcaption></figcaption></figure>

### ARN

All resources have unique Amazon Resource Name (ARN)

It is of the following format

```json
arn:partitition:service:region:account-id:resourcetype/resource/qualifier
```

Note that partition in arn can also be "aws-us-gov" or "aws-cn", if not, it is usually "aws" for most case

Example:

```json
arn:aws:s3::::images-of-football

The reason region and account id are not mentioned in this 
is because s3 is a global service, so no region is required and 
also when region and account is not give, it is assumed that default account
and default region is selected
resource type is also set to default to bucket
resource is images-of-football as this is a bucket arn
```

```
arn:aws:ec2:us-east-1:112233445566:instance/i-054dsfg34gdsfg38

Here, one can can see that for ec2, resource type is given as instance
and resource is instance id (i-054dsfg34gdsfg38)

If it ever requires that all instances would have ARN of
arn:aws:ec2:us-east-1:112233445566:instance/*
```

### AWS STS

One of the foundational service for IAM is AWS STS. AWS Security Token Service (AWS STS) is a web service that enables to request temporary, limited-privilege credentials for trusted users in form of tokens that can control access to AWS resources.&#x20;

The duration of the validity of the token or lifetime of the token can range from 15 mins and go upto 36 hours.

The working of AWS STS can be explained as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FkJyw35D8uQXcxqerVtQQ%2Faws-sts-chart-2.png?alt=media&amp;token=f56e49c6-9639-408a-85ca-16e38d3a1d0f" alt=""><figcaption><p>Source: <a href="https://cloudpatterns.org/wp-content/uploads/2023/03/aws-sts-chart-2.png">https://cloudpatterns.org/wp-content/uploads/2023/03/aws-sts-chart-2.png</a></p></figcaption></figure>

{% hint style="info" %}
**Each IAM entity (user, group, or role) has a defined aws:userid variable.**&#x20;
{% endhint %}

Note that a **Session ARN is a unique identifier for a session when a user assumes an IAM role. This session is created when an IAM user or another role assumes a role using the AssumeRole API call**.

The Session ARN typically looks like this:

arn:aws:sts::ACCOUNT\_ID:assumed-role/ROLE\_NAME/SESSION\_NAME

### AWS Requests

{% hint style="info" %}
To access a resource, the principal sends a request to AWS with the help of following components:&#x20;

* Name of the principal that can be IAM User or IAM Role&#x20;
* Actions or operations to perform&#x20;
* Resource over which the operation has to be performed&#x20;
* Resource specific data&#x20;
* Environment in which the request has to be performed (Specific conditions such as IP if implemented)
  {% endhint %}

&#x20;A sample of Request and Response made using AWS CLI can look like this:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FFYrL3yuR6kjLP8tHMUq6%2Fimage.png?alt=media&amp;token=3243fbca-9dff-4e33-9133-9affa8966d99" alt=""><figcaption></figcaption></figure>

> **For those who are interested to know how to intercept AWS CLI Requests in Windows/Linux, here are the steps:**
>
> 1. Download Burp Certificate and head over to Linux machine or ubuntu wsl and issue the command: openssl x509 -inform der -in path/to/Burp-certificate.der -out /path/to/Burp-certificate.pem
> 2. copy the contents of .pem file generated in above step.
> 3. Append the above certificate in "C:\Program Files\Amazon\AWSCLIV2\awscli\botocore\cacert.pem" at the end. Note for linux, the path is "/usr/local/aws-cli/v2/current/dist/awscli/botocore/cacert.pem"
> 4. Download the AWS-Sig4 Burpsuite extension from Portswigger.
> 5. Import the keys into the extension.
> 6. In Windows CMD prompt, use the following commands for Windows/Linux (for particular session):
>
>    * HTTP Proxy
>
>    `set HTTP_PROXY=http://127.0.0.1:8080` OR`export HTTP_PROXY=http://127.0.0.1:8080`
>
>    * HTTPS Proxy
>
>    `set HTTP_PROXY=http://127.0.0.1:8080` OR`export HTTP_PROXY=http://127.0.0.1:8080`
> 7. Finally use awscli commands and it would be intercepted.
> 8. One can also use this to change User Agent if required


# AWS Organizations

As the name suggests, it is used to organize different AWS Accounts (which can be used by different departments in a company) to have consolidated billing and gives the flexibility for different departments to have different policies:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FQ1wQFaVXjRtvr3WI43YF%2Fimage.png?alt=media&amp;token=f823b595-f44b-4b78-a1d6-2ded24623a09" alt=""><figcaption><p>Source: <a href="https://td-mainsite-cdn.tutorialsdojo.com/wp-content/uploads/2018/12/AWS-Training-AWS-Organizations-2.jpg">https://td-mainsite-cdn.tutorialsdojo.com/wp-content/uploads/2018/12/AWS-Training-AWS-Organizations-2.jpg</a></p></figcaption></figure>

By default, when one goes to AWS Organizations menu, the context can be as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FX8A81QBTTGAKtEaqscjn%2Fimage.png?alt=media&amp;token=1f337462-d1f4-4ed8-8801-9008372916e5" alt=""><figcaption></figcaption></figure>

Now, one can create an OU and then create an account under it:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F7je2maVjlRWsIa51vN53%2Fimage.png?alt=media&amp;token=7484187c-a8f3-401b-b7cd-eae01dbd24ae" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fih38Rs8GAUgsUVRUn0h5%2Fimage.png?alt=media&amp;token=c08ab87a-919b-4e13-93fb-12de7ce793a8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FXeHqxVEk459kqrAdajWc%2Fimage.png?alt=media&amp;token=ab8f28d8-21ac-4141-9ab9-3335d3ad5009" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fke9TmBKXMWGcQtQEVRmp%2Fimage.png?alt=media&amp;token=1c53da89-d5d6-45b5-b623-e6743e55934c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZWUh4EV70Jo20cMUaFON%2Fimage.png?alt=media&amp;token=86812617-d714-42ec-85fb-b10ebe9b5e04" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FCBEQRDBOqIS958mHENBu%2Fimage.png?alt=media&amp;token=c9d23af8-9a88-4721-aa36-5fd3f3b7ecfd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FPxKQiReBSiTXhEzmS3qo%2Fimage.png?alt=media&amp;token=f7828dca-3bd8-4072-bcb8-41501ff0c5ec" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FqKOJ6zDHxp7qK4rtq8xU%2Fimage.png?alt=media&amp;token=3f9230f2-368f-41e2-8f3e-1fb70b689975" alt=""><figcaption></figcaption></figure>


# Users

Every IAM user receives Amazon Resource Name (ARN). It is similar to object id in Active Directory and is of the format:

* arn:aws:iam::\<account-id>:root&#x20;
* arn:aws:iam::\<account-id>:user/iam-username

More details about ARN are already explained [here](/aws/aws-identity-and-access-management#arn).

### Console Access

When logging into AWS, using root account, one can simply navigate to <https://console.aws.amazon.com>, which will redirect to domain [signin.aws.amazon.com](https://signin.aws.amazon.com)

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FlVoL7P6Fn7KCspBzMa8I%2Fimage.png?alt=media&amp;token=98034837-3dd0-4c0d-83ef-b41c3f2466ed" alt=""><figcaption></figcaption></figure>

However, when logging using IAM account, one can simply use the 2nd option as mentioned in the above screenshot and simply provide the options as mentioned in the below screenshot:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FHR5gGTbk3Mki1nhrP629%2Fimage.png?alt=media&amp;token=7c01d4eb-a0b1-4aa6-8f53-ed3a0f0e5464" alt=""><figcaption></figcaption></figure>

Now one can either provide account ID (which is 12 digit numerical id) created when one sign-up for AWS or simply provide an account alias (as its difficult to remember the 12 digit number) in place of account id to access further and lastly provide the IAM user and password to login, provided the IAM user has console access.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FvQw8BFY92SRuG4Z2Gfzf%2Fimage.png?alt=media&amp;token=48f521b6-3f8e-4327-81bf-fde253426b30" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FuukDuVmHWSMdB4AVQPcn%2Fimage.png?alt=media&amp;token=99cc4fba-7f3c-4999-9d0e-c88ca80878d4" alt=""><figcaption></figcaption></figure>

Now, one can understand the steps can be referred to see how to create an IAM user and provide the user console access in IAM console. If its the first IAM user, then one has to use root account privileges. To be specific, the following account that is created is the administrator account which can be used to manage day to day operations in AWS.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FAUKfxa2pqvbI9F9V7iUu%2Fimage.png?alt=media&amp;token=5648b24c-34bc-487c-a241-359aa54e5131" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F0sujTdunzuyQxzbPmws1%2Fimage.png?alt=media&amp;token=4049a678-690b-4671-960c-e0ea3f893202" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZ9SEjsmKCdyHrj0B1Yk9%2Fimage.png?alt=media&amp;token=737c2be6-2e70-4eee-aece-12798f2529a4" alt=""><figcaption></figcaption></figure>

Instead of creating user with administrator access individually, a group has been created with administrator privileges as shown [here](/aws/aws-identity-and-access-management/groups-and-roles).

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FJERINKp2iQY9vsmjcYUY%2Fimage.png?alt=media&amp;token=77165d93-5074-45a9-a034-de09d4573f65" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Every IAM user access resources based on assigned permissions.
{% endhint %}

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FC3cQlC0tq95e3CYcyW3x%2Fimage.png?alt=media&amp;token=351d9565-c35d-4167-aaac-7a5c9b14a15b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FTiaJcfxqGlDlWcNU19jU%2Fimage.png?alt=media&amp;token=5542f3e4-6abe-40d3-8385-1ef6fc216529" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note, one can also access AWS console via https\://\<account-id>.signin.aws.amazon.com for AWS IAM Users to login
{% endhint %}

### Forgot Password

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FaPAVqMGbkgj6qaMOUyeu%2Fimage.png?alt=media&amp;token=03143a5d-3071-434b-bf70-78f8869f3e61" alt=""><figcaption></figcaption></figure>

As said above, IAM users would have to go to their IAM administrators for password reset. This is particularly useful to prevent SSPR (Self Service Password Reset) abuse in phishing attacks.&#x20;

### Programmatic Access

Next, one can also create access keys to let the user access AWS programmatically or using cli. It is like **user-id (Access Key ID)** and **password (Secret Access Key)** for programmatic access.&#x20;

Moreover, the best practices for them are as follows:&#x20;

* Rotate access keys every 90 days
* Store access keys in secure manner

**Note**: Refer [here ](https://guides.radifine.com/how-to-securely-access-and-transfer-file-to-an-ec2-instance-in-private-subnet-of-vpc-in-aws#heading-step-24-for-access-via-awscli-more-work-is-necessary)on how to use access keys and MFA to create[ short term credentials](https://notes.radifine.com/aws/aws-iam/federation#aws-sts) for best practices. This is particularly useful to avert the risk of long term damage in case the user's system is compromised.

**Note**, if the access key is for an application, then one can create a different user with only cli access that has access to particular resource in AWS, store it in AWS secrets manager and then give EC2 IAM instance profile to fetch only that particular AWS key from AWS secrets manager as security best practice

* Delete unused keys
* Monitor usage of access keys

It can be created as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FaxPKRUoD2eblQq7YhODP%2Fimage.png?alt=media&amp;token=0bf904ef-38e7-48cf-b219-b7abc43a50bf" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FXNgskPzRtG3IwZC5eLhK%2Fimage.png?alt=media&amp;token=a7a2493d-0b81-469e-a290-6a98c630ccca" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FnBXPjdzGjnVilaL82bVJ%2Fimage.png?alt=media&amp;token=ca5208cb-e72c-4ec6-a688-0fac072889be" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note: If the primary use case of access keys is going to be to use it to perform operations across AWS service to do repetitive tasks or save time to do something over cli for better productivity, then **CloudShell** can also be used as shown below. It is simply better because there is no requirement to ever store access keys locally in user's system in this case.
{% endhint %}

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6jVCdsvVBxegN29IHlBl%2Fimage.png?alt=media&amp;token=c23adbd3-c164-4a75-bdf9-3f46c80c5722" alt=""><figcaption></figcaption></figure>

Note that Access Key ID starts with AKIA for long term credentials and ASIA for short term credentials

### Password Policy

It is basically used to configure the following:

* Character requirement like small alphabets, capital alphabets etc.
* Minimum Password Length.
* Validity of the password in terms of its expiration.
* Number of times it is allowed to do attempt entering password for users.
* Reusability of Passwords

Password Policy can be managed as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FiTCvM9A5MaPwqSHbcMk5%2Fimage.png?alt=media&amp;token=d5501d22-cc8d-4de0-987a-413c2ce727b2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FsnkNJseECoBNhIGwGX5V%2Fimage.png?alt=media&amp;token=175cffd6-2f18-4fae-a4ff-da29d4ebe4f2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FVq30rrJlL7N6Xk6IzFnA%2Fimage.png?alt=media&amp;token=62623f2d-7e62-464d-b555-b9b99abdf767" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FgPaNLzYYlsk6KzjYoOzk%2Fimage.png?alt=media&amp;token=811b5535-7b0d-40f5-870b-aecd36faa589" alt=""><figcaption></figcaption></figure>

### Setting up MFA

This is used to setup extra layer of security.

Login to AWS console and go to Security Credentials

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FtspGAycNcNvBse7mbOAx%2Fimage.png?alt=media&amp;token=644a4535-1319-409a-9be4-f85316ac5aa0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FdsTeYKzPootRi0qdt7xi%2Fimage.png?alt=media&amp;token=ffa0e729-860e-41c7-bd65-ebfc8b789bb7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FU1kE5hmTyTWAuIOASGzj%2Fimage.png?alt=media&amp;token=568ab7d4-5ba3-41a8-8477-12d683d110ea" alt=""><figcaption></figcaption></figure>

For demo, lets configure using Software based Authenticator app. OneAuth, Microsoft Authenticator, Google Authenticator, Orange Authenticator etc are supported. We can also configure using browser extension from authenticator.cc

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F2ctynANcJzh160zqq2Az%2Fimage.png?alt=media&amp;token=e8403581-3a92-46b1-8f75-cef956cb4a02" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FWLx575ilkVKnkqiJ32a0%2Fimage.png?alt=media&amp;token=35b69ea0-25d6-4622-ae6a-e719337eb1f2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FkbMYkcZWwlqa1JOGY0ln%2Fimage.png?alt=media&amp;token=44c94c76-3453-4f22-983b-b1671776f032" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FGIPPwhkoec3pYn7vRNrP%2Fimage.png?alt=media&amp;token=7a502617-2150-4520-bcba-6020c0de73f9" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FatCZGERKP5SKtxUx4APK%2Fimage.png?alt=media&amp;token=3b1f0ab1-1fe5-44c4-bdec-7404b33d227a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FzxniuT5DJctg3u5sWoyE%2Fimage.png?alt=media&amp;token=72ea34dc-d487-4f25-921b-7318e429253f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FEwOXhVwmf91w837JOF7B%2Fimage.png?alt=media&amp;token=2dded367-a121-42f6-8883-8ba68f00b817" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FeNs9lU0hIGLUaCyxMlFF%2Fimage.png?alt=media&amp;token=c4648635-76f2-4b59-88fc-8fe29914cb04" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fpoj552vcAJFZrVyZD09Z%2Fimage.png?alt=media&amp;token=9673d61e-2c64-406e-b0d6-bb9336a096f1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FIy3kI5F23Knp9mb2erM5%2Fimage.png?alt=media&amp;token=fb6618ce-9517-427b-8604-7e42534277b0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FfHNh6MYkLW5ti8ZJNqfx%2Fimage.png?alt=media&amp;token=b849ca03-ef35-4bb2-9491-9648fca72239" alt=""><figcaption></figcaption></figure>


# Policies and Permissions

### IAM Policy

Permission policy is an authorization mechanism. Hence, until the policy is attached to an AWS Identity, that identity cannot do anything.

AWS Identities are authorized to perform or forbidden to perform certain actions based on these policies. This is possible a single policy can include multiple permissions or statements. Also, multiple statements in policies are evaluated in OR logic

IAM Policy is a JSON-formatted document in which permissions are listed. It consists of 4 different categories such as Effect, Action, Resource and Condition where Effect can be to allow or not to allow, action can be create or delete, resource can be AWS service and condition can answer whether to perform or not based on if it is true or not. These policies itself are like template. These needs to be attached to an AWS identity like user, group or IAM Roles for them to shape up to become permissions.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FVKf19XKJQ6vyYZPeGUaD%2Fimage.png?alt=media&amp;token=3a1cc59f-984e-48db-9f3a-4da6069baebd" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note, for ease of creation of an IAM policy, one can always try using the following:

<https://awspolicygen.s3.amazonaws.com/policygen.html>
{% endhint %}

IAM policy is written in Access Policy Language (a fancy name indeed for a JSON Document)

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F7EBToWg1C3mFqngyKbZs%2Fimage.png?alt=media&amp;token=494e568f-530d-4c9c-9964-82168eb91f06" alt=""><figcaption></figcaption></figure>

Note that there is a Version: 2012-10-17 statement in the above policy. It states when AWS created this version of policy writing. there was 2008 also, which was older version.&#x20;

Also, statement ID (SID) is optional

The Action follows Noun-Verb format (example: s3(noun):Get-Object(ACL)

The Condition follows Key:Value pair (example:"Condition":{"StringsEquals":{"aws:username":"Senapati"}}) and value is case sensitive by default, otherwise condition can be set to ignore case for value of Senapati. Also Policy condition types can be global condition keys or service-specific condition keys, examples of which is as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FWrCYwg4Kl92zcusF6Yjw%2Fimage.png?alt=media&amp;token=cd2049ba-13cc-4aa4-81d3-f63e47fcf894" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html">https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html</a></p></figcaption></figure>

Please note that for these policies to take effect, these need to be attached to an IAM Identity like User, Group or Role, thereby becoming permissions for the attached identity.

### Policy Creation

Steps to create a policy are as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FBDHKyvkvA2eEsmSQS34v%2Fimage.png?alt=media&amp;token=b345e076-5ae5-422b-a2e9-86fb30b47381" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FKjvDCkBG9dbocvREFubR%2Fimage.png?alt=media&amp;token=74231f12-459c-4048-8ac4-a7a3f722ae38" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FI8r1NcuLkbv2XuwVUrYJ%2Fimage.png?alt=media&amp;token=2471565f-b50d-4ea4-8b40-f1646bdea463" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FfvPUpxAALQBewSEssv39%2Fimage.png?alt=media&amp;token=15900b4a-3e4a-481f-b399-1cf3fc10e501" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FkPhfv8K9RxEPZPOI3RFe%2Fimage.png?alt=media&amp;token=bee7a932-9919-4525-8c54-33e7531affaf" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FHIzMPqelODRIYtllAcK4%2Fimage.png?alt=media&amp;token=d14aa977-f841-4d46-a859-1b93849a87c4" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FF3YkaCBtMQPOFHudQTlO%2Fimage.png?alt=media&amp;token=6353f9bc-9570-4073-b9a3-4f63e7ef6406" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F0h9o7NoAeP9EH3tNFxzF%2Fimage.png?alt=media&amp;token=eebfab21-63b6-4681-bd91-79d123453e3d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F5gMnsncz4AE5itWFk3Ug%2Fimage.png?alt=media&amp;token=07b3fca3-dc26-4205-b9e4-9893c0c98755" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FgxUKLGDnqiIG7AC3V56U%2Fimage.png?alt=media&amp;token=cc9f53f5-9279-4b08-bef0-d62c253624c2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F8FThYp48yPA5twEBSXtO%2Fimage.png?alt=media&amp;token=dd10dfdd-9fe0-48d1-955b-f86c0621d6db" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Personal Interpretation, the AWS IAM policies are evaluated on every action, especially for Console Access, meaning:

Let's just a user ABC is logged onto the console and has the permission in a policy attached to him/her that allows to upload a file inside S3 bucket. Now, if the admin or any user with change permissions over IAM removes the policy that allows ABC to upload files, then he/she would be unable to do so, the next time they want to perform the file upload permission (PutObject) inside the s3 bucket.&#x20;
{% endhint %}

Note that there is a&#x20;

### Summaries in IAM&#x20;

The policy summary have hyperlinks to Service Summary and it has hyperlinks to action summary. These summaries are an absolute gold when it comes to analysing and understanding a particular IAM policy and can be navigated as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FDMB8Ru6Sirab1YgcXk4K%2Fimage.png?alt=media&amp;token=6788057b-4356-4e5e-bf1e-eb4ccef35ff4" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/images/IAM/latest/UserGuide/images/policy_summaries-pol-sum.png">https://docs.aws.amazon.com/images/IAM/latest/UserGuide/images/policy_summaries-pol-sum.png</a></p></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FPiwZjcQduZQ2xcY5T1sd%2Fimage.png?alt=media&amp;token=e088e81d-f1a3-4630-b1d9-c06a5d3ca271" alt=""><figcaption></figcaption></figure>

### NotResource, NotAction

NotResource is exact opposite of Resource in an IAM policy, With NottResource, one can setup policy like Everything except the one mentioned in NotResource

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FJ8JsjXG00LrtaIOYUlFv%2Fimage.png?alt=media&amp;token=97ccd8c1-c5f9-4269-9688-160e9c7d0251" alt=""><figcaption></figcaption></figure>

NotAction matches everything except the specified action. When effect is allow, it allows all actions except the ones mentioned in NotAction. When effect is deny, it denies all actions except the ones mentioned in NotAction.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fb1GQ9as1WFlMTQxIGVnz%2Fimage.png?alt=media&amp;token=e0e414ea-801c-421c-99b4-20c8288770a9" alt=""><figcaption></figcaption></figure>

### Types of Identity-based Policies

* **Managed Policies**
  * [x] These managed policies are independent resources with their own unique ARNs
  * [x] They can be attached to multiple AWS Identities
  * [x] It can be further categorized as **AWS managed** (cannot be edited or updated by anyone including root except AWS and used for common use cases\[also referred as **Job Functions - which are like full job role that can be assigned to a person**]) or **Customer managed** (as the name suggests, they are managed by the customer of that particular AWS account)
  * [x] It has version control, i.e., it is possible to have multiple versions of a particular policy. Max number of policy versions are 5.
  * [x] The newest version of the policy is default, so if one wants to choose another policy version to be applied, simply change that version as default.
* **Inline Policies**
  * [x] They are embedded in a single identity.
  * [x] They are inline hence cannot be attached to other identity.
  * [x] They are also managed by the customer themselves, hence customizable at any given time

### Policy Evaluation (I)

{% hint style="info" %}
**An AWS identity with multiple policies also follows OR logic when evaluating the final access**&#x20;
{% endhint %}

IAM policy works with the following precedence: Explicit Deny -> Explicit Allow -> finally Implicit Deny. Example: A new user is created and no access was given during creation time, so access to all services in AWS are implicitly denied, post that, if the user is allowed to access certain things, then that would be the case of explicitly allowing or granting them permissions to do certain task, and then if the same user is explicitly denied to access anything then takes the highest priority for denying access to certain AWS services or resources as applicable. This is particularly useful when one has to temporary ban the usage of AWS account by assigning Explicit Deny on the account that prevents the usage of the account.

The evaluation logic flowchart whenever any action would be attempted to be performed is as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F2XroHWCriXpuaEZq7SVS%2Fimage.png?alt=media&amp;token=d384cdeb-5fe7-43fa-8f30-229b6d59f307" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/images/sns/latest/dg/images/AccessPolicyLanguage_Evaluation_Flow.gif">https://docs.aws.amazon.com/images/sns/latest/dg/images/AccessPolicyLanguage_Evaluation_Flow.gif</a></p></figcaption></figure>

The evaluation logic can be summarized as follows:

* By default all requests are denied.&#x20;
* An explicit allow in any permissions policy/ies override the default.
* An organization's SCP, IAM permissions boundary or a session policy overrides the allow.&#x20;
* In short, they must all allow the request for anything to be permitted
* An Explicit deny in any policy overrides any allows

The decision making algorithm flowchart for policy evaluation considering all relevant policies can be as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FpRvT9WjuER85yGXC3fLO%2Fimage.png?alt=media&amp;token=aca6f58a-b095-4aba-bbd7-d0a9d0eedd46" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/images/IAM/latest/UserGuide/images/PolicyEvaluationHorizontal111621.png">https://docs.aws.amazon.com/images/IAM/latest/UserGuide/images/PolicyEvaluationHorizontal111621.png</a></p></figcaption></figure>

### Policy Simulator

Policy simulator allows a way to test and simulate policy changes without applying them. Testing can be done based on policies attached to AWS IAM Identities or based on services, actions and resources. It can be useful to test overlapping policies to understand that if an action is allowed or denied and which statement works and which is preceded

Head over to <https://policysim.aws.amazon.com/home/index.jsp#>&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F8mJ5yoHaBrfWyFuePT3m%2Fimage.png?alt=media&amp;token=ada9535f-7228-4ba7-b60d-0b10fda2f3cf" alt=""><figcaption></figcaption></figure>

### Permission Boundaries

It indicates maximum permissions that an IAM identity can have and can only be attached to an IAM user or role. Note that there can be one permission boundary per IAM identity. This is useful to prevent accidental application of IAM policies to an AWS IAM identity in case there are multiple people in organization that has the privileges to change or add permissions to a Identity.

It works in conjunction with Permission policy as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FItrloBVv0iLDk8GiccY4%2Fimage.png?alt=media&amp;token=3e7ac875-ef40-434f-bb6c-8558e6f0b60b" alt=""><figcaption><p>Source: <a href="https://securityboulevard.com/2023/10/aws-permission-boundary-what-is-it-and-how-to-use-it/">https://securityboulevard.com/2023/10/aws-permission-boundary-what-is-it-and-how-to-use-it/</a></p></figcaption></figure>

One can setup a boundary as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FdL7AlZ1wXdAIQ6rlsLsz%2Fimage.png?alt=media&amp;token=81a44597-5012-43b6-b351-5920f86e4bcc" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FmlXOrHTro2YCpBiFXPGF%2Fimage.png?alt=media&amp;token=55aa063d-d877-4092-b869-3251c8b654d1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F12uClRCUaI4eC80Qpntq%2Fimage.png?alt=media&amp;token=294532e5-3132-4522-a594-f07be226cac0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fwa53kXomaXrYLkt47cvy%2Fimage.png?alt=media&amp;token=81476e62-4fff-4a75-8f4a-0bfb966c8d11" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fj2OYcHvnGVqXTzjdOwEO%2Fimage.png?alt=media&amp;token=a5b8015b-d4f0-4867-b957-8e9bcfafd9a5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fe6bBAQJexHDv6LsQNaYY%2Fimage.png?alt=media&amp;token=588ded5d-f823-4668-8982-3f283db71ab4" alt=""><figcaption></figcaption></figure>

So effectively whoever assumes the role of s3kacommander, will only have the common access which would be that of s3bucketaccess policy simply because it has less permissions and they are the only actions rather than the overly permissive policy of tests3fullaccess and therefore senapati will only be able to access based on the condition set even when senapati assumes the role of s3kacommander

### Other Policy Types

The entire discussion that happened above is for Identity-based policies. Other tyes of policies are as follows:

* **Resource-based Policies**: Available for certain resources such as [S3 ](/aws/aws-storage-services/s3#resource-based-policy)or SQS
* **Organization Service Control Policies:**
  * [x] To understand this, it is recommended that one reads about [AWS Organizations](/aws/aws-identity-and-access-management/aws-organizations) first and understand OU or Organization Unit
  * [x] Sometimes despite privileges, a user is unable to execute commands. This is despite the fact one can have privileges. The reason for that is SCP i.e., Service Control Policies which is always set in Management Account
  * [x] It sets the maximum permissions for an OU and limits permission for entities in member accounts, including each AWS root Account
* **Access Control Lists**: Relevant to storage and buckets and ACLs in firewall (especially for public access). It defines which principals in another account can assume a role.
* **Session Policies:**
  * [x] When one is assuming a role, session policy can be applied to limit what all role can do. It is similar to permission boundary, but there is a difference based on applicability. Session policy is applied only when one is assuming a role. So if the organization wants to limit what a user assuming a role can and can't do, then it can be defined in session policy.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZtLO6SH6N185BmioZ3zg%2F1.png?alt=media&amp;token=db4714fb-2f54-4322-bfed-52516fe9e186" alt=""><figcaption></figcaption></figure>

When an IAM user assumes a role to access a s3, if s3 has a resource policy, and if it mentions Resource ARN, then internally the resource policy is converted to IAM policy to provide access accordingly. If it is session ARN, then it is not converted.

* [x] As per above diagram Scenario 1: A resource-based policy can specify the ARN of the user or role as a principal. In that case, the permissions from the resource-based policy are added to the role or user's identity-based policy **before the session is created**. The session policy limits the total permissions granted by the resource-based policy and the identity-based policy. The resulting session's permissions are the intersection of the session policies and the resource-based policies plus the intersection of the session policies and identity-based policies.

```json
// Identity-Based Policy for DataAccessRole:


{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "*"
    }
  ]
}

// Resource-Based Policy on example-bucket:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:role/DataAccessRole"
      },
      "Action": "s3:*",
      "Resource": "arn:aws:s3:::example-bucket/specific-object"
    }
  ]
}

// Session Policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::example-bucket/specific-object"
    }
  ]
}

// Effective Permissions
The effective permissions will be limited to:
Actions: s3:GetObject, s3:PutObject on arn:aws:s3:::example-bucket/specific-object
```

* [x] As per above diagram Scenario 2: A resource-based policy can specify the ARN of the session as a principal. In that case, the permissions from the resource-based policy are **added after the session is created**. The resource-based policy permissions are not limited by the session policy. The resulting session has all the permissions of the resource-based policy *plus* the intersection of the identity-based policy and the session policy.

<pre class="language-json"><code class="lang-json">// Identity-Based Policy (attached to DataAccessRole):

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "*"
    }
  ]
}

<strong>// Resource-Based Policy on example-bucket:
</strong>
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:sts::123456789012:assumed-role/DataAccessRole/*"
      },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::example-bucket/*"
    }
  ]
}

// Session Policy (applied during the session):

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListBucket",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::example-bucket",
        "arn:aws:s3:::example-bucket/*"
      ]
    }
  ]
}

// Effective Permissions
The effective permissions will be limited to:
Actions: s3:GetObject, s3:PutObject, s3:ListBucket for all objects in arn:aws:s3:::example-bucket
</code></pre>

* [x] As per above diagram Scenario 3: A permissions boundary can set the maximum permissions for a user or role that is used to create a session. In that case, the resulting session's permissions are the intersection of the session policy, the permissions boundary, and the identity-based policy. However, a permissions boundary does not limit permissions granted by a resource-based policy that specifies the ARN of the resulting session.

```json
// Identity-Based Policy for DataAccessRole:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "*"
    }
  ]
}

// Permissions Boundary:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "arn:aws:s3:::example-bucket/*"
    }
  ]
}

// Session Policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::example-bucket/specific-object"
    }
  ]
}

//Effective Permissions:
The effective permissions will be limited to:
Actions: s3:GetObject, s3:PutObject on arn:aws:s3:::example-bucket/specific-object
```

{% hint style="info" %}
Note that **Resource groups** and **Tag editor** are another methods to provide access via IAM
{% endhint %}

### Policy Evaluation (II)

The evaluation logic can be summarized as follows:

* By default all requests are denied.&#x20;
* An explicit allow in any permissions policy/ies override the default.
* An organization's SCP, IAM permissions boundary or a session policy overrides the allow.&#x20;
* In short, they must all allow the request for anything to be permitted
* An Explicit deny in any policy overrides any allows

The decision making algorithm flowchart for policy evaluation considering all relevant policies can be as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FpRvT9WjuER85yGXC3fLO%2Fimage.png?alt=media&amp;token=aca6f58a-b095-4aba-bbd7-d0a9d0eedd46" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/images/IAM/latest/UserGuide/images/PolicyEvaluationHorizontal111621.png">https://docs.aws.amazon.com/images/IAM/latest/UserGuide/images/PolicyEvaluationHorizontal111621.png</a></p></figcaption></figure>

###


# Groups and Roles

## IAM Groups

An IAM Group is a collection of IAM Users. This is used to prevent applying common policies (bunch of permissions) to users individually and instead apply them to the group, of which the users will be part of. This works, because the policies are flow down to individual users, as inheritance of the group membership. Hence, any policy changes done to an AWS Group will automatically be reflected to AWS IAM Users within the particular group.&#x20;

{% hint style="info" %}
Note that IAM Group doesn't have unique identifier i.e. ARN
{% endhint %}

{% hint style="info" %}
There is no concept of group within a group in AWS i.e. Groups nesting is not present
{% endhint %}

### Group Creation

Creating Group with Administrator privileges:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FEy6glqWjJAssovRrZcmL%2Fimage.png?alt=media&amp;token=b85a8114-22b0-43e9-9368-90fd7293ea2f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FowmMjnlIctTw9pXtDytE%2Fimage.png?alt=media&amp;token=4a8a058a-7846-4af6-9dc7-27f95292b3f3" alt=""><figcaption></figcaption></figure>

## IAM Roles

IAM Roles are temporary permissions given to either people or apps to perform a certain task. Consider IAM Role as a hat, whoever assumes it, gets the permissions attached to the role.

An example of It being particularly useful is to consultants or contractors who join the company for a specific project and don't need permanent access to the client's company.&#x20;

They are a also popular choice for Applications i.e., whatever application requires, give it via an IAM role.

IAM Role can be assigned to an AWS service or AWS IAM user account (same account or even different AWS account) or a federated identity (both Web based or SAML 2.0).&#x20;

Benefits:

* No long term credential
* No requiring embedding of permanent credentials to applications
* No IAM user creation for consultants/contractors or other AWS account users
* Allows for federation

AWS AssumeRole enables entities like IAM users or AWS services to temporarily acquire the permissions and access rights of another AWS entity by assuming a specific role. This delegation is defined through a trust policy, which specifies the trusted entities that can assume the role.

Here’s how it works:

1. An entity requests to assume a role by calling the AssumeRole API operation or assumes the role via the AWS Management Console.
2. AWS validates the entity’s permissions against the trust policy attached to the role. The trust policy specifies who can assume the role, typically within the same or different AWS accounts.
3. Once authorized, AWS generates temporary security credentials for the entity, granting access based on the permissions defined in the role’s policies.
4. The entity can now perform actions and access resources using the temporary credentials, limited to the permissions of the assumed role.

To assume an IAM role, one needs a trust relationship that will be configured in trust policy. Just like MSFT Active Directory, there is a trusting account (whose resources are accessed) and there is trusted account (that contains the users accessing the resources of the trusting account).

So, to summarize, for IAM Roles to be effective, there are two types of Policy that are required:

* Permission Policy - Define what actions and resources for an IAM Role
* Trust Policy - Define who is allowed to assume an IAM Role. Note in trust policy, another role is also allowed, i.e. role within a role or role chaining.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FcTG82EEhLxUATI7qkW9N%2F1_e_faUe39DVwrnAlg2nSOfg.webp?alt=media&amp;token=3ad421de-9489-45ba-a513-bf4bb6eb7e5f" alt=""><figcaption><p>Source: <a href="https://miro.medium.com/v2/resize:fit:640/format:webp/1*e_faUe39DVwrnAlg2nSOfg.png">https://miro.medium.com/v2/resize:fit:640/format:webp/1*e_faUe39DVwrnAlg2nSOfg.png</a></p></figcaption></figure>

A Trust policy looks as below:

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:user/AnotherUser"
            },
            "Action": "sts:AssumeRole"
            "Resource": "arn:aws:iam::123456789012:role/Role-A"
        }
    ]
}

```

### Service Role

AWS services assume the service role to perform action on user's behalf. Two types of service roles, with the difference between the two is that one is user defined (service role) and other can be AWS predefined (example EC2 Autoscaling, CloudFormation etc). Note it is usually not possible to delete AWS managed Service-linked policy even by the root account &#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FaPNq2UEa6Rgu0ZEFhD7i%2Fimage.png?alt=media&amp;token=82b1ec72-b8bb-4cfe-9d6b-1803599a0446" alt=""><figcaption><p>Source: <a href="https://anjanashankar.com/2021/05/20/role-based-access-aws/">https://anjanashankar.com/2021/05/20/role-based-access-aws/</a></p></figcaption></figure>

{% hint style="info" %}
**Note that instead of creating long term credentials, as shown in the above image, the EC2 instance profile assumes an role that has access policy to S3 buckets. So, by the virtue of presence of applications on the EC2 instances, they are able to generate temporary credentials to access S3. Here, the EC2 has that trust relationship in form of service role, this means that if tomorrow instead of XYZ application, ABC application gets deployed on that EC2 instance, they will still be able to access the S3 bucket as they are associated with the EC2 rather than long-term credentials which can be hardcoded in the application. This also means, if more than one application is hosted on EC2, every app would be able to access the s3 bucket.**

**Basically, the applications access the s3 bucket using IMDS (Instance Metadata Service) endpoint  on a link-local address of 169.254.169.254 to get short term credentials at runtime and access s3 using that.**&#x20;
{% endhint %}

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FnTVyDZs9vqyhlh3CAs47%2Fimage.png?alt=media&amp;token=38d054c3-79d8-4814-ae08-13f214c35532" alt=""><figcaption><p>Source: <a href="https://anjanashankar.com/2021/05/20/role-based-access-aws/">https://anjanashankar.com/2021/05/20/role-based-access-aws/</a></p></figcaption></figure>

### Role Creation

Note, for role creation, first ensure that AWS Policy is created as shown on below link:

{% embed url="<https://notes.radifine.com/aws/aws-identity-and-access-management/policies-and-permissions#policy-creation>" %}

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FjM1GtnQfOGmMJ735GIU5%2Fimage.png?alt=media&amp;token=e52ccf94-99ac-4d8f-9378-10bf38426a5f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fy9szK8J4X8ndxuVb5zfE%2Fimage.png?alt=media&amp;token=66d16851-84a7-4b78-8a3b-de313570a041" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fsyqfj1ax0427hQQL8cqk%2Fimage.png?alt=media&amp;token=9030ff2f-3480-455d-9fed-194f76edeb3c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FYCbKSg6i6NYzafDnOxkO%2Fimage.png?alt=media&amp;token=99f2936e-6826-4865-97f7-0cda7ce6d0d7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FelF6mSXfttk79CYCFyHc%2Fimage.png?alt=media&amp;token=cd0c7de3-d561-4c9c-89bc-b8b3733c7dec" alt=""><figcaption></figcaption></figure>

The sample role can then be attached to an IAM role in EC2 as shown below during EC2 instance launch configuration:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fy7HLwQuVj7ViKry5laNz%2Fimage.png?alt=media&amp;token=09788c55-b45c-4e29-b934-7fd9489f9f08" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note that you can also attach the role in existing EC2
{% endhint %}

### PassRole

There is something called IAM:PassRole, which allows users to delegate permissions in form of Roles to AWS Services so that they can access other resources or AWS Service. Note that usually the IAM Admin create these roles and allow users to delegate the role to AWS services. Visually, it can be demonstrated as follows:

```scss
// Generated by ChatGPT

[ User/Service ] --( PassRole )--> [ IAM Role (EC2ReadS3Role) ]
        |                                           |
        |                                           v
        |                                  [ EC2 Instance ]
        |                                           |
        |------------------------------------------> [ S3 Bucket ]

```

### Delegation - For Cross Account Access

Just like in MSFT's Active Directory, there is concept of delegation in AWS, i.e., permissions can be given to resources a user controls. As said earlier, the resource holding account is trusting account and users of the account who will access are trusted accounts and therefore trust policy is gonna be required. So, in short, cross account Role is used for delegation

Steps are not given as it requires opening and signing up another AWS account, so due to economical constraints, request you to follow the guide [here](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html).

### Effective Use case

IAM services can interact with each other using IAM Role example: AWS Serverless LAMP stack

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FHBhOoWIiWzRCEGHyBdDV%2Fimage.png?alt=media&amp;token=67b34ca2-e11a-487e-b46a-5c19cd369e99" alt=""><figcaption><p>Source: <a href="https://d2908q01vomqb2.cloudfront.net/1b6453892473a467d07372d45eb05abc2031647a/2020/06/01/Screenshot-2020-06-01-at-17.59.43.png">https://d2908q01vomqb2.cloudfront.net/1b6453892473a467d07372d45eb05abc2031647a/2020/06/01/Screenshot-2020-06-01-at-17.59.43.png</a></p></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FkPd4pjGJbS3kIW2ld8mh%2Fimage.png?alt=media&amp;token=d618a506-5af2-405b-86cc-4c97693bba75" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/images/IAM/latest/UserGuide/images/roles-usingrole-ec2roleinstance.png">https://docs.aws.amazon.com/images/IAM/latest/UserGuide/images/roles-usingrole-ec2roleinstance.png</a></p></figcaption></figure>

### Revoking a session

Sometimes due to unforseen circumstances, an IAM Role assumed session has to be revoked. AWS does that by attaching explicit deny to that session, so that when any action is evaluated, it would be denied

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F3oeKuWl0HojBWd3YkCrY%2Fimage.png?alt=media&amp;token=e22e4f0c-450d-45e2-aa84-4baf583bfd65" alt=""><figcaption></figcaption></figure>

Follow the steps to revoke the steps from here: <https://www.linkedin.com/pulse/aws-under-hood-day-10-how-revoke-temporary-iam-exposed-lakhera-efa7c>


# Federation

The idea of Federation in AWS IAM is that it allows organizations to bring existing authentication in form of on-prem identities (MSFT's Active Directory) or online identities (Google Workspace Identity or MSFT Admin center users or MSFT Entra-ID etc) here in AWS and assign permissions to them, i.e. use existing corporate credentials for authentication and authorization into AWS Console, CLI or direct API calls. &#x20;

### Types

AWS supports different types of Federation, as given below:

* Cross Account Access
* SAML 2.0
* Web Identity
* AWS Directory Service

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZUsxtPv49L7CfVBlHhH1%2Fimage.png?alt=media&amp;token=01438926-8224-4115-be95-938a8212024f" alt=""><figcaption><p>Source: <a href="https://d1.awsstatic.com/security-center/SecurityBlog/federated_auth_with_adfs_5.69a994ecc1645a52e53648efaae211cdfcfaa55a.png">https://d1.awsstatic.com/security-center/SecurityBlog/federated_auth_with_adfs_5.69a994ecc1645a52e53648efaae211cdfcfaa55a.png</a></p></figcaption></figure>

### Cross Account Access

This can be best understood from the following diagram:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F62npn8WApOyHfrcDVplC%2FDiagram_KZ_111616_d.png?alt=media&amp;token=75ed44e7-dba3-427a-8fdd-58c4ecf5ac5c" alt=""><figcaption><p>Source: <a href="https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2016/11/16/Diagram_KZ_111616_d.png">https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2016/11/16/Diagram_KZ_111616_d.png</a></p></figcaption></figure>

Please note that temporary security credentials can be valid from 15 minutes to upto 12 hours.

### SAML 2.0 - For existing Corporate Users

Security Assertion Markup Language or SAML is an open standard supported by many identity providers (IdPs) such as auth0, Microsoft Active Directory, Azure, Google Workspace Identity etc.&#x20;

It requires first setting up metadata, which lays the ground rule for how the communication will happen between the IdP and SP (AWS in this case). Once the authentication is done between IdP and user, then SAML assertion document will be sent by IdP to SP to prove that the user is who he/she claims to be and then based on authorization set in AWS based on IAM role, will get access to AWS services. &#x20;

The following will explain the process better:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F04DgR9WmgQYJJChKRYCx%2Fimage.png?alt=media&amp;token=2189930f-d9d4-4b71-9845-d1edf15ea02c" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/images/IAM/latest/UserGuide/images/saml-based-sso-to-console.diagram.png">https://docs.aws.amazon.com/images/IAM/latest/UserGuide/images/saml-based-sso-to-console.diagram.png</a></p></figcaption></figure>

Note that just like there is sts:AssumeRole, for SAML, there is sts:AssumeRolewithSAML and for Web Users, there is sts:AssumeRolewithWebIdentity

### Web Identity - For general Web users

Popular method for Application logins. It supports Amazon, FB, Google or any **OIDC** Connect compatible Identity providers and integrates with Amazon Cognito as identity broker. Best benefit of these is that End-Users don't need AWS account, and they can still login and access AWS resources (like an image within S3 bucket, let's just say via the application) . The IAM Role that has access to the particular resource can be said to be assumed by the user proving his/her identity using above mentioned providers.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FC67DLmC5gJHnitO3uzSW%2Fimage.png?alt=media&amp;token=5d2d7efe-9daf-4289-ab3b-d95a54b32168" alt=""><figcaption><p>Source: <a href="https://miro.medium.com/v2/resize:fit:720/format:webp/0*adBXuxmDWcJWCgth.png">https://miro.medium.com/v2/resize:fit:720/format:webp/0*adBXuxmDWcJWCgth.png</a></p></figcaption></figure>

### AWS Directory Service

There are basically 3 options, Simple AD, AWS Managed Microsoft Active Directory and Active Directory Connector

* Simple AD - Standalone Samba4 powered Active Directory compatible server. Supports Kerberos and does have user accounts, group membership, group policies but no support for MFA, no trust relationships or PowerShell etc. It works well with AWS apps and services such as Amazon Connect, Amazon QuickSight, Amazon WorkDocs, Amazon WorkMail, Amazon Workspaces etc.
* AWS Managed Microsoft Active Directory, as the name suggests, is simply Microsoft AD in the cloud. It is usually a pair of domain controllers which supports almost all features, supports RADIUS, MFA and secure TLS communication. It requires a VPC with two subnets in different availability zones for redundancy, but does not support NAT. This can be used to keep AD-aware workloads on AWS as well as provide SSO to Office365 and other cloud apps. It is also provides connectivity to On-Prem.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FPHzSioT2GtqTBJoRlrZ0%2Fimage.png?alt=media&amp;token=5fe5134e-1f37-491d-8325-79c60a67f225" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/images/directoryservice/latest/admin-guide/images/ms_ad_use_cases2.png">https://docs.aws.amazon.com/images/directoryservice/latest/admin-guide/images/ms_ad_use_cases2.png</a></p></figcaption></figure>

* Active Directory Connector - A simple gateway to redirect all requests to on-premises Microsoft AD over a VPN connection or AWS direct Connect. It also requires Kerberos pre-auth enabled. It can also be used to join EC2 instances directly to cloud.&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FPRXt5prqQW4ExT6Ahkky%2Fimage.png?alt=media&amp;token=a96c8848-a386-4262-a102-173ff780b99e" alt=""><figcaption><p>Source: <a href="https://aws.amazon.com/blogs/security/how-to-connect-your-on-premises-active-directory-to-aws-using-ad-connector/">https://aws.amazon.com/blogs/security/how-to-connect-your-on-premises-active-directory-to-aws-using-ad-connector/</a></p></figcaption></figure>


# Access Control (via available tools)

## IAM Access Control

Tools that can help in monitoring Access Control are as follows:

* **Credential Report** - It can be used to identify unused credentials and maintain compliance evidences by providing a CSV about password and access keys usage of a particular IAM user with its ARN, creation time, password or access key last used, last changed, next rotation date and MFA active, last used service and also X.509 certificates

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FUGZ2h0EpCMD6JH1PU2v3%2Fimage.png?alt=media&amp;token=2249c0c7-10e8-4e5a-953b-3a41579526bb" alt=""><figcaption></figcaption></figure>

* **Access Analyzer** - A feature in IAM that allows to monitor the usage of policies so that unwanted policies can either be modified or removed. It has service name, policy granting permissions, last accessed, access by members. This is particularly useful to see if a person who has changed jobs or moved from the organization does not have that same level of access, which it discovers by telling IAM policy not getting used. Apart from all these, it can be used to monitor external access also

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FQ3xXcQ1AXklNGDFI11Hu%2Fimage.png?alt=media&amp;token=5e9d9518-3a9d-495b-b308-e59ed1435a2e" alt=""><figcaption><p>Working Model for Access Analyzer</p></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FT8W0KpWZw2a5ugXdm7bW%2Fimage.png?alt=media&amp;token=4c0e9089-f8ab-4462-a2d8-fc09fbdb0ce9" alt=""><figcaption></figcaption></figure>

In short, it identifies resources shared with external principals for few resources such as:

* [x] S3
* [x] AWS KMS keys
* [x] Lambda functions
* [x] AWS IAM Roles
* [x] Amazon SQS queues
* [x] AWS Secrets Manager secrets

Feel free to navigate to the following link to have a more hands-on approach:

<https://aws.amazon.com/blogs/security/iam-access-analyzer-simplifies-inspection-of-unused-access-in-your-organization/>

* **AWS CloudTrail** - One of the foundational AWS logging service that can be used to monitor as collect forensic evidence. More details on[ AWS CloudTrail page](/aws/other-aws-services/logging-and-monitoring/aws-cloudtrail).
* **AWS Trusted Advisor** - Useful for newly created AWS account to know the must do's. It helps with Cost optimization, performance, fault tolerance, security etc. **It has lot of many checks, but are behind a paywall. First thing post setup** should be to check suggestions from IAM

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FRmz4cM3UKBNVHQicLkZf%2Fimage.png?alt=media&amp;token=ac949b73-c4f3-4c9c-ad1e-2c665e4a00d1" alt=""><figcaption></figcaption></figure>

* **AWS Config** - This paid service from Amazon, assesses, audits and evaluates configurations of AWS resources, but where it really shines is its nature for enforcement. It is kind of File Integrity Monitoring but for AWS configurations. Hence the feature list is as follows:
  1. Continuous Monitoring of configurations when it differs from baseline
  2. Continuous Assessment of configurations when it differs from baseline whether the change is permitted or not.
  3. Change Management - view all the changes
  4. Operational Troubleshooting - if any flow breaks, then it can help in that
  5. Helps in Compliance

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F0tYstZugj9Hp9dei61Wt%2Fimage.png?alt=media&amp;token=a6d7bbf2-17e0-43c2-97fe-1aa4eda5fe7a" alt=""><figcaption></figcaption></figure>

W\.r.t IAM, AWS config can help in:

* [x] Monitoring of Root Account MFA enabled or disabled
* [x] Changes to IAM password policy
* [x] IAM policy blacklisted check helps in monitoring if a blacklisted user has suddenly got any policy.
* [x] Monitoring if a group has suddenly got additions or subtractions in its members (useful for checking if any user is part of Admin access)
* [x] If an IAM User has any policies applied to them
* [x] If an IAM group has any user or is it is blank

Setup example for AWS Config:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F7fvCTGbfxCU0Zq4Nt2Nt%2Fimage.png?alt=media&amp;token=f2c43e38-bdbd-4868-81bf-ef94eca0c030" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F8aYlRU3xZRrXph2vtim3%2Fimage.png?alt=media&amp;token=d35427e2-96d8-4017-85c7-7e182c8bc6ff" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F1qQt9p0xJ9z5fP6mWcfR%2Fimage.png?alt=media&amp;token=bc3af99b-21da-4c82-93f7-c147ccfac35c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FyeKXns1QvpiidEdxE7io%2Fimage.png?alt=media&amp;token=c0c61e7f-750c-4c0b-9d5c-1b17cb81d5ff" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note, one can create its own Rules using Lambda and Guard
{% endhint %}

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fwk8kTDmU43W3YfmecBeO%2Fimage.png?alt=media&amp;token=7da17b16-538e-480f-8191-c6dd913597ae" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FbZdUmmTk1Vocuqc1bibV%2Fimage.png?alt=media&amp;token=350ada4b-edfc-4b3f-be37-7c26cc762b27" alt=""><figcaption></figcaption></figure>


# AWS Cognito

Amazon Cognito is a technology that lets app developers implement user sign-up, sign-in and role based access control in web and mobile applications to support serverless authentication and authorization, and when using federated identity, can act as identity broker.

Note RBAC is implemented when users are divided into groups and each group is then provided different permissions

Practical Example, Streaming Platforms can use AWS cognito to let users sign-up and sign-in through Google or Microsoft Accounts or Apple ID and different users would have different viewing permissions to the content the streaming platform will host based on if a user is on ad-supported free tier model or paid premium subscriber.&#x20;

### Identity Sources in Cognito:

Simply speaking, they represents the source of authentication or user pool.&#x20;

* **User Pool Directory** - It leverages Cognito itself as identity source and managing user directory by using cognito user pool that stores identity information (username and password), user profile information (photo, URLs etc), compatible with AWS Lambda as well as supports categorization of users into groups
* **Identity Federation** - It enables users to sign-in with an existing identity source (enterprise, social) (Example: Sign in with MSFT AD, Sign in with Google etc)
* **Identity Pools** - It enables to grant users access to other AWS services. Note this can be used in conjunction with user pool or even separately. Use cases - Direct service integration (client apps use aws direct creds of the service to integrate and communicate with AWS services) and Permission pass-through (it can be AWS Lamda function or other functions that uses the permissions of the user and not the function itself) &#x20;

### Authentication flow:

History and typical use case of AWS Cognito&#x20;

* Previously, the web application tier would be divided into client and server where upon authentication, server would provide  cookies to client and subsequent requests would be interacted with that session cookie. Usually the application logic was mainly on server side and client used to only display rendered output.&#x20;
* This got changed to API based architecture, where the application logic or main heavy lifting shifted to client side and only required data would be fetched from server. So app clients would communicate with  API tier on server i.e., instead of web requests, API requests (which can be said as standalone functions) would be made and based on data received, app at client side can display output. Now, instead of session cookie, the better solution that was implemented would be to use either use OIDC standard via JWT tokens or Cognito User Pool. Either OIDC that allows third party identity providers such as Google, Facebook, Microsoft etc or Cognito User pools allows to authenticate and provide user profile back in those JWTs (this is what actually replaces session cookies and information is provided back and forth into JWT components which are trusted due to the it being digitally signed).&#x20;
* Note JWTs have 3 components: first one is HEADER shows token type and algo, the second one being PAYLOAD has the main part where data about the user and its relevant profile is present and last component is the SIGNATURE part. There are basically three types of JWTs at play, which are ID Token (Contains user identity info), Access Token (Contains groups and scopes) and Refresh Token (Used to get new ID and access tokens), which are obtained upon successful authentication and validity of these tokens can be changed and is mostly configured inside Cognito user Pool .&#x20;
* It is these access tokens that is used to access resources in AWS. The validity of a token can be verified whether it is for specified user pool  (iss), whether the client\_id is valid,  whether toke is not expired, whether token is not expired(exp), whether is time is in past (iat), verifies the token scope, verifies the signature with the user pool keys.&#x20;
* So, how this works is that once authentication happens, let's just say using Cognito user pool, all three JWT tokens are received, which will be sent in future API requests.
* To make this more meaningful, IAM roles can be created that has access to specific AWS services like S3, so whoever assumes the role can access the required resources and these IAM roles are then mapped to Identity pool. So the authentication flows works like that first do authentication and obtain JWT tokens. Using the access tokens, which on user basis, can obtain short term credentials for particular AWS IAM role, which can then be used to obtain resources from other AWS services like S3

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FaUsrdRuIuq6EkRFElyJd%2Fimage.png?alt=media&amp;token=946d0781-7584-4496-a26a-d39fc134f512" alt=""><figcaption><p>Source: <a href="http://blog.jacobmarks.com/2016/12/amazon-cognito-user-pool-admin.html">http://blog.jacobmarks.com/2016/12/amazon-cognito-user-pool-admin.html</a></p></figcaption></figure>

### Creating User Pool

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FyLO6LlPDiIxzkVQHe55z%2Fimage.png?alt=media&amp;token=f200c60c-a534-44e0-a88d-1fbf0c26ac4d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FUlVRgfMEkhT1KxKy5vuS%2Fimage.png?alt=media&amp;token=2aff0742-2eb0-46d2-9338-14286bac1b1c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FndsT2sen4XfmBg45FNe5%2Fimage.png?alt=media&amp;token=8d82c5ec-41c5-45eb-931c-e720bc2221e8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FDLlS4tjdZ8xYCFA6Vnma%2Fimage.png?alt=media&amp;token=c5aa4e2e-2ffa-4710-b5ee-7b8fe1798595" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F94mux1WuJY6vR9ujvgwq%2Fimage.png?alt=media&amp;token=88eae28e-1906-4d6e-bb27-e40a5188760a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F1xLj0XSgbOTc3RS4nmYo%2Fimage.png?alt=media&amp;token=6f065def-c249-4aaf-8500-d4d0eef2bacd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FQp9Eoz6J6kpjkL1COL8e%2Fimage.png?alt=media&amp;token=c3d78558-52fc-49f8-8b19-1ffcf88d298d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FdJ1Zp2tC0j6swqITc8IS%2Fimage.png?alt=media&amp;token=b6a92729-525b-40c5-8122-b88ba986a56d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FedGN03xWFyHprTvqoTQm%2Fimage.png?alt=media&amp;token=57f18ea3-8bf7-4259-8e19-ae01cbd2f07a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FuvEp33lfXU7VVXpkLKuA%2Fimage.png?alt=media&amp;token=27d9d927-95f2-4aed-aaa4-aa127d79e613" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F16xWD7k7avUMZLi1Zhzx%2Fimage.png?alt=media&amp;token=b5920fd5-cc1c-410c-a5b7-7759db7f8dc7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FPiCyUXRBVTobIsMryza4%2Fimage.png?alt=media&amp;token=572f4a37-d3ed-47dd-8634-a6f1c82fa0ae" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FzJxMRoZ5uMM7yaBiS8th%2Fimage.png?alt=media&amp;token=04deaf16-8883-4f31-bff3-cf97b52ca238" alt=""><figcaption></figcaption></figure>

### Creating Identity Pool

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F0j373z4R2G8lRedA5hCL%2Fimage.png?alt=media&amp;token=343983d4-57bf-466f-a06a-81ae3370cccc" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLXLeIe3hzPrIySZ8TaRJ%2Fimage.png?alt=media&amp;token=0d2f57f9-8d88-4b5c-9909-4263455437d5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FXroOsgBt4lnf2nuFbLN5%2Fimage.png?alt=media&amp;token=a805a2d8-370f-4ce8-9eea-2a535078248a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FJrtlTyqY9J0nsPO4meQx%2Fimage.png?alt=media&amp;token=1e0ad1f0-2b1f-45fe-b4e7-75a4df220c27" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FpqKe3QqrIvNJqXry8T8t%2Fimage.png?alt=media&amp;token=acb941c9-54dc-4632-9ebe-41eb5f665cd9" alt=""><figcaption></figcaption></figure>


# AWS IAM Identity Center

### Features

AWS IAM Identity Center (previously known as AWS Single Sign On) offers a secure solution for the central management of workforce identities, allowing to establish or link user identities seamlessly across AWS accounts and applications. That means, if an organization have multiple AWS Accounts, across AWS Organizations, a single sign on to all AWS accounts can be enabled. AWS recommends Identity center as the method for implementing workforce authentication and authorization within AWS, catering to organisations of diverse sizes and types.&#x20;

With IAM Identity Center, AWS customers gain the ability to efficiently create and oversee user identities within the AWS ecosystem. It can be used to integrate existing identity sources, including but not limited to Microsoft Active Directory, Okta, Ping Identity, JumpCloud, Google Workspace, and Microsoft Entra ID (Azure AD).

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F4ApqBiCkqVt5EB679dO8%2Fimage.png?alt=media&amp;token=4d9d9547-530a-42a3-b853-8662e6a649e3" alt=""><figcaption></figcaption></figure>

### Use-Cases

**Enable multi-account access to AWS accounts:** IAM Identity Center simplifies multi-account access management by allowing users to employ their directory credentials for seamless single sign-on access to various AWS accounts. Through their personalised web user portal, users can conveniently view and access their assigned roles across multiple AWS accounts from one centralised location. This streamlined authentication experience extends to AWS CLI, SDKs, and the AWS Console Mobile Application, ensuring a uniform and secure authentication process.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FTFrmYK7td0AMT01Uyzfp%2Fimage.png?alt=media&amp;token=52ec870a-ec8a-43dd-a98f-136275519f51" alt=""><figcaption><p>Source: <a href="https://cdn.hashnode.com/res/hashnode/image/upload/v1684949549669/df98e960-5aed-49fc-9e1c-f8e4f804eaaa.png?auto=compress,format&#x26;format=webp">https://cdn.hashnode.com/res/hashnode/image/upload/v1684949549669/df98e960-5aed-49fc-9e1c-f8e4f804eaaa.png?auto=compress,format&#x26;format=webp</a></p></figcaption></figure>

**Enable single sign-on access to AWS Apps:** IAM Identity Center offers integrated access to AWS applications such as Amazon SageMaker Studio, AWS Systems Manager Change Manager, and AWS IoT SiteWise, enabling zero-configuration authentication and authorization. These applications seamlessly interact with IAM Identity Center to provide a unified view of users and groups, enhancing resource sharing and collaboration within the application environment. This integration ensures an efficient and consistent user experience for accessing AWS applications.

{% hint style="info" %}
**Access EC2 instances running Windows using IAM Identity Center**
{% endhint %}

**Other Use cases** include Logon to M365 applications, Salesforce and SAML based applications, etc. It can also work with multiple Identity Providers such as Active Directory, Okta, IAM stores etc.

{% hint style="info" %}
A web-based portal where users can sign in to access their assigned AWS accounts and applications is generally used as shown above. Organizations can customize the portal with their branding for a cohesive user experience.
{% endhint %}

By default, access to the AWS portal can be obtained via a URL following this format: ‘**d-xxxxxxxxxx**.awsapps.com/start.’ But most organizations customize it as per company branding.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F035R8MBQI1sVVcDx8hgw%2Fimage.png?alt=media&amp;token=bfe98c24-55e2-4305-b4d2-5e4c77ede22b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F4PgFR5ZQ7QH33CR9dfll%2Fimage.png?alt=media&amp;token=fc50809b-beb8-4be0-90bd-cb4cf0f2a1a9" alt=""><figcaption></figcaption></figure>

### Components

When setting up IAM Identity Center, AWS account will typically create an **SSO instance**. It serves as the centralized management point for user identities, access controls, and authentication across multiple AWS accounts and applications. Here are the main components:

**AWS Accounts**

* AWS consumers can link multiple AWS accounts to your AWS Identity Center instance, allowing centralized management of access across those accounts.

#### **Identity Sources**

Individual identities or collection of such identities that can be created and managed within AWS Identity Center or imported from an external identity provider (IdP).

* **Internal Users**: Users can be created directly in AWS Identity Center. Custom attributes can be created to store additional information about users, for finetuned access control and management
* **External Identity Providers**: Integration with external IdPs like Microsoft Active Directory, Okta, or SAML 2.0 providers for user authentication and management.

#### **Permission Sets**

* A permission set is a collection of IAM policies that define what actions users can take and which resources they can access within an AWS account.&#x20;
* It can include AWS managed policies, customer-managed policies, or custom policies.&#x20;
* Permission sets are assigned to users or groups for specific AWS accounts, determining what resources and actions they can access.
* When creating a permission set, AWS consumers can define how long a user’s session remains active before requiring re-authentication, adding an extra layer of security.
* Sample Policy example:

```json
// Created by ChatGPT 
// Role that has read only permissions for Account A: 123456789012 and Account B: 210987654321

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:RunInstances",
        "ec2:StartInstances",
        "s3:PutObject",
        "s3:GetObject",
        "lambda:InvokeFunction"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:123456789012:*",
        "arn:aws:s3:::example-bucket-account-a/*",
        "arn:aws:lambda:us-east-1:123456789012:function:*"
      ]
    },
    {
      "Effect": "Deny",
      "Action": "iam:*",
      "Resource": "*"
    }
  ]
}

```

{% hint style="info" %}
**AWS SSO Admin** refers to the AWS service that allows you to manage AWS Single Sign-On (SSO) features programmatically through the AWS CLI (Command Line Interface) or SDKs.
{% endhint %}

### Device Code Authorization

There is something called as the device code flow (The *device code* grant type) which is generally used on embedded devices. Example: While setting up Google Chromecast, it shows the pin and then one has to enter the same in Android's Home App, so that it reflects there. It works by starting the flow on the device (think apple TV, etc) and then providing the user a URL and 'user code' to access on a more powerful endpoint. The user will navigate to this URL in a full featured browser and provides auth and the user code. Meanwhile, the device, without a browser, is polling a specific endpoint with that same 'user code'. When the user completes authentication, the endpoint will return an access token or other authentication information to the embedded device.&#x20;

Similar is the case with AWS and Azure as Cloud providers when it wants user to authenticate with AWS CLI.  Following are the steps:

1. The user 'registers their device' (creates an app) using the /client/register endpoint i.e., the client application (AWS CLI) registers an OIDC client by calling [sso-oidc:RegisterClient](https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_RegisterClient.html). It does not need authentication to do it. It will return an OIDC Client ID and Secret
2. The user 'authorizes their device' (starts Device Authorization Flow) using the /device\_authorization endpoint. This endpoint takes the client ID, client secret, and start\_url (provided by AWS). The result will be a DeviceCode, UserCode, and VerificationUrl. The client application calls [sso-oidc:StartDeviceAuthorization](https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_StartDeviceAuthorization.html). This generates an URL that looks like *<https://device.sso.\\><region-name>.amazonaws.com/?user\_code=ABCD-DCBA*
3. The user is asked to visit the verification URL and enter the code. Because this is typically all completed on the same machine, the code can be prefilled. Once the user visits the verification URL, they'll be asked to allow access to the device (this is an OIDC consent screen). Upon clicking allow they'll be redirected via the SP-initiated SAML Flow for authentication (if configured). Upon successfully completing authentication they'll be told they can close the window.&#x20;
4. In the back end AWS is recording when the user code associated with the specific AWS SSO start url (and thereby account) has authenticated successfully. Meanwhile the CLI code has been polling the /token endpoint at 1 second intervals (or there abouts) with the deviceCode, UserCode, ClientId, and ClientSecret. Once AWS records the success, this endpoint will return an Access Token (OIDC compliant). Once the end user has accepted the prompt, the client applications calls [sso-oidc:CreateToken](https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) to retrieve an **AWS SSO access token**.

The access token provided by AWS can be used in conjunction with many AWS endpoints including sts.assumeRole(), sso.listAccounts, and sso.listRoles. using sts.assumeRole, a CLI can request a short lived access key and secret for a provided role.

With this access token, the client application can use the AWS SSO API, and in particular:

* List all the AWS accounts to which the end user has access ([sso:ListAccounts](https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_ListAccounts.html))
* List all the roles available to the end user in every AWS account ([sso:ListAccountRoles](https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_ListAccountRoles.html))
* Assume any of these roles to retrieve temporary STS credentials ([sso:GetRoleCredentials](https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html))

#### Demonstration

```bash
// Copy the below command to configure sso

aws configure sso 

SSO session name (Recommended): session1
SSO start URL [None]: https://radifine.awsapps.com/start
SSO region [None]: ap-south-1
SSO registration scopes [sso:account:access]:
Attempting to automatically open the SSO authorization page in your default browser.
If the browser does not open or you wish to use a different device to authorize this request, open the following URL:

https://device.sso.ap-south-1.amazonaws.com/

Then enter the code:

ABCD-DCBA
```

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Frkx9nK922dTTwfSkj7vP%2Fimage.png?alt=media&amp;token=faac5cb9-0019-462f-8f48-d167d300c841" alt=""><figcaption></figcaption></figure>

Once authenticated, it looks something like this:

```bash
The only AWS account available to you is: 123456789012
Using the account ID 123456789012
The only role available to you is: Reader
Using the role name "Reader"
CLI default client Region [None]: ap-south-1
CLI default output format [None]:
CLI profile name [Reader-123456789012]: radisession

To use this profile, specify the profile name using --profile, as shown:

aws s3 ls --profile radisession
```


# Networking and Content Delivery in AWS

## How do AWS provide Networking in its cloud infrastructure ?

AWS implements Software Defined Networking (SDNs) to provide its users with various networking services.&#x20;

### Key Options in AWS

* Amazon VPC - Virtual Private Cloud, the foundational service of AWS.
* AWS Route 53 - DNS Service of AWS, similar offerings such as given by GoDaddy, NameCheap etc.
* AWS Direct Connect - Dedicated connection to AWS with existing on-premises network using a high speed (and low latency) optical fiber provided with AWS Direct Connect Router. &#x20;
* Elastic Load Balancing
* AWS CloudFront
* API Gateway&#x20;

&#x20;


# AWS VPC

Virtual Private Cloud or VPC is an isolated virtual network within the AWS Infrastructure. It is similar to Internet side and Intranet side of an organization's own on-premises data center. Hence, just like any traditional network, VPC supports the following:

* IPv4 and IPv6 addresses
* NAT
* Can be connected to new or existing VPCs
* Can be connected to on-prem network with the help of VPN

&#x20; Also note that, VPCs can be designed to be equally scalable to accommodate more resources.

Now, let's see some technicality of the VPCs. The fundamental blocks of VPCs can consist of the following:

* **Subnets** of a particular CIDR block.
* **Implied Router** implementing the route table. Route Tables controls the flow of traffic in, out and within a VPC.
* **Internet Gateway** (IGW) providing path to and from the Internet for instances with public IP.
* **NAT Gateway** (NGW) \[Public NGW for providing egress only path for instances with no public IP, to reach the internet i.e., internet devices cannot connect back to the source instance and Private NGW for communication with instances in other VPCs]&#x20;
* **Egress-only Internet Gateway** which supports only IPv6 internet traffic.
* **Virtual Private Gateway** (VGW) for providing termination point in a VPC for a VPN Connection or AWS Direct Connect. &#x20;

*Note: One can also use NAT instances available as part of Community AMIs as shown below instead of NAT Gateways, simply because they are cheaper:*

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Filjyjbj3u9hpcU5todMm%2Fimage.png?alt=media&amp;token=ffaa1720-9bd6-4ba8-ba0d-be885125fb00" alt=""><figcaption></figcaption></figure>

## VPC Creation Process

Now, let's use all the above concepts to see practical implementation:

*Step 1*: Create a VPC with CIDR Block:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F4z1zu3t6OVsSsxuaMqeU%2Fimage.png?alt=media&amp;token=a7f7e6d8-5831-4e35-b2ed-cbbaea7b55c2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FEPKnux1GyS2jt1aMhrrK%2Fimage.png?alt=media&amp;token=79113e2b-ad1c-4d4a-b28d-f8d9e3ceeab0" alt=""><figcaption></figcaption></figure>

*Step 2*: Create Subnets from the CIDR block of the VPC:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FRcyaP0pY4R29bAUMNOrX%2Fimage.png?alt=media&amp;token=19e48486-749c-4515-afd3-0ca8f8c88989" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FGmay42dtv0msJxQ938Bn%2Fimage.png?alt=media&amp;token=fefcb2af-646f-4fef-aa44-2e7719e09d35" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FiiqRrHZv9MNoIKGn6rSc%2Fimage.png?alt=media&amp;token=519b47e5-d286-4a0b-9526-a87e7632906d" alt=""><figcaption></figcaption></figure>

*Step 3:* Associating the Subnet with VPC Route Table

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FWqdKHuqM59faaosfhKeW%2Fimage.png?alt=media&amp;token=f2ae7ae9-0fc5-43f8-862a-1e67265942af" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FVhEuTpwUGKta3A73bMds%2Fimage.png?alt=media&amp;token=b6183825-b02c-4a48-95e2-d9c6496d9162" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6PGiMEBtFhlhGXJRmNqP%2Fimage.png?alt=media&amp;token=aca0519d-3b49-491e-8777-1b841d76d7f2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FXlZn2sbrNntdjZK0h90H%2Fimage.png?alt=media&amp;token=041c2cfe-1c22-4c1e-8639-6cc273dfb458" alt=""><figcaption></figcaption></figure>

*Step 4*: Creating Internet Gateway and making changes in route table for Internet Traffic.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FFzn3DY9fZjVIRwgMtZmk%2Fimage.png?alt=media&amp;token=5ede8d2d-5e81-492c-b1ed-0a24c935146b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FRe3vs3g1eS6TPj9ikluD%2Fimage.png?alt=media&amp;token=d0532de0-09cd-4362-af35-214aacfe4eb1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F3SEcaiacy9erhAO7EkJR%2Fimage.png?alt=media&amp;token=4520c459-0e93-443e-9d4d-6ac79c069e4b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FSpkXEnxoodfcah6FqXkt%2Fimage.png?alt=media&amp;token=c85e0832-b13c-47a1-b03e-1f9bdf5bb19f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F5WPrbZ6gs9WY9vWuzMrm%2Fimage.png?alt=media&amp;token=11719679-6dfd-442a-8b24-75781971936d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6Tp4ePNyKHM8vfwfi2H9%2Fimage.png?alt=media&amp;token=9c2e612b-a687-4b75-8586-92b7be4ddb2a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FosKLsLhPyDla2lRqWKCf%2Fimage.png?alt=media&amp;token=bd28e785-da42-48a9-b4e3-b58c7aa77066" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fuq5Z7aLWJsBnNzq7EMS5%2Fimage.png?alt=media&amp;token=dd784eb8-7ee4-447b-93f0-41bd82145279" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F5TrSWiW0cm6inj2sSg0Z%2Fimage.png?alt=media&amp;token=edee56e9-25aa-455f-aeb0-daf5f026eae4" alt=""><figcaption></figcaption></figure>

Now, to put an instance such as a web server in the pub-net range, it is required to follow the steps of setting up an EC2 given [here](/aws/aws-compute-services/ec2).&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FS58EtehUql5FNmfgNnY6%2Fimage.png?alt=media&amp;token=7210f50a-2234-460d-88b0-391d220bb9f4" alt=""><figcaption></figcaption></figure>

## NAT Gateway in VPC

Consider the scenario that there is a VPC, which has a subnet consisting of two EC2 instances with no Public IP Attached to them and the use case is to only provide outgoing traffic. The architecture might look like this:&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FPRoIXDex0ZpulsGTbXrM%2Fimage.png?alt=media&amp;token=7cf18845-0c94-468b-b675-f5ae2ccf8af4" alt=""><figcaption></figcaption></figure>

**Well the above network architecture will fail miserably, because of following reasons:**

* Internet Gateway is still required to sort of provide the path for the NAT Gateway Public IP to connect with Internet. This can be seen in solution point 2 as mentioned in AWS Docs (<https://docs.aws.amazon.com/vpc/latest/userguide/nat-gateway-troubleshooting.html#nat-gateway-troubleshooting-no-internet-connection>).

Hence, the correct Network architecture can be as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F5w4VTAsHXpyFi4zU2Oy9%2Fimage.png?alt=media&amp;token=29a69cba-554e-4c09-af66-9f820a718d12" alt=""><figcaption></figcaption></figure>

*Step 1*: To construct the above diagram, one can first create two instances with no Public IPv4 addresses in private subnet:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FauNmgUiCdsTK1iPvqWCD%2Fimage.png?alt=media&amp;token=51d10f9a-32a7-4295-abdb-19fc1912707b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fs1MCeHrfjZi0gKda8xnd%2Fimage.png?alt=media&amp;token=de038aa1-1e9f-4c1d-986f-1b278c4abf2f" alt=""><figcaption></figcaption></figure>

*Step 2*: Create NAT GW in public subnet

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F0608lyaKim5rkpvr4syd%2Fimage.png?alt=media&amp;token=54a56089-281d-472a-b342-02d8f98bb5bb" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fsx09ekUVeLBbAYmOADxF%2Fimage.png?alt=media&amp;token=c0c76453-0a15-4d6a-a545-a448ebdc43ee" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZMJFHK11o2gVdRzo5Mbl%2Fimage.png?alt=media&amp;token=ec70f154-c946-4320-bdb7-efae2616ca78" alt=""><figcaption></figcaption></figure>

*Step 3*: Edit the route table of a private subnet

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FjcQqXpAduMCJ6KeTkGTh%2Fimage.png?alt=media&amp;token=64f7193c-2db6-4d5d-a410-49472918289b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F4LajPlAYarUipUgEWO26%2Fimage.png?alt=media&amp;token=30e1268b-23bf-4a83-b45e-e9d9e0fa4187" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F2Kh6fE4FSbOsRWQwtbg9%2Fimage.png?alt=media&amp;token=665191f4-655a-4537-b136-b6934bb46ede" alt=""><figcaption></figcaption></figure>

*Step 4*: Similarly, add the route of Internet Gateway to a public subnet

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F7SiuzVsa5GSM1tk9uqWH%2Fimage.png?alt=media&amp;token=cd332916-bb2b-4df2-91db-dda322fa8918" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
What is **VPC Endpoints**?

**These are basically endpoints that allows to connect AWS services that are completely private and not exposed to the Internet for direct communication or Access**.

How VPC Endpoint can be created?

<https://guides.radifine.com/how-to-securely-access-and-transfer-file-to-an-ec2-instance-in-private-subnet-of-vpc-in-aws#heading-step-19-create-vpc-endpoints-for-ssm-access>
{% endhint %}

To connect with instances with only private IP Addresses, one requires a way to connect with them. This can be done with the help of **EC2 serial console** if the instance supports it or one can go with VPC Endpoint of type **EC2 instance connect;** the latter is shown below:

### Connecting to EC2s with Private IP

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FrFgY1MpljjDij4vJ0X1k%2Fimage.png?alt=media&amp;token=3ec0f1db-0bf8-4a7d-a57e-7698dcdf9ff7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FzuKqdfCRrIzPZX5KimcQ%2Fimage.png?alt=media&amp;token=6003724f-b7f8-4fa4-978d-35446a08d215" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FVdtXkNSEAJHOd0Zxtcyc%2Fimage.png?alt=media&amp;token=7206ae4f-abdf-4ded-a3de-2f37e8c523a8" alt=""><figcaption></figcaption></figure>

Now, let's connect with EC2 instances

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FkPR8qetTWvSZRmgJ5k5A%2Fimage.png?alt=media&amp;token=50053b3c-91f5-4376-ba87-e8a8ce727f74" alt=""><figcaption></figcaption></figure>

*Step 5:* Post connecting to one of the instances in the private subnet, one can simply check outgoing traffic as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FfIWAsYqGTjexQPBvgK41%2Fimage.png?alt=media&amp;token=7a815242-78cf-409a-8d05-adeb23638604" alt=""><figcaption></figcaption></figure>

## VPC Peering

For communication between instances in two separate VPCs, one can use **AWS VPC Peering connection.** *For the below peering connection to work, the route table of the two VPCs also needs to be edited to have a route in their respective route tables, such that when traffic to vpc-a is required to go from vpc-b, then vpc-b route table must have a route of source as ip range of vpc-a and target as peering connection.*

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FXsnE7p5GmZm4v5zcVV4y%2Fimage.png?alt=media&amp;token=5a8d0a38-a58f-4502-a018-c8817f386300" alt=""><figcaption></figcaption></figure>

## Transit VPC&#x20;

Note that for Site (On-Prem) to VPC connection, apart from AWS Direct Connect, one can use a Transit VPC. *Transit VPC is like a common hub or gateway to AWS Cloud VPCs. Various Site to Site VPNs can terminate at Transit VPCs and this Transit VPC would have access to other VPCs, where necessary workloads are there. This effectively reduces the no. of connections as shown below:*

&#x20;   *Before Transit VPC*:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F5uFBaju90E7ID7N4mXpH%2Fimage.png?alt=media&amp;token=f0096d84-adcf-436f-989e-f5456b6f119a" alt=""><figcaption></figcaption></figure>

&#x20;       *After Transit VPC:*

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FbHE0zJsV5Qn9FAg9Dddd%2Fimage.png?alt=media&amp;token=5a2f2bbd-5618-4635-a2a0-f8812fed6541" alt=""><figcaption></figcaption></figure>

One thing that must be noted that for the transit VPC to be implemented, following are the steps:

* *Create (Instantiate) a Virtual router with elastic N/W Interface & elastic IP and place it in transit VPC.*
* *Create a Customer Gateway (just an object like representation of the physical or virtual router device) representing Office A Router, Office B Router and Virtual Router in Transit VPC.*
* *Create a Virtual Private Gateway in VPC A, VPC  B & VPC C in order to further create a Site to Site VPN between that of virtual private gateways and virtual routers.*&#x20;
* *Similarly, have a site to site connection between physical router of Office A & Office B with that virtual router for dynamic propagation of routes via BGP.*&#x20;

## CloudHub

Also note down that if two physical sites need to have a site to site VPN, then using concept of CloudHub in AWS, they can be joined. Implementation is similar to above transit VPC process, i.e. creating customer gateways object of routers of the two offices. Creating Virtual Private Gateway, which would be having VPN connection with both the customer gateways and lastly route propagation.


# AWS Route 53

Simply speaking, Domain Name System is a translation of a Domain Name to IP Address. Route 53 is Amazon's DNS Service. Some of its features are as follows:

* Its a global service rather than regional service. It uses edge locations.
* It can be used for global resource routing i.e., it can be sued to redirect the nearest server to a user based on region or country or the server with fastest response time.
* Its highly available with almost zero downtime i.e., it provides failover capability to route the user to different server if the server nearest to them is down w/o the user knowing it.

Let's see how to get started with Route 53 to look into the following sub-services that are available with Route 53:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FgrdQIWIhiEDekbyjbwAj%2Fimage.png?alt=media&amp;token=eb1d577d-67eb-4798-9aaf-b897087fb907" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fr0uAHHLL13GZ8zLZEa7p%2Fimage.png?alt=media&amp;token=b79e3b6d-9689-4733-957e-4d0eab850df3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fa1U9BJjNDx6nEvFNYdbD%2Fimage.png?alt=media&amp;token=50ace239-fe6b-4c9c-9b4a-fed463d2688b" alt=""><figcaption></figcaption></figure>

Route 53 after registering the domain can have various options as per the above features:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fs200qXTRoq8Tv5F83is1%2Fimage.png?alt=media&amp;token=3342b01a-b487-4e9f-910f-a65fa6d27093" alt=""><figcaption></figcaption></figure>

## Hosted Zone

Let's suppose, we have registered a domain on Route 53 or any other domain registration website such as Bigrock or Godaddy or Namecheap. Now, one can purchase and register the domain at one place and can still definitely use AWS Hosted Zone to maintain the DNS records. This is done with the help of pointing the nameservers of the AWS at domain registration website, which can be done as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FtMcGPX0mUD7Q8rcVIsvO%2Fimage.png?alt=media&amp;token=5710021d-1e7a-4708-93cf-bb1d9305ab34" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FC2hOkukxCeqGqRVEvTuH%2Fimage.png?alt=media&amp;token=205aa678-cdec-4602-8fbd-9e05b8e58867" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FbiPNg3Ztmo3lNcr8Gpff%2Fimage.png?alt=media&amp;token=22635953-42dc-4715-9edb-d2ddfa9fa945" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F81m1CevEsKZ8LQot68n8%2Fimage.png?alt=media&amp;token=3b520440-385e-4a40-ba17-dec29a7bc004" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FWPIG6dxm46EY6KsNmaQ1%2Fimage.png?alt=media&amp;token=057de464-3ce6-4c10-bc97-5bd6918138be" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FSQfambD8McvvSI6uZ0W1%2Fimage.png?alt=media&amp;token=87d8a8a2-490b-4420-9562-f12ec6b64338" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FH0J1UZFyew84potkRkww%2Fimage.png?alt=media&amp;token=4f02924c-c53e-40f9-a8fb-9a6c850667ee" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FPZdjcdky08EZOhed2uKx%2Fimage.png?alt=media&amp;token=31806186-342c-4022-9600-50ff141d6811" alt=""><figcaption></figcaption></figure>

Now, there are two ways to create DNS record. One is one record at a time and one is zone wise i.e. by importing the zone file (*filenameofrecords.zone*). Let's look at the latter first.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FhlGQeKoPUioFy2AbO7B1%2Fimage.png?alt=media&amp;token=6a9e4213-0be1-465f-9cb3-68672186653c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FnDf8ffMfSDSLrvJAjCex%2Fimage.png?alt=media&amp;token=2e15e7cc-2029-4837-8833-e340f35c0915" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FOTvpoM2yjeQNi0ZbF71w%2Fimage.png?alt=media&amp;token=87fa2919-4e54-4684-b6e7-40f776e1e984" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FX8aqig3ahHsv6VxbCg8c%2Fimage.png?alt=media&amp;token=df5a7f72-25a4-4ff8-80a5-5858002964fd" alt=""><figcaption></figcaption></figure>

To create a single record, the steps are as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLI3aYC17wqAsarlDGb1C%2Fimage.png?alt=media&amp;token=b470c23c-f10e-476b-add3-08c0308fb560" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FlFlTPtXSTjzMniLMhyd8%2Fimage.png?alt=media&amp;token=1fed1c83-e9e0-4cb5-8eac-e4bc0afd3537" alt=""><figcaption></figcaption></figure>

Now there is a concept of Alias records. These are not CNAME records but rather an AWS concept. They provide alternate Route 53 way to AWS services such as S3 or Elastic Load Balancers, CloudFront etc. One can simply set the alias record as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLgI5QYbZBYm8e0GCH99m%2Fimage.png?alt=media&amp;token=f2148256-d0a0-47a2-836c-d727b8a832a6" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FKXmB8AyH98Pr87nQtRfv%2Fimage.png?alt=media&amp;token=e65d26b9-e0c8-481e-8175-a7f5b3e8b633" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F7psIPPiMMa5KLQ0B5Vjo%2Fimage.png?alt=media&amp;token=08ced1d1-8a63-4144-9ce6-3e5e214ea789" alt=""><figcaption></figcaption></figure>


# Elastic Load Balancing

Load Balancing is a networking concept that is used to distribute loads or in simpler terms, let's just say traffic to different servers of the same application. This is particularly useful to improve fault tolerance and performance of applications running in AWS.&#x20;

It integrates with EC2, EKS and Lambda easily.&#x20;

One point to be noted here that there are two types of scaling.&#x20;

* [x] One is vertical scaling, meaning to increase the compute or memory or storage capacity of the instance to meet the demand, but downside is that EC2 needs to be turned off before it can be scaled.&#x20;
* [x] Another type of scaling is Horizontal scaling that can leverage Elastic Load Balancers. Here instead of increasing capacity of existing EC2, another EC2 is spun up (can be done using [auto scaling groups ](/aws/aws-compute-services/ec2#auto-scaling-groups)of EC2) and then using elastic load balancing, the traffic is routed between existing and new EC2. &#x20;

ELB also supports Availability Zone Balancing; meaning if different servers hosted on EC2/EKS/Lamda  for the same application or use case are distributed across different availability zones, then ELB can be used to serve the user with nearest one, for enhancing the user-experience.&#x20;

### Working of Load Balancer:&#x20;

* Load balancers have a listener that receives traffic and forwards it to internal web or app server depending on the application architecture.&#x20;
* Usually the recipient of the load balancer traffic is configured in form of target group.
* Also important to note that load balancer configuration has something called as target type, which can be either instance or IP. When instance is there, the traffic is forwarded to its Internal IP Address on primary interface. And when IP is selected, private IP has to be specified which can be associated with an interface, other than primary, considering the instances has more than one IP other interfaces.
* The members of the target group are also subjected to a health check to know if traffic can be passed to it or not. This health check is usually done in form of a GET request and successful response ensures that the instance member has passed it or not.

There are four types of Load Balancers:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLEbNtZHw3X1WIpepAYvh%2Fimage.png?alt=media&amp;token=624e3403-7e67-4823-aa72-6ead9506f0d7" alt=""><figcaption></figcaption></figure>

## Application Load Balancers (ALB)

* For passing traffic based on request attributes.&#x20;
* It uses Round Robin algorithm to select the target each time.
* Supports WAF to be used in conjunction with ELB.&#x20;
* Please note that it terminates the client connection by responding to them post looking at HTTP headers and can use any port from 1-65535 for HTTP and HTTPS.&#x20;
* It supports Path and host-based routing (particularly useful for microservices based architecture)

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FVEnaNTFH0Fb15UI8VEAz%2Fimage.png?alt=media&amp;token=5de74a24-2786-481d-88bc-946997bf2ba3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fjz1KnKk0K2MwzIbUbT9T%2Fimage.png?alt=media&amp;token=a50ea41c-4632-41de-927a-8eeee60a33ed" alt=""><figcaption></figcaption></figure>

## Network Load Balancers (NLB)

* For passing traffic based on layer 4 protocol and port number.
* Supports any TCP Connection.
* It uses Flow Hash algorithm for even selection of all targets.
* It passes the traffic as it is and does not terminate the HTTP or HTTPS client connections. Hence, the target remains the same tillthe TCP connection is timed out.
* It does not support host or path based routing

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F8jTI2A57JLq3d2AwYhFh%2Fimage.png?alt=media&amp;token=dbc36197-0c15-4d15-a0fc-b341d9277440" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZtXkrJYgERY7RoXHZcQV%2Fimage.png?alt=media&amp;token=d71a66a2-41c6-43c0-a012-a5025bd0615c" alt=""><figcaption></figcaption></figure>

## GateWay Load Balancers (GWLB)

* For passing the traffic through security appliances.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FSGvxSC3D5VEQcU0JwIIl%2Fimage.png?alt=media&amp;token=a6857535-d4a7-48a4-9b69-480d8e7fa127" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZhDvKT9HXXDsf4ZA4fPN%2Fimage.png?alt=media&amp;token=5fcb17f6-2c94-4071-aefb-c85bf8369c8b" alt=""><figcaption></figcaption></figure>

## Classic Load Balancers (CLB)

* For load balancing based on EC2 instances individually.&#x20;
* This is usually used for Network of old EC2 Classic Instances (applicable before 2014) and hence not recommended for VPC deployments

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FKXM1yLuShLyjmjxUqUZX%2Fimage.png?alt=media&amp;token=30dc30e7-3064-491d-b915-07bc19a8e8df" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fyc2xBuTU5BnkMPpaCVm7%2Fimage.png?alt=media&amp;token=9c5ae5c0-04f1-4295-aeff-d531556f5138" alt=""><figcaption></figcaption></figure>

Note: *Sticky sessions make sure that when a user connection received to ELB gets forwarded to a server, all the subsequent connection remains to that server for a specified period of time to prevent bouncing of connection to other load balanced server*

Note: *Idle Time outs ensures a client connection that is no longer being used, gets closed after a specified number of seconds.*

### Configuring Application Load Balancers.

Consider an application with following architecture:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FBxLLhhq9ckqyWAom8utS%2Fimage.png?alt=media&amp;token=23cd9000-7241-470e-89d5-cccfa4719cad" alt=""><figcaption></figcaption></figure>

webs-1, webs-2 and webs-3 are three web servers in three different availability zone and are part of subnets websnet-1, websnet-2 and websnet-3 respectively which is having private IP range of 172.31.1.x/24, 172.31.2.x/24 and 172.31.3.x/24 correspondingly.

To load balance, the first thing needed is a target group, which can be configured as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FbdGtRHoLD9fmk7URoqWI%2Fimage.png?alt=media&amp;token=d1a84580-a266-4e79-b279-c38b2a123feb" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FdkewuWYgZ9K6XRmX0Zod%2Fimage.png?alt=media&amp;token=8c8a785c-0ded-436f-b2a4-c40241e37695" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FBh0xbRPTVh4I9EyPPwta%2Fimage.png?alt=media&amp;token=f0fa64f4-9127-4ef2-af3d-5efa8af9cd7d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FhpjBeZ5om5fQ6HiJwPGZ%2Fimage.png?alt=media&amp;token=5b5c1196-f676-433d-b537-66327af08904" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fqm4AOzp6bIwfsNLDAmGd%2Fimage.png?alt=media&amp;token=6d55aa39-4e28-48c3-9a6a-dd6f3631198b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FNdJNGwDkv4ZrHCaQKyaY%2Fimage.png?alt=media&amp;token=2b0bdd52-83a8-416e-81f5-e5a4486a542c" alt=""><figcaption></figcaption></figure>

Now, let's see how one can find the creation page for a load balancer on AWS portal:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fn1IWPbXMNzXe7aV4FNcD%2Fimage.png?alt=media&amp;token=f8e39eb4-f62e-4eeb-87d6-88b70e93a07e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6BJaMJitGgUKGmNkIjtC%2Fimage.png?alt=media&amp;token=e92f12fc-3446-4a27-8a7a-1509de035917" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F98tHbmzNn1gHAamKW4Ds%2Fimage.png?alt=media&amp;token=8fb5015b-b849-407c-a32a-21c224653b8d" alt=""><figcaption></figcaption></figure>

*Note, if the load balancer would have been internal, then instead of internet facing, we would have selected internal in the scheme area as shown above.*

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FxadDjMZD7mH0ik4hMuqw%2Fimage.png?alt=media&amp;token=e4c488b0-054e-420c-94b6-941fd3a8f7f6" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FxgZeFJtx882ClmqArWoV%2Fimage.png?alt=media&amp;token=ef69b735-9659-4d2a-88b7-9b9a28a3ef98" alt=""><figcaption></figcaption></figure>

*Note that for HTTPS, one can set the listener to 443 and since it uses TLS, a certificate is necessary to be given to load balancer listener as shown below:*

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fvch3C3VFAbu93G0uIeI5%2Fimage.png?alt=media&amp;token=18bcefcb-9e95-4ec3-bd14-2d117119ed18" alt=""><figcaption></figcaption></figure>

Rest from below, common wizard options are shown:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fl59yTZtNTYmSMvuBHabT%2Fimage.png?alt=media&amp;token=801c1849-5fe1-451b-92fe-dd1aa2a7c993" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FGY8ZnsMRmK6eCH4gr4Jy%2Fimage.png?alt=media&amp;token=2e1063e7-ba7f-4bb0-bf62-09bb54e3554b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FohVW61arhPHVCJz3jhxH%2Fimage.png?alt=media&amp;token=33623f95-1fbc-4580-a74b-2c7d16eb44c8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FndHI4JJUgZfkPSSmZ4gK%2Fimage.png?alt=media&amp;token=f56302e1-0873-41b9-9367-563a09291239" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLsLO5dkE7v6k1WSD1H51%2Fimage.png?alt=media&amp;token=3477743f-d860-47ce-a417-0ebbd340a104" alt=""><figcaption></figcaption></figure>

***Note that one can create an alias A record to load balancer for routing traffic via domain name.***&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FSTlangClcnCbwU2BSTsr%2Fimage.png?alt=media&amp;token=1bfa1cea-bf82-414a-b5d5-c0e39bce99dd" alt=""><figcaption></figcaption></figure>

Now, if one wishes to do rule based routing, one can setup the rules accordingly. Example: There is one domain configured to a load balancer. The requirement is that when the path after the domain name is different in the URL, a different target group (of maybe the same target servers but the service is listening on different port number) should be reached out, so that the resource can be loaded accordingly. To do this, one can set the rules accordingly.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FDqPokYoY1SEUb1RJB7Nc%2Fimage.png?alt=media&amp;token=ce1308c5-aee3-4831-8b0b-638ed256e959" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F1lOzCZSSnRw1nlXwDxha%2Fimage.png?alt=media&amp;token=659b09a9-5966-40c9-9000-cc129480a8f8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FxUH1pygsuVgDQEaiVhh9%2Fimage.png?alt=media&amp;token=bab4153c-8b9d-4b1f-9d32-ac8bd4c2a35b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FBk7pTa8l6iDuYAlp1dbj%2Fimage.png?alt=media&amp;token=5642ccc1-6231-43f3-ba6e-453d85f0a576" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FuTfQd536dfb2dhHfpcG3%2Fimage.png?alt=media&amp;token=42e7d955-6557-4d01-87ca-60a9e38bd83a" alt=""><figcaption></figcaption></figure>

Other rules can be on the basis of:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FiAjRTXaYZqpXwqKcL2OP%2Fimage.png?alt=media&amp;token=ec5fb10f-0820-4d0c-bc6f-dca22a4b9311" alt=""><figcaption></figcaption></figure>

### Configuring Network Load Balancers

The process is almost the same as Application Load Balancers. The only difference is that instead of HTTP/HTTPS, TCP has to be selected.

&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F5qim7iuhOhSOv7Mtnw29%2Fimage.png?alt=media&amp;token=51f17e2f-bde3-49ff-9b69-4f104a7ee6db" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FbYU4wr92cV8Hqd1N5kED%2Fimage.png?alt=media&amp;token=b27017b8-2247-44a3-b6c8-463acc3fda72" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FcS1jVMwdNkcZjd1C9FuH%2Fimage.png?alt=media&amp;token=44d56d38-1980-4e7a-9013-ed993d70bab2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FOERNRG1z4OK6AJMolckO%2Fimage.png?alt=media&amp;token=7fd07bd1-6a47-4591-9279-d8a7a1a67898" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZATs0nIMmKXhQPpYpgmN%2Fimage.png?alt=media&amp;token=64e7a5fa-fe98-42aa-aa37-99955c52f093" alt=""><figcaption></figcaption></figure>

and rest of the process is exactly the same.

*Please note for having HTTPS connection over Network Load Balancer, each target must have the certificate installed individually because one can't install the certificate on load balancer itself as the connection is pass through and terminates directly on the target itself.*

## Session Management

Sticky sessions ensures that a particular client connection always gets forwarded to the same target that it originally gets load balanced to. To do this, the load balancer uses cookie which has a unique encrypted value that changes with each request. When different clients and load balancer are communicating with each other, load balancer identifies a particular client with the help of that changing value cookie and on basis of that, the load balancer forwards every subsequent request to a particular target of the target group. Stickiness duration can range from 1 second to 7 days. It can be configured as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FNF1RBnsUITMXu12OQ39N%2Fimage.png?alt=media&amp;token=52471a0d-5e81-4f75-94ca-3edc8001c68a" alt=""><figcaption></figcaption></figure>

Idle Timeouts maintains the duration till how long a TCP connection for a client is open as it is this TCP connection in which HTTP request and response traverses. idle simply means no data is passing between client and server and default timeout is 60 seconds. If simply due to business or non performance of the a particular target of the target group result into timeout, then client receives a gateway timeout error with 504 code.&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FSd6fCOxDwu3CnZdAr2j4%2Fimage.png?alt=media&amp;token=e05d7d5d-4e51-42f6-8ed8-0811945dbbf0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F3htZvPNOJvpmrFMlaE6x%2Fimage.png?alt=media&amp;token=ebd23820-2ca5-4050-9cce-2c2b226f8766" alt=""><figcaption></figcaption></figure>

Just like idle timeouts are for connection waiting time for clients , keep alive time is for waiting time of load balancer to receive response from the a particular target of the target group before terminating the connection.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fz8KBt4p7WyXZOKsypBBZ%2Fimage.png?alt=media&amp;token=506e325a-77e5-4b67-9a13-85f822f1ffe4" alt=""><figcaption></figcaption></figure>


# AWS CloudFront

## Introduction to CDN

Suppose there is a new website in a local area that is gaining traction. Soon, the organization that is behind the website is experiencing a surge in their traffic from other local areas as well as other countries, but realizes that if they don't serve the content of the website with faster response time, this popularity will eventually fizz out and they won't be able to cash in at this opportunity. Why this is important? Because the websites that loads faster will provide a better user experience as no user in today's time wants to wait longer than expected to consume the content served on their website.&#x20;

So, what's the solution to the above problem? Add more servers that hosts web front end content (Static Content such as HTML, CSS and Dynamic Content such as Javascript). Yeah that solves this problem on a small area wise division where those servers would be put. But what if website is receiving traffic from a brand new area. The organization just can't keep adding servers as this would be costly as well as non scalable. Here enters the service to rescue such situation and that solution is none other than CDN. Yes, Content Delivery Network can be used to provide a scalable solution to resolve the serving of web content faster by having a bunch of servers that are geographically distributed across different locations. This will server the content from the nearest CDN node server to the user. One can consider the CDN server as remote cache of the website. They are basically reducing the distance between the origin of server hosting the content and the user of the website, automatically reducing the load times.&#x20;

Other than the faster load times for better user experience, using caching and optimizations, CDNs are able to save bandwidth, increase content availability and redundancy to hardware failures of web servers by providing alternate servers and may also be able to protect against DDOS attacks and provide fresh TLS/SSL certificates to host. They can also compress files and minification. Apart from that, CDNs use load balancing, failover and anycast routing to make sure that even if other CDN servers or even if the data center goes down, the experience would be seamless and problems would be unknown to the end user and website is always up. CDNs can also provide or enable WAFs to protect the websites against vulnerabilities. Hence CDNs are important for any individual or organization with an internet property. CloudFront is AWS's answer to the service of CDN. &#x20;

## Tech behind CloudFront

As explained in AWS Global infrastructure page, there are many edge locations and regional edge locations that allow caching of the original website. These actually help because the regional edge may cache your website first and then other edge locations can take a copy from regional edge caches instead of taking it from the source directly.  This is known as tiered caching.

CloudFront uses optimizations such as TCP fast open (TFO - alternate to continue TCP connection w/o 3 way handshake for repeated connections), and keep alive connections have definitely improved performance.&#x20;

One Important thing which defines CDN is Caching Behavior, which are set of rules bound to an origin that define how the CDN handles and process incoming requests. This behavior is controlled by multiple configuration settings such as&#x20;

* Path Patterns (it is like caching will depend on matching pattern rule example: /images/\*.jpg -> /images/\* -> \*.gif, so a /image/sample.gif will match with 2nd pattern first so that caching behavior will be used to cache the object from the origin server),
* Multiple Origins (Website components or the entire website can be kept at multiple origins which may depend on the region, i.e, content may change depending on country like in Netflix),&#x20;
* Query Strings (example: search parameter in Get URL of the website can get cached to serve the content faster to newer audience if there is a surge in a certain search query after the first person searches where the content is directly served from origin server and then it gets cached for subsequent searches),&#x20;
* Securing Objects through HTTPS (depending on whether http  is hit or https, different cache can be served)
* TTL (Different TTLs for different cached elements)

The above configuration are complimentary to other elements such as origin behavior, cache duration, cookie or query string forwarding, request headers, compression, encryption etc.

CloudFront's cache retention is made to keep objects longer in cache and to minimize cache churn using techniques like tiered caching (explained earlier) and de-duplication (Instead of caching based on URL for every new request which is different from previous URL hits, it is always better to divide the entire content from origin server into different small elements, also known as chunks; these chunks of elements is kept with unique reference such that these references ultimately add up to serve any content. This ultimately helps to remove redundant chunks and only if new content is asked, then only new element chunk is made).

## CloudFront Features

* CloudFront also supports Pay-as-you-go model. Hence one can use CloudFront when let's just say they have a anticipated demand like during some sale to increase app availability.
* CloudFront Data transfer is free , if the origin server is an AWS endpoint like S3 or EC2 etc as long as the traffic is within AWS.
* CloudFront also supports multiple origins that will enable redundancy.&#x20;
* CloudFront also supports micro services etc to support modern day application tier.
* CloudFront also supports Access Control to kind of provide geographical restrictions to your website.
* CloudFront supports WebSocket, as well as the HTTP protocol.
* CloudFront integrates easily with AWS Shield and WAF to protect against a large variety of attacks including DDOS
* CloudFront integrates easily with AWS Certificate Manager to automatically handle renewal of TLS certificates and provide features such as OCSP stapling (OCSP is a real-time check of the status of a certificate validity, that browser normally performs when a user visits on https website, by checking with the CA that issued certificate has not been revoked and OCSP stapling is a process to keep a digitally-signed and time-stamped version of the OCSP response directly on the webserver for faster TLS /SSL handshakes), session tickets (Session Tickets help speed up the time spent restarting or resuming an SSL session by encrypting SSL session information and storing it in a *ticket* that the client can use to resume a secure connection instead of repeating the SSL handshake process), perfect forward secrecy (Forward secrecy achieved by generating new session keys for each message ensuring that past communications cannot be decrypted even if the secret long-term key is compromised.), and field level encryption (Field-level encryption configurations helps protect specific data that end users inserts in `POST` requests. CloudFront encrypts the data at the edge location, using a public key that is  provided to it, before forwarding the request to the origin. The specific application component that has the appropriate private key can decrypt the data, but the data remains protected as it’s passed through other parts of the system).&#x20;
* One can restrict access to content through a number of capabilities. example, with signed URLs and signed cookies, one can support token authentication to restrict access to only authenticated viewers.&#x20;
* Through Geo-restriction, one can prevent users in specific geographic locations from accessing certain content. With OAI, or origin access identity, one can restrict access to an S3 bucket to only be accessible from CloudFront.
* In CloudFront, Lamda\@Edge can help to serve requests faster than previously by using Edge Locations.
* When certain portion of website (such as css) is updated, CloudFront supports invalidation to ultimately re-cache the new file. If one wants to update files frequently, it is recommended to primarily use file versioning for faster processing. At max, CloudFront supports 3000 invalidations (it can be any combination - 3000 requests for 1 file each, one request for 3000 files or 30 requests for 100 files each). First 1000 invalidations in a month are free, rest are chargeable. These 1000 invalidation is overall limit. If an organization has more than 1 distribution, so 1000 free will be applicable as changes over sum of both and not individually.&#x20;
* CloudFront also supports Error Handling for better user experience

Few important pointers before moving ahead:

The flow of request is is as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FQn5jocG08gTtlCm5mlTO%2Fimage.png?alt=media&amp;token=450d1115-39f2-4886-85d5-d2c6f8dd94c3" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
When the response is served from Cache, it is called as Cache hit and when CDN has to go to origin request to fetch response, then it is called as cache miss.&#x20;
{% endhint %}

## Setting up AWS CloudFront

> Prerequisite : An application hosted on EC2 or Elastic Beanstalk with or w/o Application Load Balancer is required.

There are mainly 3 config parts/areas, which are Origin Settings, Cache Behavior and distribution settings.

* Let's begin with the first one: Origin Settings:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FExFJxDf3WN1X1DqGr5OE%2Fimage.png?alt=media&amp;token=77cd2a55-2720-4e00-af08-6a26c8c759b3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FnocGKXUpOevjC9qExvZl%2Fimage.png?alt=media&amp;token=48efc266-1192-47e7-925f-dcdde14bdad8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fh7XOawaHeDJY3lLHsFRB%2Fimage.png?alt=media&amp;token=89967f39-8479-45f6-975b-b6c6380f6208" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FKWeiridtUvg09ATthQLw%2Fimage.png?alt=media&amp;token=5dad9822-d2fd-47b2-b29d-7477e0264c1a" alt=""><figcaption></figcaption></figure>

* Cache Behavior Settings

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FhlDxlo9XEvI2hdtFm2vT%2Fimage.png?alt=media&amp;token=613881b0-7bab-4d86-a010-3cc7f141d7b9" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F3nClUphSsoALem4xY7ay%2Fimage.png?alt=media&amp;token=57303e75-da3d-44a4-b23b-1a2422114d0f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6T26v8XdPpjqthwyPOEH%2Fimage.png?alt=media&amp;token=414c6961-7ad8-49ed-9b7d-15ccc08c92c4" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F1Aatt418MXILMcdsPIfD%2Fimage.png?alt=media&amp;token=819fd84b-4e9d-483f-9614-d6956b1962ef" alt=""><figcaption></figcaption></figure>

> For static content, managed cache policy of "Caching Enabled" can be easily used&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FH3pJFPfldHEljyZZzd1c%2Fimage.png?alt=media&amp;token=07d800b0-1e17-4eb9-a32b-96e07ffed6c3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FeXpZW61jh2Cq92eu2Uvn%2Fimage.png?alt=media&amp;token=956f0d68-0914-458d-954e-528eeef6b5c3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FrrTci9etJPVchn3oDriE%2Fimage.png?alt=media&amp;token=d9b400f2-ab84-46b9-bc61-5b23e4ff3d3e" alt=""><figcaption><p> </p></figcaption></figure>

> Please refer [this](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/field-level-encryption.html#field-level-encryption-setting-up-step4) for more details about field level encryption configuration&#x20;

* Other Distribution Settings

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FzQrbUGSbk1sSodkzBA9Y%2Fimage.png?alt=media&amp;token=ebd1b53a-bc2e-45fd-898f-67c2570f6b8b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FXsKwctwCtPVrwCNqusuh%2Fimage.png?alt=media&amp;token=c26dd2de-17f4-4dd5-a669-ecd025420658" alt=""><figcaption></figcaption></figure>

### Additional Configuration Options in CloudFront

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FgNFl5lhXLUXAp0kRmvy2%2Fimage.png?alt=media&amp;token=a574014f-72e5-4ca4-938b-3bedf98e4667" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
The above snapshot makes one thing very clear that for a single distribution, there can be multiple behaviors based on different URLs or headers or cookies etc. Hence, it can be said that **CloudFront Distribution is a collection of an origin and all associated caching rules while handling its traffic.**&#x20;
{% endhint %}

### Error Handling

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FvQYQypQu43iFpHl9SgF7%2Fimage.png?alt=media&amp;token=a82c010a-a7d4-4a95-b93c-6168e03147e0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FkPg82EF9TVV0WQG5VJQG%2Fimage.png?alt=media&amp;token=6184d954-d36b-438c-b550-82f81fd80def" alt=""><figcaption></figcaption></figure>

### Invalidations

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FHeKOf1F9shDCKVPmPHpw%2Fimage.png?alt=media&amp;token=8dd93f9d-4e55-4bbc-9f7a-ecc5665375ef" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Invalidations as shown above is basically a way developer or AWS Admin telling CloudFront that its needs to update its cache at the edge location by taking the content from Origin. It does it when the viewer requests the updated file and due to this invalidation configuration, CloudFront considers it as cache miss and gets the file from origin.
{% endhint %}

### Geo Restrictions

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fl1UGdahLXood3TTaYKcx%2Fimage.png?alt=media&amp;token=80d55e74-b595-49c5-ba6d-51b73ff85eba" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FJ2Ir7tS2HCxmL0U3qpLv%2Fimage.png?alt=media&amp;token=9bdf041b-fd7b-4cfc-8e1f-fd0d00ca862e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FHzKBmc54Dl8CIL60w5za%2Fimage.png?alt=media&amp;token=3a63fd8a-3e3c-40bf-8a86-16fe0a299e8d" alt=""><figcaption></figcaption></figure>

### WAF

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6ub04UElXFIZIN4Sjchn%2Fimage.png?alt=media&amp;token=3495e7b0-967b-4644-9aa3-50c45d487b09" alt=""><figcaption></figcaption></figure>

### Origin Access&#x20;

Two ways of Origin Access: Origin Access Control and Origin Access Identity. OAC uses signed URL's/Cookies to restrict access to certain users. OAI uses canonical user of CloudFront to have permission to read a bucket. OAC is more stringent than OAI.

* OAC requires use of Amazon library during development process of application code present in the origin server.&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FmCrGA8l8W1I7X1WPfpDV%2Fimage.png?alt=media&amp;token=7e0cd7fb-f808-4a3a-9156-5c00c82046fe" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FpZXd5AsGENKrNr0zfhNl%2Fimage.png?alt=media&amp;token=e30db935-389c-4476-98f8-c251ad288adc" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FuygrdfWPdVGFS6cenL3C%2Fimage.png?alt=media&amp;token=a90df366-68c4-4959-a6be-7c37a47ceb96" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FuM5BFLpKkM5t5tuzIa87%2Fimage.png?alt=media&amp;token=43f1d91a-6489-4d4c-b23c-69dcf337a955" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FiyvLweIZNEc2RHVr5Ubn%2Fimage.png?alt=media&amp;token=7fc73c0a-ae63-4922-89ec-3f6f1b46e957" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Create 2048 bit new priv key pair online using: <https://travistidwell.com/jsencrypt/demo/>
{% endhint %}

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLLfuvmo8Dt5gyzBBYiV5%2Fimage.png?alt=media&amp;token=2cac3418-41f7-4c97-be71-ea03a6918b91" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fv3Kbh8QGWUeXeTkm840O%2Fimage.png?alt=media&amp;token=d2b6d395-d97a-4898-9d58-e4d172738171" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F7Km1d5PhIc4OKs39yXWC%2Fimage.png?alt=media&amp;token=77fffac3-ace6-4b66-bea7-32d87ca346ef" alt=""><figcaption></figcaption></figure>

Save the above and users will be served with signed URLs of the format:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FzBttmdW1N6r2F5LoTEef%2Fimage.png?alt=media&amp;token=bf820800-7081-4ad2-a671-85e58e6f65fc" alt=""><figcaption></figcaption></figure>

* OAI can be best explained with the following diagram:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FOPOe0SAiibOuDtwhlto9%2Fimage.png?alt=media&amp;token=c700b212-0474-4eec-9560-fe4ee572d645" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fb4dqMGHqi1dw9I78gOPK%2Fimage.png?alt=media&amp;token=a9c5d3bf-c2aa-4f37-a35f-2e607f979a11" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FpESKKcqhiQT50f17Hfpp%2Fimage.png?alt=media&amp;token=10b41720-b336-4859-b784-7efd5e6497d6" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FOumjWXdEqAxFLQxjE2bP%2Fimage.png?alt=media&amp;token=aba93f36-0fd8-4e90-b26b-2facf9e101f0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FPTJT6SzWwZvcrO4dyf6c%2Fimage.png?alt=media&amp;token=b2436902-6ccb-43a9-abef-05779de9a6e8" alt=""><figcaption></figcaption></figure>

Select appropriate settings and necessary details and output can be obtained.

### Field Level Encryption

The use case is explained earlier, i.e. protection of post body parameters. The way to set this is as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FfRU4KJKoEAzo9WnVhuiq%2Fimage.png?alt=media&amp;token=75f62bc6-fde7-4c7e-84ad-672b46f6a600" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FBSYU3M6IDGsUoCjNhWYu%2Fimage.png?alt=media&amp;token=aa2d8d85-2e94-4f60-b499-1e2dd67f6ef8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLFEoAL6MsjdqVfRvQyDl%2Fimage.png?alt=media&amp;token=f4b64355-6e9a-468a-9c25-bdf946622243" alt=""><figcaption></figcaption></figure>

Post that it is possible to set Field Level Distribution in Behaviour page

### Lambda\@Edge

Lambda\@Edge allows devs to deploy Node or Python code at the same edge locations where the content is cached. It's a fully managed solution, so there's no servers to manage, which helps on security, compliance, and also your time and resources.&#x20;

Points to Remember:

* Only Node and Python are supported languages for running on Lambda\@Edge. One can't just deploy Lambda\@Edge by itself. It has to be associated with a CloudFront distribution in order to deploy to the edge locations.&#x20;
* Use Case of Lambda: CloudFront can customize the content delivery perhaps in such a manner that one can send search engine crawlers to a static version of the content while delivering real users to the dynamic version. Another use case is to do content security by adding or altering headers.&#x20;
* Working of Lamda\@Edge:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fm8Gu1l9DdSCMjk5P1KZW%2Fimage.png?alt=media&amp;token=0e1ccadf-21da-43f4-be27-6c8fe6ef9204" alt=""><figcaption></figcaption></figure>


# Amazon API Gateway

### Features

API GW can be said to be a bridge between different AWS services or between Users of a Application and their corresponding backend. It can act as the "front door" for applications to access data, business logic, or functionality from the backend services. &#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FETZkXCiGQOAOXI6xzDTm%2Fimage.png?alt=media&amp;token=b20869fe-eb71-43b4-b6b4-8fc73bf72879" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html">https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html</a></p></figcaption></figure>

**Amazon API Gateway is a fully managed service to create, publish, maintain, monitor, and secure APIs at any scale with the help of API Keys and its tracking via usage plan**. Note that usage plan can be used to put limitations/restrictions on a particular API with the help of Quotas or throttling etc.

API Gateway supports RESTful APIs, WebSocket APIs and even HTTP APIs&#x20;

They support containerized and serverless workloads, as well as web applications. One such use case is its integration with Lambda:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLycEN3dDGaShTSZUgKfL%2Fimage.png?alt=media&amp;token=2d3d2a5b-7f79-4f1f-876a-3ec0810b3ac5" alt=""><figcaption><p>Source: <a href="https://dev.to/aws-builders/two-ways-to-directly-integrate-aws-lambda-function-with-amazon-api-gateway-3can">https://dev.to/aws-builders/two-ways-to-directly-integrate-aws-lambda-function-with-amazon-api-gateway-3can</a></p></figcaption></figure>

API Gateway supports thousands of concurrent API calls, including traffic management, CORS support, authorization and access control, throttling, monitoring, and API version management. &#x20;

The url is of the format: https\://<**random-api-key/id**>.execute-api.<**region**>-amazonaws.com/<**stage-such-as-dev**>/<**resource-name-such-as-default**>

Note that Stage can also have stage variables, which can be used to store configuration without modifying the code (example, URI for uat stage and prod stage can be different and this is stored in stage variables, so dynamically the value can be taken at runtime and used further by the API)

An HTTP or REST API GW can have versions with each version having a method (GET/POST...), Authorization and API Key&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FvuYbHmbaDBzrsGcPtX17%2Fimage.png?alt=media&amp;token=c20a9d5a-fdbb-40c9-a696-b6d9eb27e76d" alt=""><figcaption></figcaption></figure>

API Gateway can also be private and **can be only accessed via VPC endpoints**.&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fc3FZOWELacQqL3vkVYDu%2Fimage.png?alt=media&amp;token=55c5b234-0c51-4df4-87e8-a699fa9f4361" alt=""><figcaption><p>Source: <a href="https://javapatel.wordpress.com/wp-content/uploads/2023/10/rest-private-api-coverimage.png?w=816">https://javapatel.wordpress.com/wp-content/uploads/2023/10/rest-private-api-coverimage.png?w=816</a></p></figcaption></figure>

### Authentication and Authorization

* API GW also supports Standard AWS IAM roles and policies, Endpoint policies for interface VPC endpoints
* Just like S3, it can also have Resource Policy, which can be used to configure for IAM users, Source IP Address ranges or CIDR blocks and even specified VPCs or VPC endpoints (any AWS account).&#x20;

{% hint style="info" %}
Please note that it best practice to specify VPC ID for private API GW in condition.
{% endhint %}

```json
// Generated by ChatGPT
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:us-east-1:123456789012:abcd1234ef/*",
      "Condition": {
        "IpAddress": {
          "aws:SourceIp": "203.0.113.0/24"
        }
      }
    },
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::098765432109:role/MyRole"
      },
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:us-east-1:123456789012:abcd1234ef/*"
    }
  ]
}

```

The authorization workflow with IAM and resource policy can be highlighted as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FDpkIOV9lWyJRWdJzo3k2%2Fimage.png?alt=media&amp;token=539e4f42-c775-4ad5-b181-d301cfeddfec" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-authorization-flow.html#apigateway-resource-policies-iam-policies-interaction">https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-authorization-flow.html#apigateway-resource-policies-iam-policies-interaction</a></p></figcaption></figure>

* It also supports Amazon Cognito User Pools
* One different authorization it supports is Lamda Authorizers

### Lambda Authorizers

It is a lambda function to control the access to a APIs behind a API Gateway. It can be used to build custom authentication or authorization apart from the usual IAM based or API key based.

It uses custom authorization scheme:

* Based on bearer token authentication strategy
* Uses request parameters to determine the caller's identity

There are two types:

* TOKEN authorizer (token-based)
* REQUEST authorizer (request parameter based)&#x20;

Based on authorizer values, access can be granted or denied as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F5acwoPGDcWKfeXPyTkJo%2Fimage.png?alt=media&amp;token=48aecb1a-93d2-494d-97d0-310feee7eaa7" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/images/apigateway/latest/developerguide/images/custom-auth-workflow.png">https://docs.aws.amazon.com/images/apigateway/latest/developerguide/images/custom-auth-workflow.png</a></p></figcaption></figure>

&#x20;Note that policy is usually cached for 30 seconds

### Steps to setup an API Gateway

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FbayQYyLdde2WIAv3NVpr%2Fimage.png?alt=media&amp;token=a82dcc35-33c7-4612-916e-71aec761053d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F4Vu2uTusF6skaYrfmw8p%2Fimage.png?alt=media&amp;token=a04eb0f3-05ac-4778-8201-c8e58b917e40" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FgNPeUnb2ClCNiETyhNqB%2Fimage.png?alt=media&amp;token=d91ea88a-5d75-4174-b7c6-e823b0cfe3e2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F9Q60YyFPkfpElY2nEE0O%2Fimage.png?alt=media&amp;token=7698df22-8884-4cae-9558-6338c88cd075" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FjWiOGznxh3WJ24rg5TyR%2Fimage.png?alt=media&amp;token=37b09dfa-6e53-402d-a16a-7604b35bd779" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FTz3X3BQ3Xeg3txsGrJYn%2Fimage.png?alt=media&amp;token=6efc93f0-4c05-42bb-937f-71a9ec954b07" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FYdKijm2Oa6AGngLGU8J1%2Fimage.png?alt=media&amp;token=2c50bc15-4d94-4070-af76-dcd17af75a22" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F3FsxYu2Pp2Lb10g9Sznu%2Fimage.png?alt=media&amp;token=241df170-80f4-4847-802e-a437b2669acd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FWRfzme3oVNdE8faym4d4%2Fimage.png?alt=media&amp;token=3792c87e-9f44-49b4-866c-cca575cf92e2" alt=""><figcaption></figcaption></figure>

> Head back to Lambda to complete setting up trigger and then use API Gateway URL

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FQQIhWuOJ4BAlVd43z012%2Fimage.png?alt=media&amp;token=95b53e9e-5092-4a0d-8076-7687cc99a5d6" alt=""><figcaption></figcaption></figure>


# AWS Storage Services

It can be divided into three main categories

* File Storage (EBS, EFS, FSx)
* Object Storage (S3)
* Databases (RDS, DynamoDB, Elasticache, Redshift, DocumentDB etc)

For large-scale data transfer, AWS Snowball and AWS Snowmobile can be used.

* AWS Snowball - It is a physical device delivered by AWS that can be connected to a network to physically migrate upto petabytes of data into it, which is then carried by AWS to a AWS data center and then the data is uploaded to S3
* AWS Snowmobile - It is a ruggedized shipping container (on a truck) that supports exabyte scale transfer where AWS sets up a connection to customer's existing network. AWS then loads the data to snowmobile and then the container is  transferred to an AWS data center to upload it to S3.&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fd6vtoJoT1W6Wpwzpme6O%2Fimage-141.png?alt=media&amp;token=f714b131-ad07-49ae-8a60-f849bf44d798" alt=""><figcaption><p>Source:  <a href="https://datavalley-ai-prod.s3.amazonaws.com/files/20230320125139/image-141.png">https://datavalley-ai-prod.s3.amazonaws.com/files/20230320125139/image-141.png</a></p></figcaption></figure>


# Amazon EBS

Basic Description about the same can be found from [EC2](/aws/aws-compute-services/ec2) page.

One can create Volumes as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FEtITpBhqjAbtDwwIFBfs%2Fimage.png?alt=media&amp;token=d0cf8e06-d097-476a-b076-7632bdc02cc6" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FVbE0KEg5syJe6eoFbzVL%2Fimage.png?alt=media&amp;token=d9686bb7-322b-40a7-9911-c8457d444840" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FSOxbEV1BxFV8dxQvcQaG%2Fimage.png?alt=media&amp;token=e8523288-dc29-4ace-b224-c33c4925110f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fo6n4Piy8PVUvsr3GOcmf%2Fimage.png?alt=media&amp;token=0ee99fe6-0a97-44f7-8148-8b146f093d2d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FpgNMHiOWZV08Yqtbtu4Z%2Fimage.png?alt=media&amp;token=0c3f764f-4ece-4c76-8ee4-200d8bb13477" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FnYqOp3lndGAAmkurkU6T%2Fimage.png?alt=media&amp;token=f9df5c1a-17d9-4d81-b002-7cfeca1541fb" alt=""><figcaption></figcaption></figure>

EBS Snapshots can be taken for periodic backup and DR purposes. Hence, to take any snapshot particularly related to EBS, its necessary to either stop the instance (for root volumes) or unmount the instance (for extra drives) to prevent any further write operation, post which the snapshot can be taken.

The EBS Snapshots can then later be made available to other new volumes, which can then be attached to another EC2 instances all together.

&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FkYrkVbGTvlFbYzrEs1bN%2Fimage.png?alt=media&amp;token=006eb81b-c296-4e07-a42d-98ade63b5b13" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FxzoO9BR48MAW7lza9MWl%2Fimage.png?alt=media&amp;token=b76fbb95-0845-42b2-8f38-dedca5911480" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FGNEBAa85CjQSdq420DHC%2Fimage.png?alt=media&amp;token=40411e61-624f-4b48-81d5-26eb35762b8c" alt=""><figcaption></figcaption></figure>


# Amazon EFS

It is a fully managed NFS file system for linux workloads

It supports data across multiple AZs and provides two different storage classes i.e., standard and infrequent access

Unlike EBS, it can be attached to multiple instances even though they are in different availability zones and even with on-prem network

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FOSBEkoCMQg5ynAv4ciOc%2F1_Gig18TiVgWdxXeedc778UA-1.webp?alt=media&amp;token=5fe9a9ea-aa47-46ec-9723-cb2a30c44e33" alt=""><figcaption><p>Source: <a href="https://miro.medium.com/v2/resize:fit:720/format:webp/1*Gig18TiVgWdxXeedc778UA.png">https://miro.medium.com/v2/resize:fit:720/format:webp/1*Gig18TiVgWdxXeedc778UA.png</a></p></figcaption></figure>


# Amazon FSx

Just like EFS is for Linux, FSx is a fully native Windows file system

It supports the following:

* Windows NTFS (note, it is a file system from MSFT for Windows, just like linux has file hierarchy system - FHS, where everything is a file)
* SMB Support
* MSFT AD Integration
* SSD for low latency


# S3

## Features

It is one of the core or foundational storage services from Amazon that lets AWS account users store files as objects in buckets where Buckets are storage containers.

It stores data across multiple availability zone and enable URL Access for the bucket as well as objects inside it

It offers the ability to configure rules for data lifecycle such as expiration time kinda like of OneDrive links that can expire

It can also be used to host static content, so a website can entirely be hosted inside s3. Note that the nomenclature for such is of the format of https\://\<bucket-name>.s3-website.\<region>.amazonaws.com/\<object-name>.\<object-extension>

Cross Region Replication of buckets and objects inside the bucket is available for backup and availability across multiple regions, but that requires versioning of source and destination buckets to be enabled as well as an IAM role might to perform the replication between the two buckets is required.

{% hint style="info" %}
Note even though the bucket can be present in an availability zone, its name has to be globally unique
{% endhint %}

{% hint style="info" %}
Object locking in S3 is supported where the data cannot be deleted, rewritten, or tampered with. It follows WORM philosophy of Write Once and Read Many, particularly useful to establish the inherent trust in data by an unchangeable permanent copy of data for auditing or record-keeping to meet compliance or regulatory requirements. They are a special choice to prove integrity of data when an organization is hit by ransomware attacks. The  objects cannot be tampered, either for a set period (retention) or indefinitely until the lock is removed.
{% endhint %}

## Storage Classes

S3 provides the following storage classes for different use cases:

* Non-Archival Storage Classes
  * [x] S3 Standard: Default storage class, used for frequently accessed data
  * [x] S3 Intelligent-Tiering: Applied on a object and moves those objects to the correct storage class based on usage i.e., moves objects in s3 buckets automatically based on whether it is frequent access or infrequent access. If an object is not accessed for 30 days, IA will move the object into Infrequent access tier, If not accessed for 90 days, Glacier Archive and if not accessed for 180 days, it would be moved to Glacier Deep Archive.
  * [x] S3 Standard-Infrequent Access: For infrequently accessed data with standard resilience i.e., it combines the lower cost of Infrequent access along with resiliency of multiple Availability Zones
  * [x] &#x20;S3 One Zone-Infrequent Access: Same as above just with one availability Zone
* Archival Storage Classes
  * [x] S3 Glacier Instant Retrieval: Retrieval time is higher i.e, in milliseconds. Doesn't require frequent access, but when access is required, it is required instantly
  * [x] S3 Glacier Flexible Retrieval: Flexible in such a time that it can have configurable retrieval times from minutes to hours. It is recommended for backup and Disaster Recovery
  * [x] S3 Glacier Deep Archive: Deep archive that has retrieval time within 12 hours. It is recommended to hold some data for many years maybe for compliance requirement but cost is more important than retrieval times

### S3 Lifecycle Policies

The objects in a bucket can be moved to another storage classes based on the criteria set by the AWS account user. The criteria can be time-based.

It also enables to delete objects based on age. The policies can also factor in versions of a specific object in the bucket, so the policy can set to delete a object that is not current version after a certain period of time

### S3 Transfer Acceleration

It is a feature that can be enabled per bucket that allows for faster upload of data using the AWS Edge locations as a part of AWS CloudFront

{% hint style="info" %}
Note that S3 supports bucket as well as objects level logging to know about the details of when they were accessed, who accessed them etc using AWS CloudTrail
{% endhint %}

## ACL in S3

Note that Access Control in S3 can be applied through various ways., which can be:

IAM Policies -> S3 bucket and IAM User has to be in the same aws account

Bucket Policies -> Can be used to provide cross account access

Access Control List -> Can be set on bucket  and objects in bucket

* READ
  * When applied on bucket, READ ACL allows user to list all objects in the bucket
  * When applied on Object, READ ACL allows user to retrieve the content of objects and object meta-data
* READ\_ACP
  * When applied, READ\_ACP allows user to read the Access Control Policy
* WRITE
  * When applied, WRITE ACL allows user to write an object (Bucket must have write permission)
* WRITE\_ACP
  * When applied, WRITE\_ACP ACL allows user user to write ACL of object and bucket.
* FULL\_CONTROL
  * It allows all the above permissions

ACL is deployed using Grantee as explained below:

<figure><img src="broken://files/23oRGYhOHPFrMKKKsOEu" alt=""><figcaption></figcaption></figure>

ACL Example:

```json
// Here Type needs to have ID, Group needs to have URI

{
    "Grants": [
        {
            "Grantee": {
                "Type": "CanonicalUser",
                "ID": "AWS_ACCOUNT_ID"
            },
            "Permission": "FULL_CONTROL"
        },
        {
            "Grantee": {
                "Type": "Group",
                "URI": "http://acs.amazonaws.com/groups/global/AllUsers"
            },
            "Permission": "READ"
        },
        {
            "Grantee": {
                "Type": "Group",
                "URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
            },
            "Permission": "WRITE"
        },
        {
            "Grantee": {
                "Type": "AmazonCustomerByEmail",
                "EmailAddress": "exampleuser@example.com"
            },
            "Permission": "READ"
        }
    ],
    "Owner": {
        "ID": "AWS_ACCOUNT_ID"
    }
}

```

> Kindly read through the [AWS KMS service](/aws/other-aws-services/aws-key-management-services-kms) before reading down.

## Steps for creating S3 and exercising access control using bucket policy:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Ftu82gjnAnQ4LXdZhQN8F%2Fimage.png?alt=media&amp;token=7ebff60f-43fb-4214-bfcd-d8f6ca89a39b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FnTB4TDYwlMuOvMsLsigb%2Fimage.png?alt=media&amp;token=b993249f-f2d7-42ac-80a1-8e01a0d4b452" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FtyAAKVcbmI94KkRAQG0z%2Fimage.png?alt=media&amp;token=1024818b-3a73-4eba-8605-e485a7b8c6b3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FB6AOgbbK64MSkxSN80MW%2Fimage.png?alt=media&amp;token=f275ac42-4a95-42dc-9cad-e15edc7abc45" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FRws4WJP1raLL4wSSQbqC%2Fimage.png?alt=media&amp;token=c2f6a013-8160-4ddc-8a44-ff6e305dc262" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F0fVnQkmcAhSYRrsunIkz%2Fimage.png?alt=media&amp;token=7f4ef56e-88de-472e-960c-819da5b9c1eb" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F2RV1oRA2nMgQsyZbdmPS%2Fimage.png?alt=media&amp;token=959dc0a1-16f3-4c2c-bcb8-a37e0fbafa73" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FOkh8Zkd9qMIoOc7tRhsR%2Fimage.png?alt=media&amp;token=d3a6d27d-e2f6-4c03-8fbe-1da0fa5e353c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZmRntslBkOazjo4sT83N%2Fimage.png?alt=media&amp;token=0fe1043a-5c14-444a-a3c5-087c03fbc2fe" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F2wwimjh1pdUp7pXBvvE5%2Fimage.png?alt=media&amp;token=d3d532d7-92fe-4669-8e6b-4636543f45a7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FWXTsrl8uuDu7KAZbb1H2%2Fimage.png?alt=media&amp;token=efd3dd5f-af51-4061-b042-53e275b37108" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6UDTFYn8IqtvJZwSP23y%2Fimage.png?alt=media&amp;token=da82f5e6-6efa-4970-8d43-f4cd6da1c000" alt=""><figcaption></figcaption></figure>

#### Resource Based policy for S3 Buckets

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FnM12LZDDJDbOkcQAZ7tF%2Fimage.png?alt=media&amp;token=21b62d54-fd70-4258-96dd-af6f080bd001" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FMEZXE66NFAYNZuuwwncL%2Fimage.png?alt=media&amp;token=018ae23e-1794-492d-b123-2b2184a691eb" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F4gskNZJx99hWqNZ6IRIp%2Fimage.png?alt=media&amp;token=c4ba2dff-8807-464d-a920-6325675a225f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FCbVhRA7uO34axXTsU58k%2Fimage.png?alt=media&amp;token=f61e5299-5cfe-4999-a470-be0b608391dc" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Note that Each IAM entity (user, group, or role) has a defined aws:userid variable. This variable is required for use within the bucket policy to specify the role or user as an exception in a conditional element. An assumed-role’s aws:userId value is defined as UNIQUE-ROLE-ID:ROLE-SESSION-NAME (for example, AROAEXAMPLEID:userdefinedsessionname)
{% endhint %}

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FTCAaeN1k4CcIGdIVu0Xo%2Fimage.png?alt=media&amp;token=a0caeb4c-3332-4a69-a5a4-07a9554e6f61" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FIqOokUCm8xkN9u47h0Sc%2Fimage.png?alt=media&amp;token=8868217f-46ac-45c0-bf2c-31bbcc7afdc7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Felf7jyv8dhO6OKXMV4Df%2Fimage.png?alt=media&amp;token=e7166b6c-cf42-4ace-b4d0-1a751a94cff0" alt=""><figcaption></figcaption></figure>


# AWS Databases Services

Amazon offers many DB Services. Some of the common and noteworthy ones are as follows:

* Amazon RDS (PaaS) - Example: Amazon Aurora Platform
* Amazon DynamoDB (SaaS - DB as a service)
* Amazon Redshift (SaaS - DB as a service)
* Amazon Elasticache (SaaS - DB as a service)
* AWS Database Migration Service (DMS) - It is possible to move existing on-prem databases into AWS Cloud's RDS. This supports one time and continual migration of data. The pay for this migration is not much as it is only for the compute leveraged in migration process.

Additional Database Services can be as follows:

* **Document DB**: It is MongoDB compatible database, which is ideal to experiment in AWS for testing with MongoDB workloads. It is also a PaaS offering similar to RDS.
* **Neptune**: It is managed graph database service, which is ideal for mapping relationships between data points. Very useful for social media companies
* **MemoryDB:** It is redis compatible service ideal for a fast in-memory primary database &#x20;
* **Timestream:** It is serverless time series database service ideal for storing and retrieving time series data points. Very useful for IoT sensors


# Amazon RDS

### Features

It is a relational database that supports MySQL, PostgreSQL, MariaDB, Oracle Database, SQL Server as well as Amazon Aurora

Its a fully managed service offering from Amazon that falls under PaaS category, so it handles provisioning, patching, backup and recovery. It provides both general purpose SSD and provisioned IOPS SSD drive. Because it is a PaaS offering, it is basically a DB application/service on an EC2 instance in a particular VPC.

**Deployment:** The deployment is supported in multiple availability zones. Users can easily launch a relational database instance in RDS. AWS manages the provisioning of hardware, database setup, patching, and backups, reducing administrative overhead.

Amazon's own RDS: **Amazon Aurora** is a MySQL and PostgreSQL compatible relational database built for the cloud that combines performance of traditional enterprise databases with simplicity and cost-effectiveness of open source databases.&#x20;

**Database Engines:** RDS supports multiple database engines, allowing users to choose the one that best suits their application requirements.

**Scaling:** RDS provides options for vertical and horizontal scaling to accommodate growing workloads. Users can resize instances or create read replicas for improved performance and availability.

**Automated Backups:** RDS automated database backups, making it simple to recover data in case of failures or user errors. Users can also set up automated snapshots for data retention.

**Security:** RDS offers robust security features, including network isolation, encryption at rest and in transit, and integration with AWS Identity and Access Management (IAM) for fine-grained access control.

**Monitoring and Metrics:** AWS CloudWatch integration allows users to monitor database performance and set up alarms for proactive issue resolution.

**High Availability:** RDS supports Multi-AZ deployments for failover and read replicas for improved availability and fault tolerance.

AWS RDS simplifies database management, ensuring that organisations can focus on their applications while AWS takes care of the database infrastructure, backups, and maintenance. It’s a valuable service for those looking to run relational databases in the cloud with ease and reliability.

<figure><img src="https://lh7-us.googleusercontent.com/g0B8KC6Yw91a8RbpockE8DBC_QResEPdwMLen96iqvd8zVTgCCOk0yP70BVPMZRUMzLUBr9MkzdromUHAu3G9zjL7fle7K4wQjB_i1t-kZZ5wp4IXz9Ju1nGugVXDyX5-_R122_-HBgf_ukpXaXtyJs" alt=""><figcaption><p>Source: <a href="https://alexanderhose.com/content/images/size/w1000/2023/01/aws-rds-architecture-diagram.png">https://alexanderhose.com/content/images/size/w1000/2023/01/aws-rds-architecture-diagram.png</a></p></figcaption></figure>

### Steps for Implementation

&#x20;Navigate to AWS RDS

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fn7thCnpzJcHl9wcVkbJD%2Fimage.png?alt=media&amp;token=71d8ae15-a2c0-49fa-8467-40dc8e8356c3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FyzdkTCRCXEJ4ZffOSOPO%2Fimage.png?alt=media&amp;token=688fa596-63b1-4839-bcdf-f1b2f886185b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F80yi0F5GUSofRXoyDzRD%2Fimage.png?alt=media&amp;token=308ee6dd-c47d-434d-bff9-bf57f38db90f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLCzuRJ0NlK0WChLZsowE%2Fimage.png?alt=media&amp;token=50e3baa1-7f0a-41fb-9d1a-6d8910012360" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FxGNAJwpZeHsvkOXUv9fe%2Fimage.png?alt=media&amp;token=bf3c53cb-a565-4fc1-8a05-fab577d8086e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FF7CzZ2gKHCdqvKtNhnO3%2Fimage.png?alt=media&amp;token=e9e47171-fcc7-42cb-93b8-a91ebc45f615" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FwpgiKqawKoYAbhJN5iwi%2Fimage.png?alt=media&amp;token=608bfae2-08bc-401c-9c0c-374d390487c7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FcgVxJNfNAUFI55itImqa%2Fimage.png?alt=media&amp;token=93f72999-c645-490f-bc15-4d355a742846" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Refer either of the below links for setting up IAM authentication to RDS over SSM: \
<https://www.nisheetsinvhal.com/blog/how-to-connect-to-rds-using-ssm-and-iam>\
OR\
<https://dev.to/suzuki0430/how-to-securely-connect-to-a-database-from-a-local-environment-using-aws-session-manager-i07>
{% endhint %}

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F06ih2qSxZZWZCOC8hKEm%2Fimage.png?alt=media&amp;token=2265dab2-4daa-48a8-b262-1bd21e66c8c8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FwuxyRMmQynax3fjlq5c2%2Fimage.png?alt=media&amp;token=4037127b-aa7f-46f2-9fed-a7a422962898" alt=""><figcaption></figcaption></figure>


# Amazon DymanoDB

### Features

In  last page, Relational DBs were discussed. The service offering from Amazon for Non-Relational DBs which supports NoSQL for querying part, is Amazon DynamoDB.

Unlike Amazon RDS, which is a PaaS, since this is a SaaS offering, not only, it is fully managed, it is also not required to manage the database layer, so need to think of schema

It provides both key-value and document database.

It provides consistent, single-digit millisecond response times at any scale.

It supports ACID (Atomicity, Consistency, Isolation and Durability) transaction

It supports Identity and Access controls on Table

It supports automated scaling without excessive maintenance and has extremely low latency

It offers in-memory cache with DynamoDB Accelerator (DAX)

It supports server-less applications and it autoscales to support growing demand

### Steps for creating a DynamoDB Table

When creating a table, not that every table is associated with a partition key

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fa6FgqAMgEFTnf4YYduun%2Fimage.png?alt=media&amp;token=4a8557b1-8f53-4603-9d03-c1926895b5e2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FfddMnGxoMWDzlEfjBPNS%2Fimage.png?alt=media&amp;token=e8c3f892-6969-4157-8c5e-76a95bd9f19e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FfddMnGxoMWDzlEfjBPNS%2Fimage.png?alt=media&amp;token=e8c3f892-6969-4157-8c5e-76a95bd9f19e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FL7ShwoZEmYuddDMRSYvt%2Fimage.png?alt=media&amp;token=fe59354c-25f4-4d29-8f7b-b89fac77ce9f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FvEj0yezUfVzgiKuIIQli%2Fimage.png?alt=media&amp;token=15680e3a-65de-40c5-aa5e-667ab730e8fd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FGrVtALHkyXQH31H3qNc1%2Fimage.png?alt=media&amp;token=78c14bd4-bd45-45d8-ae72-5639504cdff2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLnk5IllQ3Yvm2GnUUH42%2Fimage.png?alt=media&amp;token=b66b01bf-2ebd-4988-9926-3db7d382de94" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FWuY3e3VXHbBLRoJSINuK%2Fimage.png?alt=media&amp;token=7178b186-af9c-496f-be24-3a9ba916f337" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FSSdSLpovzH0SWxy1vStm%2Fimage.png?alt=media&amp;token=7a7ff492-c21f-426b-be10-e5fb4604ac5b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FVfaQcjLTas6ai82Wu2rH%2Fimage.png?alt=media&amp;token=cd7feb7f-9e80-4b13-bc0a-46686fabfc39" alt=""><figcaption></figcaption></figure>

Note, DynamoDB supports PartiQL which is used to query NoSQL DB like DynamoDB using SQL queries

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FgDDbpU3YX39uq6YUDsIb%2Fimage.png?alt=media&amp;token=6d7e88ec-57bf-44b1-abf6-e8b98522c77f" alt=""><figcaption></figcaption></figure>


# Amazon Elasticache

### Features

It is the fully managed in-memory data store offering from AWS.

It is supported by by both in memory engines - Memcached and Redis

It provides low latency in response times

It enables scaling and replicas to meet sudden surge in demand from the application

It can be used for database later caching i.e., between the application and actual database, Elasticache can act as buffer to hold the data &#x20;

When a web application is doing session storage, Elasticache with Redis engine can also used to get quicker responses on session data&#x20;

##


# Amazon RedShift

## Features

It is a scalable data warehouse service from AWS that can be used for user analytics

It supports warehousing upto petabytes of data

It uses high performance disks and columnar storage

It has in built feature to fully encrypt contents and also provides isolation within a VPC

It has something Redshift Spectrum to support querying exabytes of data in s3


# Amazon DocumentDB

It is a NoSQL Database


# AWS Compute Services

## What is AWS Compute?

A service that enables to leverage virtual machines on cloud for workloads. This could be for hosting website, running a database, or calculating statistics from a data set.

### Key Compute Options in AWS

* Amazon EC2 - VMs on AWS - **IaaS (Infrastructure as a Service)**
* AWS Elastic Beanstalk - For scaling WebApps and services - **PaaS (Platform as a Service)**
* AWS Lambda - Server-less Architecture
* AWS Container Services such as AWS AppRunner, AWS EKS and AWS ECS&#x20;


# EC2

## Features

It is **E**lastic **C**ompute **C**loud.&#x20;

But What is Elasticity? - *It is the ability for the infrastructure supporting a use case to grow and contract based on how much it is used at a point in time*.

The name has elastic simply because of ability to resize capacities of vCPUs or RAM or SSD. The use cases are limitless.

* One can launch EC2 on basis of the factors such as Instance Types \[Predefined bundle of vCPU (processor), RAM (memory), SSD (storage) Network Bandwidth etc with varying options of General Purpose OR Compute or Memory or Storage optimized etc.), AMI, Purchase Options and Root Device type.
* What is AMI? - Its Amazon Machine Image. Its kind of a like a template of a OS with different flavors of add-ons. AMI when instantiated, usually requires of Root Volume Template, Launch Permissions, Block Device Mapping etc.
  * [x] Root Volumes are usually like hard disk that hold the OS. There are two types of storage (Root Volumes) that can be attached to EC2:

    1. The first one is Instance Store (Ephemeral Storage) - local storage on the bare metal server where instance is stored and it is like RAM (shut down and data gone) & it is physically connected to host on which VM is running, mostly used for temporary computations, storing caches, storing non-critical logs etc&#x20;
    2. The other is [Elastic Block Storage](#user-content-fn-1)[^1] (Persistent Storage), **where Hard disk is separately connected from the host (Network attached storage)** on which VM is running but it will be persistent.&#x20;

       Note that EBS can be attached to only instance at a time and it supports Amazon EBS encryption for meeting regulatory requirements.&#x20;

       It supports petabytes of data and supports multiple volume types based on need such as General purpose SSD (general workloads), provisioned IOPS SSD (High performance low latency), throughput optimized HDD (designed for frequently accessed data) , cold HDD (less frequent workloads).

       It supports data across multiple Availability Zones

  * [x] Launch Permissions decides which AWS Accounts can launch instances of AMI.

  * [x] Block Device Mapping helps in attaching another storage to EC2
    * One Can Create Custom AMI images or use community AMIs or commercial AMIs (all available from AWS Marketplace) for providing OS to the EC2
* **In AWS EC2, there are different instance types, such as t3.medium or m5.large (t starting or m starting is general compute - the difference is that t is burstable and m is non burstable, i.e., for predictive workload, m type can be cheaper as the flexibility of t type may cost more), c5d.24xlarge (c starting is compute optimized), p3.16xlarge (p starting is accelerated compute optimized), i3.16xlarge (i starting is storage optimized), r4.large (r starting is memory optimized)**
* There are different types of Instances - On-Demand, Reserved, Spot, Savings Plan, Spot and Dedicated.&#x20;
  1. On-Demand as name suggests can be spun up and closed at any time. There are no contracts and mostly used for experimental POC purpose.
  2. Reserved -  Cheaper when compared to On-Demand Instances, because of commitment to use a Virtual Machine over a defined period (1 year or 3 year). There are multiple offering class, as mentioned below

     Note that the pricing for the above are based on the following configuration options:

     * Platform - OS such as Linux or Windows
     * Tenancy - Underlying hardware can be dedicated to AWS Account or Default (Shared among multiple instances, even though they cannot communicate with each other)
     * Offering Class -&#x20;
       * [x] Standard (for steady workloads, but lock-in so, can't change),&#x20;
       * [x] Convertible (some attributes can change, but good for steady workloads),&#x20;
       * [x] Scheduled (change possible as per time like weekend, you can increase);&#x20;
     * Instance Type - These are as defined above in bold. In Convertible, instance types may be changeable.&#x20;
     * Term - It can be 1 year or 3 year
     * Payment Option - Payment terms can be All Upfront, Partial Upfront or No Upfront
     * Availability Zone - If this is selected during configuration of RI, it can be termed as Reserved RI, if all availability zones within an entire region is selected for discounts to be applied  otherwise discount can be applied in a single availability zone, to reserved capacity.

     *Note that if suppose an AWS user is signing up for a Reserved Instance for a 3 year plan and then the user does not require that Reserved Instance, let's say after 2 year, then the user can have the option to sell Reserved Instances on Amazon Reserved Instance Marketplace, where there are also opportunities to buy instances for terms shorter than one year.*
  3. Savings Plan is rather commitment to pay per hour that can be utilized for any of the compute services that matches the criteria given at the time of purchasing the plan, rather than reserved instances, where you pay for commitment to use a instance for a standard 1 or 3 year plan.&#x20;
  4. Spot is like of stock market. If the price offered by you to AWS is higher than the spot price, your instance is up. If the spot price goes higher than what you were paying per hour, your instance is terminated. The price difference can be verified from the AWS pricing calculator:&#x20;

     <figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FR2iHt5jxIsJq8p6CX7av%2Fimage.png?alt=media&amp;token=28d95e82-81ce-4b7d-9102-844051289f42" alt=""><figcaption></figcaption></figure>

     <figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F8f2SbWNlDd6ILFPxIrPY%2Fimage.png?alt=media&amp;token=b5af626c-1916-4994-975a-137fa28947c3" alt=""><figcaption></figcaption></figure>

     These are meant for those applications which can be easily operated by starting and stopping them i.e. something which don't have a real time usage and are used to carry out independent work.
  5. Dedicated host is like full physical server for the customer/user in AWS data center. This is the most expensive option. Note the difference between dedicated instance and dedicated host may sound a bit complex, but is not. Dedicated instances means the various instances created by a single customer (AWS User Account) onto the same underlying hardware; that hardware can be the same or different depending upon how many dedicated hardware we have opted for in AWS. Dedicated Host, on the other hand ensures that hardware will always be the same for a particular instances that the user will launch. This is usually helpful for running softwares which binds with hardware device id.

## Setting up an EC2 instance

* To Launch an instance on-demand with default settings, one can follow the steps as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FrISFbhoDPfVNhMTyY4qL%2Fimage.png?alt=media&amp;token=29eab951-f2c1-4dc8-b9c9-8378c52b9309" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F5GBXeGQZ2exkkDQdnlPQ%2Fimage.png?alt=media&amp;token=5d9eb451-fc83-4882-b7f7-e0c504ba114a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FHjmuQKn09UV92IUsLun4%2Fimage.png?alt=media&amp;token=bbe6d212-5fd1-45de-8f40-e31cddb80700" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fju5P7xfEOjOEicAc6ibu%2Fimage.png?alt=media&amp;token=f921510c-176a-459a-b47b-f5eca34e9fc5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FNsNFihtaEj4Fe3Esd5wr%2Fimage.png?alt=media&amp;token=0e762221-b7b1-45f9-b6a6-dff58a374030" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FvW46T2DuUHUwsQuC1VlB%2Fimage.png?alt=media&amp;token=0ec26875-dbd0-454b-a9e3-50531733fa80" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FyWwhSmKqhK9oMwXpucvY%2Fimage.png?alt=media&amp;token=4a45f283-9ff8-4615-8ad1-6520e06e3180" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FsReyeKREgX0zwyaM0Vnb%2Fimage.png?alt=media&amp;token=a1831afe-6fb6-4596-9a30-11f566aed3ab" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZfxg0IS7BB3DI6qalKmv%2Fimage.png?alt=media&amp;token=aa715ce0-7b6d-4898-b014-4df48deb3189" alt=""><figcaption></figcaption></figure>

Now, there are three ways to go ahead (One is Auto Assign Public IP, One is Assign Elastic IP and last is not to assign an public IPv4).&#x20;

* [x] For letting AWS assign and attach an interface with changing IP addresses during server restart (stop instance and then again start instances)

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FfxycelkhjzTho7XmvbPy%2Fimage.png?alt=media&amp;token=20a52c92-d183-40be-97ad-e3687347f8ae" alt=""><figcaption></figcaption></figure>

* [x] Another way is to create N/W interface and assign elastic IP (which won't change even after when the server restarts, post stopping am instance as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F1iSVb0WK45piAcVws9VB%2Fimage.png?alt=media&amp;token=569aea8e-8381-46dc-a03e-0ee8f319e7c5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FEllrVu3axNi8HsK8ZNTM%2Fimage.png?alt=media&amp;token=4624f39d-c2e3-45e3-88e6-d3f612f29a38" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FABjTPx63Q27Pmz37WTg2%2Fimage.png?alt=media&amp;token=1a5dff7b-0824-4083-aa4b-68ab2ce7b570" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F4Dr29nqqiFzQF8r4v02p%2Fimage.png?alt=media&amp;token=e13cebda-5799-4d43-99ed-a1a244442b02" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FGCHdFQWsE8h00p689Fou%2Fimage.png?alt=media&amp;token=3ecd8193-9d53-4ad5-ae52-7d7c50f73054" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FKmo7VBThK3TeamU67TZ3%2Fimage.png?alt=media&amp;token=d3400094-8a7a-4503-ae78-2ca8d66da11d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FzH3MTgOet9snqouakVDW%2Fimage.png?alt=media&amp;token=f356dfd8-a603-421b-97be-984c8404112f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FUdddsTYds2UHm8mFxd0L%2Fimage.png?alt=media&amp;token=63e3acb9-99ef-42e3-b6b6-3ec5ca0679df" alt=""><figcaption></figcaption></figure>

* [x] No Public IP to be assigned. For providing Internet, one can use NAT Gateway

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FvB2Uf4v9HYxqmqSzuL94%2Fimage.png?alt=media&amp;token=2a4eaef3-6ef7-421c-b493-68e49ef2e3cb" alt=""><figcaption></figcaption></figure>

From below, steps to further configure an AWS instance merges from the above three NIC variants shown above

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FihZKh7ftho3BEeX7tqj4%2Fimage.png?alt=media&amp;token=047bafaf-d705-47d7-b444-a99c4d53193f" alt=""><figcaption></figcaption></figure>

**Here, IAM Instance Profile can be used to provide role based access to EC2 instance**.&#x20;

**The EC2 instance profile assumes an role that has access policy to S3 buckets. So, by the virtue of presence of applications on the EC2 instances, they are able to generate temporary credentials to access S3. Here, the EC2 has that trust relationship in form of service role, this means that if tomorrow instead of XYZ application, ABC application gets deployed on that EC2 instance, they will still be able to access the S3 bucket as they are associated with the EC2 rather than long-term credentials which can be hardcoded in the application. This also means, if more than one application is hosted on EC2, every app would be able to access the s3 bucket.**

**Basically, the applications access the s3 bucket using IMDS (Instance Metadata Service) endpoint  on a link-local address of 169.254.169.254 to get short term credentials at runtime and access s3 using that.**&#x20;

{% hint style="info" %}
The IMDS service can be used to fetch the following metadata. It is the way by which AWS makes configuration data available to EC2

* Public IP Address
* UserData
* Security Groups
* Instance details
* IAM Access Credentials for the EC2 instance

The url is **<http://169.254.169.254/latest/meta-data>**

AWS IMDSv1 (Instance Metadata Service Version 1) and IMDSv2 (Instance Metadata Service Version 2) are services provided by Amazon Web Services (AWS) that allow EC2 instances to retrieve metadata about themselves and interact with the instance’s local configuration. While both services serve similar purposes, they have significant differences in terms of security and functionality.

**IMDSv1** was the original metadata service provided by AWS. It allowed EC2 instances to access metadata by making HTTP requests to a predefined local IP address (<http://169.254.169.254>). While it was useful for retrieving instance information and user data, it had some security concerns, as it didn’t offer strong protection against potential attacks.

**IMDSv2**, introduced to address these security concerns, enhances the metadata service significantly. IMDSv2 provides a more secure and robust way to access instance metadata. It uses a session-based approach, requiring an instance to authenticate and use a short-lived token to access metadata. This mitigates risks related to potential exploitation of the metadata service by unauthorized entities, making it more resilient against various attacks.

**For the instance’s hostname**:&#x20;

curl <http://169.254.169.254/latest/meta-data/hostname>

**For the instance’s AMI ID**:&#x20;

curl <http://169.254.169.254/latest/meta-data/ami-id>

**For the instance type**:&#x20;

curl <http://169.254.169.254/latest/meta-data/instance-type>

**For getting the public IPv4 address assigned to the instance**:&#x20;

curl <http://169.254.169.254/latest/meta-data/public-ipv4>

**For getting security groups associated with the instance**:&#x20;

curl <http://169.254.169.254/latest/meta-data/security-groups>

**For getting the EC2 Instance Profile credentials of the IAM role (if a role is attached to the instance)**:&#x20;

curl <http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name>
{% endhint %}

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FyPy6aZmnxsmz7Aylqr5C%2Fimage.png?alt=media&amp;token=113716ff-e268-466b-8679-1bd745a1c595" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F7MZjBhyMEHdT55wzgz4Y%2Fimage.png?alt=media&amp;token=819ed610-eb98-472d-99ab-983642dff893" alt=""><figcaption></figcaption></figure>

*Note:*&#x20;

*a) Placement Group allows to specify how instances are placed on underlying hardware. There are three types, namely cluster, partition and spread.*&#x20;

1. *Cluster helps to keep the two instances very near to each other within an availability zone with having a far better instance to instance communication for low latency and high throughput.*
2. *Spread offers hardware isolation, i.e., each instance in run on separate hardware.*
3. *Partition is a hybrid of above two, i.e., suppose there are 8 instances then there would be group of 4-4 instances within a partition. So, instance to instance communication within the same partition is very fast; at the same time, they are isolated with the other set of partition on hardware level.  These are also called as nodes*

*b) The On Demand Capacity Reservation is different from Reserved instances. This was introduced during Covid crisis. Because of huge shift to cloud, many new users were launching EC2 instances, and old users were getting error  of type "No capacity on host to run the instances". Hence, AWS came up with the idea to pre-book a slot for on-demand instances at no extra cost, but providing users a way to get guaranteed capacity to run shorter term workloads which can be turned on and off at any given time.*&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F29WoOzDXLtolT9duJlXu%2Fimage.png?alt=media&amp;token=5708762e-85f8-4ece-aa1b-2f34003fd9ac" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6mWv6BgfdDVjCEnObFay%2Fimage.png?alt=media&amp;token=8095da5c-f23c-4a5b-a64b-99b386dfd845" alt=""><figcaption></figcaption></figure>

*Note: Whenever selecting AMI (Amazon Machine Image) from Community or AWS Marketplace, one can find that Amazon supports two types of images. One is HVM (Hardware Virtual Machine) and other is PV (ParaVirtual). To learn the difference, kindly check out the below data sourced from the AWS Docs:*

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FizH7DfgkS1LlVTifpJHh%2Fimage.png?alt=media&amp;token=42388ed9-6687-46b8-821a-131896b889e1" alt=""><figcaption></figcaption></figure>

## Reserved Instances&#x20;

Let's now see about reserved instances launch:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FHOcUPeu59KGX3JDuHv6Z%2Fimage.png?alt=media&amp;token=503a592d-1b64-4486-acfb-9924be8cd6c9" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FaPB7CDVfoMymvb6VbuWc%2Fimage.png?alt=media&amp;token=914b7c8b-4692-4064-a99b-400458a4d354" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FKI9hXrjaqL6hAc3aIbV3%2Fimage.png?alt=media&amp;token=8241023f-1b37-418d-a9a7-cde72bc2958d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F2P7ss47vKdw9aNXpmEIk%2Fimage.png?alt=media&amp;token=a8866229-b766-4a22-a4c0-2d3f4cff7ab3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F1rySdXAnv4TXJSKMT9PZ%2Fimage.png?alt=media&amp;token=5c4f004f-0e51-43de-80e4-b9a59cdf2150" alt=""><figcaption></figcaption></figure>

* Post this, launch the instance of the exact same configuration just like an on demand instance and it would eventually be shown into the reserved instances section, solidifying that reserved instance discounts are being applied on the turned on instance

## Spot Instances

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F78rIRljGpEhMaEqHjk0J%2Fimage.png?alt=media&amp;token=e4f69a94-5f8c-442e-a081-98519e1e34f5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FI9Gdzt50L0mlHUqDeapG%2Fimage.png?alt=media&amp;token=8d926475-5fda-4097-a553-928ae0e583bf" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FVoLHDC4tMG9BSuo51R9V%2Fimage.png?alt=media&amp;token=f58a4342-d089-4422-b001-25e18a2347b4" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FCC7eEuaKU77PUoVbvT8H%2Fimage.png?alt=media&amp;token=be9a0a13-6870-4653-b6cb-f7e3ecdcae97" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FMSgrMPKOLGP59xWDEmt6%2Fimage.png?alt=media&amp;token=6b6861c4-11cf-436a-a8a6-4fe85bb49f0b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FaCIgkIDm6UTAOrLoi9Mq%2Fimage.png?alt=media&amp;token=2c26943d-6de9-4311-b512-d56229ab7e1b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F1XVbUHw08J9HCoxeahol%2Fimage.png?alt=media&amp;token=56ed5baf-5724-40a9-ba58-6f131f3e5309" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FppfVUFikvLNLDGDoXOWO%2Fimage.png?alt=media&amp;token=0b5e4e50-4002-4a84-88e0-97675798844e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FhYgTaXwF7KzDUlU9VmYi%2Fimage.png?alt=media&amp;token=0b3340df-e532-4ae7-9dae-7f1afcbe6a0c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FCGemDUGpjq7fIDQkd43p%2Fimage.png?alt=media&amp;token=914fe63a-d012-47fd-92f0-795877c67320" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FvY61vCVXt5fzFwMr0Eu3%2Fimage.png?alt=media&amp;token=6e262134-3459-4d71-8cdf-8a4e60c849e8" alt=""><figcaption></figcaption></figure>

## Dedicated Hosts

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FoIgtomzkW4dsXEhYxePM%2Fimage.png?alt=media&amp;token=4be1a13a-279f-48a0-a59d-a6206254fede" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FubK49ctKhwzS5CaPViLq%2Fimage.png?alt=media&amp;token=7a78d3e3-4014-4705-a0cf-075a49682963" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FDtIql1PkjnFc4H3IcKUh%2Fimage.png?alt=media&amp;token=78630107-bdd3-4f91-a607-cbe10624acf9" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FSqGcWJICQiYTrDL9YwGf%2Fimage.png?alt=media&amp;token=45039e64-c178-4a4c-8994-d9d3a5cc0731" alt=""><figcaption></figcaption></figure>

## AMI

*Practical usage for AMI: Suppose a user created an EC2 instance, configured everything that is required in the system such as settings and softwares. Now, the user wishes to create copies of this EC2 instance with the previous OS and instance settings as golden copy, then it can be done by creating image or snapshot of the machine, which can be replicated with new instances.*

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FEIFXCrR20GSSzFkojd7r%2Fimage.png?alt=media&amp;token=87b21b75-c4c4-4337-83d0-d4ff75772e69" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FComLMBiBTMeCc7SDEv4N%2Fimage.png?alt=media&amp;token=24423bd6-f560-4c3f-b4a1-7824e19166a0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FcA6UnrTbe7cPH7HD0psH%2Fimage.png?alt=media&amp;token=15a4570c-b270-4647-835c-d485691f2599" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F1eHp9B5IIBxeEEVw3qcA%2Fimage.png?alt=media&amp;token=414047ec-30e5-4778-9af6-ab045b428744" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FYSPoquIANUDXlKISkMYM%2Fimage.png?alt=media&amp;token=9bad7ff8-ae67-4bfb-b3d6-16dfb91513a0" alt=""><figcaption></figcaption></figure>

Rest of the steps to launch the instance is similar

Note that an EC2 can have different stages such as AMI -> Pending -> Running -> Stopping -> Stopped -> Shutting Down -> Terminated.

When an instance is in Hibernation mode (Stopped Stage), the contents of its RAM are quickly flushed into the EBS, so that next time the instance is made up, the RAM can be repopulated with the same data, making the transition feel seamless.

## How to move EC2 instances from one subnet or Availability Zone to other?

Steps are as follows:

Step 1: Stop the instance.

Step 2: Note down the Security Groups attached to the instance

Step 3: If an elastic IP is attached to it, make note of it as well as the network interface.

Step 4: Create an AMI of the same as shown above.

Step 5: Terminate the instance. This will detach the the network interface from the instance.

Step 6: Under the network interface, disassociate address and select the elastic IP.![](https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FfWFEyohYu1x5QyFm7K2o%2Fimage.png?alt=media\&token=7be868d0-9bcf-4c1e-8997-c6d10b578f77)![](https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FOaCAb3TZDhcQ0jvA98vf%2Fimage.png?alt=media\&token=d2a0eece-6781-4a5e-b9cf-adc1afef677b)

Step 7: Create a new network interface **in the required subnet or availability zone with new private IPv4 address as per the subnetwork** and **associate the elastic IP with this interface.**

Step 8: Create an instance from that AMI. While doing that, in the wizard, attach the new network interface which has association of previous elastic IP and relevant security group.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FUdfkfGWCcC7ukf7y5GVj%2Fimage.png?alt=media&amp;token=aff69c9e-0d12-40f8-9b43-6e8ed9df4815" alt=""><figcaption></figcaption></figure>

## Auto Scaling Groups

Suppose there is a video streaming application with fluctuating workloads, data gathered from Cloud Watch and is as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FgFa36bXqwW9Xd3g4M7nu%2Fimage.png?alt=media&amp;token=0a2cb002-4c96-46d6-8bef-e4ea3ebb8083" alt=""><figcaption></figcaption></figure>

This typical week shows demand of the application by its consumers with release of final trailer on Thursday and movie on Friday and general viewing habits peaking in the Weekend.

If the video streaming platform wants to optimize costs of the application, it needs to scale the application underlying EC2 instances with demand rather than keeping the high cost instances up all the time. This can be done with the help of Auto Scaling Groups.&#x20;

Auto Scaling allows to add or remove EC2 instances on demand based on conditions specified to maintain performance and optimize costs. This results in automated scalability. There are two types of scalability:

* Scaling Out: Increase in EC2 instances by launching them.
* Scaling In: Decrease in EC2 instances by terminating them.

The steps to achieve Auto Scaling happens in three stages:

1. Auto Scaling Launch Configuration
2. Auto Scaling Group
3. Auto Scaling Policy

*Note that the best way of Auto Scaling is Dynamic one. Let us take an example: There are two instances, supported by* [*Elastic Load Balancing*](/aws/networking-and-content-delivery-in-aws/elastic-load-balancing)*. As ELB sees a surge in demand in number of requests hitting it, a CloudWatch alarm is triggered. This results in auto scaling event to be executed, which can be to scale out to meet the rising demand.*&#x20;

Note that it also supports MAC OS instances<https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-mac-instances.html>&#x20;

[^1]: [https://notes.radifine.com/aws/](https://notes.radifine.com/aws/aws-storage-services/aws-ebs)


# Elastic BeanStalk

WS Elastic Beanstalk, automates the process of deploying and scaling compute workloads on EC2. The main difference is instead of AWS user to deal with those servers directly, AWS will manage all that for the user. It allows developers to concentrate on dev part and helps them with the deployment and administration part.

Technically, everything is still running all of the compute on EC2, but the process of managing servers, handling things such as provisioning, load balancing, scaling, and monitoring are all handled automatically through the work of Elastic Beanstalk service. *This is particularly helpful for developers because the services helps in administration of the server on which the app is going to be hosted.*

Hence, as normal thumb rule goes, with ease, comes limitation and restriction. This is because unlike EC2, where user is free to do whatever he/she wishes to, here, in Elastic Beanstalk shows limited compatibility with technologies such as Java, .NET, PHP, Node.js, Python, Ruby, Go, and Docker. &#x20;

The following are the steps to deploy a sample application on AWS Beanstalk, to understand the overall **PaaS** concept better:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FAPkLRqXNotFumBNZp2wd%2Fb0.png?alt=media&amp;token=7277ea83-598c-474f-9fb7-31882f87a185" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FqFx2aug27J7J3qlf21yZ%2Fimage.png?alt=media&amp;token=cc473799-107b-4b86-a9d9-29f7ac2cc160" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FZ7W9qyOm4QV1s9Wik3Ev%2Fimage.png?alt=media&amp;token=ac9f6cfc-4886-401b-9091-0776c7f8d7ba" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FexvFJwOLSpdqKcug7258%2Fimage.png?alt=media&amp;token=4fe99ebb-bf44-453c-81e3-1fce14ddfb7f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FHJmkOqCS4RTxVho7LqAL%2Fb12.png?alt=media&amp;token=57f294a5-ca5e-4b15-aac2-53fdb37ce375" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F14uTaeN6XJr1FvuikmDj%2Fb13.png?alt=media&amp;token=bd88a997-f323-4e87-a7e0-becdf14c4a21" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F9liw85O2jFwja4gAMMtm%2Fb14.png?alt=media&amp;token=fa1b2790-b83b-4dc6-bfca-f3a5b6d1bef3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FxqBtnL4C0NJn1occFkgr%2Fb14.1.png?alt=media&amp;token=9107a458-5890-4bbe-9541-d545a051e450" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FdUAsKDk3AlQIxqpTm4DM%2Fb15.png?alt=media&amp;token=2392d874-41d3-4c56-bbb4-dda1d59956d7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FvnxOMjI7u2RImvJSiNJu%2Fb16.png?alt=media&amp;token=362ef128-8f3b-4ff5-a5c1-382db846103e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FHjhbYNhf8obx5uq4pCaQ%2Fb2.png?alt=media&amp;token=de86c79d-cc4d-435e-a548-c2dd1a0eff03" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FquaagbiWLeLxV7wm4btb%2Fb3.png?alt=media&amp;token=5bcc4b87-8950-4e81-8d74-93d81611a9dc" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6VddCeiHFgFyijHh8fql%2Fb4.png?alt=media&amp;token=14049c80-3102-4363-95ce-e6d21114e997" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FkNEUEIM1K9gGRuUG9rvU%2Fb19.png?alt=media&amp;token=eb6f657b-a337-48dd-8c99-2fb674bf88f3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FKQcTRXCzbVGnXgoTRW8O%2Fb5.png?alt=media&amp;token=ebffb5de-69a8-4c42-8c04-a7275d2e55cc" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FG7gJOVxFoNcmt9xbm4cd%2Fb6.png?alt=media&amp;token=70d27157-3523-4fc0-82f4-09c593cc3a85" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FWh7WPRJT2tA3lo6a7Ctp%2Fb7.png?alt=media&amp;token=4e8bd5ae-acf1-496c-9318-907009fcbd1a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FE8aKUC4L8jPvDKTQAgjo%2Fb8.png?alt=media&amp;token=3311493a-c687-402c-9a22-125e20373958" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLtGIHskSNI1gD2ujjUTQ%2Fb9.png?alt=media&amp;token=eca67f46-a160-4fa6-b8bc-300ed329a383" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FQKNdW3aQHXA8tK0wzJ5c%2Fb10.png?alt=media&amp;token=5d773a67-4857-49f8-9f66-c74cc4c4c157" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fh1SuBoBFwC7rRTYj2Mtq%2Fb11.png?alt=media&amp;token=b65d89fd-5bb9-4948-8b68-fbc6595f778d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FEkeYPjkYpnC82E9splRL%2Fb17.png?alt=media&amp;token=3975de16-6581-4b5f-bd0a-f7dbe9157d41" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FhrIcEnub6gT0q9hBKXJP%2Fb18.png?alt=media&amp;token=022e5f13-d885-44c0-8e70-fba29bbdd050" alt=""><figcaption></figcaption></figure>


# AWS Lambda

### Features

Lambda is the so called as "server-less architecture" of AWS. It is different from the previous two as it is event driven; so the code uploaded in Lambda, is not given an execution environment to run code, until the defined event is triggered, and in this process, the user does not get to either provision or manage servers, and hence user only pay for the time used to consume compute resources. Due to this, there is a limitation, that whatever code is uploaded in Lambda, should complete execution within 5 minutes

Here, lot of application or back‑end service is supported and as there is no scope for administration, it integrates with many AWS services. &#x20;

One of the most important features is that it is highly scalable.

&#x20;Pricing changes with memory. An AWS user can consume memory from 128 to 3008 MB allocated for functions that are running on AWS Lambda.&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FJj8knFBn1Yyyl4Sna2j7%2Fdeep-dive-on-aws-lambda-vti-cloud.jpg?alt=media&amp;token=a98bbdb2-de4f-4aed-ba1f-f182ccc96769" alt=""><figcaption><p>Source: <a href="https://vticloud.io/wp-content/uploads/2021/03/deep-dive-on-aws-lambda-vti-cloud.jpg">https://vticloud.io/wp-content/uploads/2021/03/deep-dive-on-aws-lambda-vti-cloud.jpg</a></p></figcaption></figure>

As explained in IAM, Roles are used for one AWS service to communicate with other service

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FIrriPccGHAIWj8EzDzak%2FAR_Diagram_010418.png?alt=media&amp;token=78e2f199-f82d-46ce-aa25-ce38f981da60" alt=""><figcaption><p>Source: <a href="https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2018/01/21/AR_Diagram_010418.png">https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2018/01/21/AR_Diagram_010418.png</a></p></figcaption></figure>

AWS Lambda supports versioning (max versions are 5) and each version is immutable, i.e., once published, they cannot be changed and if changes are required, publish a new version, so in all, it can look like this:

* LambdaFunctionName
* LambdaFunctionName:1 <- Immutable
* LamdaFunctionName:2 <- Immutable

### Execution Environment Lifecycle

Execution Environments are secure and isolated runtime environments

The lifecycle can be defined as shown below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FwgTG8WOWu2rxSl82uRiP%2Fimage.png?alt=media&amp;token=115a73d3-f723-43ee-bbdd-7733edb54a52" alt=""><figcaption><p>Source: <a href="https://trackit.io/aws-lambda-lifecycle/">https://trackit.io/aws-lambda-lifecycle/</a> and <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html#runtimes-lifecycle">https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html</a> and <a href="https://tmmr.uk/post/lambda/lambda-execution-environment/">https://tmmr.uk/post/lambda/lambda-execution-environment/</a></p></figcaption></figure>

Extension INIT - In the Extension Init phase the system starts all extensions to let them apply their logic to the Lambda

Runtime INIT - The runtime is the combination of an operating system, programming language and a combination of software libraries required to invoke the Lambda function

{% hint style="info" %}
Note that when AWS Lambda was not used and is initialized for the 1st time at any given time, i.e., it was not active, then for its first run, it will take a little time to respond. This is called **Cold Start**

When it has become active and is responding to 2nd or 3rd trigger or request, it is called as **Warm Start**. Here initialization doesn't happen and request goes straight to invoke stage
{% endhint %}

### Types of Invocations

AWS Lambda supports parallel invocations:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F9ehVE3PowA7h3L5cl01Q%2Fimage.png?alt=media&amp;token=460f73be-ec2d-43af-9260-104aa8651bc0" alt=""><figcaption><p>Source: <a href="https://blog.awsfundamentals.com/lambda-limitations">https://blog.awsfundamentals.com/lambda-limitations</a></p></figcaption></figure>

The characteristics of Lambda Execution environment are as follows:

* Read Only File System
* Memory based on Lambda configuration during setup
* 512 MB of disk space in /tmp directory
* No inbound connections
* Only TCP/IP Outbound connections are allowed
* Max timeout of 15 minutes&#x20;

{% hint style="info" %}
If API Gateway is used for passing the trigger to lambda function and it has a timeout of 30 secs, so and if Lambda function code has a sleep of 35 seconds then it won't work, because there is timeout at API Gateway due to which API Gateway will not be able to relay the response back from Lambda to API Gateway all the way back to user.

What is the solution then?
{% endhint %}

The solution to above problem can be diagrammatically summarized as: Use Asynchronous events or Stream (Poll-based)

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F5jWnq26qyNCIH5UCEffr%2Fimage.png?alt=media&amp;token=8b78520a-a1fe-464f-83ee-a544cb5e7914" alt=""><figcaption><p>Source: <a href="https://d2908q01vomqb2.cloudfront.net/fc074d501302eb2b93e2554793fcaf50b3bf7291/2019/06/27/Screen-Shot-2019-06-27-at-2.23.51-PM-1024x510.png">https://d2908q01vomqb2.cloudfront.net/fc074d501302eb2b93e2554793fcaf50b3bf7291/2019/06/27/Screen-Shot-2019-06-27-at-2.23.51-PM-1024x510.png</a></p></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FGcH53H1Bfx07GYeGlbiv%2Fimage.png?alt=media&amp;token=0f586816-7f24-4b79-b506-d839d09ea00f" alt=""><figcaption><p>Source: <a href="https://media.licdn.com/dms/image/v2/D5612AQEkftRQJaBD3g/article-cover_image-shrink_600_2000/article-cover_image-shrink_600_2000/0/1721199571323?e=2147483647&#x26;v=beta&#x26;t=vyOf-dB-uRgAxj5sQe83_sWT71MnrKrnoiZqcE-KBuw">https://media.licdn.com/dms/image/v2/D5612AQEkftRQJaBD3g/article-cover_image-shrink_600_2000/article-cover_image-shrink_600_2000/0/1721199571323?e=2147483647&#x26;v=beta&#x26;t=vyOf-dB-uRgAxj5sQe83_sWT71MnrKrnoiZqcE-KBuw</a></p></figcaption></figure>

#### Improving Response Time by keeping Lambda Functions Warm

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FO9RxX3qxiHahrasKzF3h%2Fimage.png?alt=media&amp;token=f711a333-ee41-4433-b146-242728712778" alt=""><figcaption></figcaption></figure>

### Layers in Lambda Functions

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLGaQr6a2aEJk8DA8hH12%2Fimage.png?alt=media&amp;token=e5a135f8-0fdf-44e9-b3e1-be0a459f8bdf" alt=""><figcaption><p>Source: <a href="https://aws.amazon.com/blogs/mobile/how-to-use-lambda-layers-with-the-amplify-cli/">https://aws.amazon.com/blogs/mobile/how-to-use-lambda-layers-with-the-amplify-cli/</a></p></figcaption></figure>

Layers can also have upto 5 versions and as they have versioning, they are also immutable.&#x20;

Lambda Functions can use multiple layers which can be compatible with a runtime.&#x20;

They are extracted to /opt directory as shown below:

* Python - /opt/python/lib/python\<version>/site-packages
* Node.js - /opt/nodejs/node\_modules
* Binaries - /bin
* Java - /opt/java/lib
*

```
<figure><img src="/files/NlKkDlKnqlyeSSHattAz" alt=""><figcaption><p>As per ChatGPT</p></figcaption></figure>
```

Each layer has specific ARN.&#x20;

Layers can be stacked and ordering of layer matters

Max size of a layer is 250 MB

### Lambda Environment Variables

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FwIXYI4YnSvWX1jIjTEtj%2Fimage.png?alt=media&amp;token=ffe4beaa-a1da-44a9-907b-3c997d3ef9d7" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html">https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html</a></p></figcaption></figure>

Note that the id (which tell username) for an lambda environment generally tarts with **sbx\_user\<number>**

### Lambda Alias Routing

Lambda supports not only creating alias of a function but also supports routing to it. This is generally used to test new features by traffic shifting to send a small percentage of traffic to a second function alias or version for a rolling deployment before production rollout. This is commonly called a [canary release](https://wa.aws.amazon.com/wat.concept.canary-deployment.en.html)

Example: 90% of invocations route to the *stable* version while 10% route to alias *new-feature* pointing to version *3*. If the 10% is successful, deployment can continue until all traffic is migrated to version 3, and the *stable* alias is then pointed to version 3.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FNfbqjYueEhhSQy6ECCve%2F5-9-AWS-Lambda-alias-routing.png?alt=media&amp;token=0d0d8f7f-7320-4bbf-8a2a-cb5b660984ce" alt=""><figcaption><p>Source: <a href="https://d2908q01vomqb2.cloudfront.net/1b6453892473a467d07372d45eb05abc2031647a/2020/06/15/5-9-AWS-Lambda-alias-routing.png">https://d2908q01vomqb2.cloudfront.net/1b6453892473a467d07372d45eb05abc2031647a/2020/06/15/5-9-AWS-Lambda-alias-routing.png</a></p></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F7CoqtIEV1xdDfpmRPYFP%2Fimage.png?alt=media&amp;token=1ebded54-9c16-4182-8d59-beea28932141" alt=""><figcaption></figcaption></figure>

### Event and Context

The `event` parameter contains data that is passed to the Lambda function at the time of invocation. This data is specific to the event source that triggers the Lambda function.&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F0lM3Jl3WSMNXY5Id2FAP%2Fimage.png?alt=media&amp;token=3820470f-8097-42e6-ac7b-b4bcfab7a669" alt=""><figcaption><p>Source: <a href="https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html#apigateway-example-event">https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html#apigateway-example-event</a></p></figcaption></figure>

When Lambda runs the function, it passes a `context` object to the [handler](https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html). This object provides methods and properties that provide information about the invocation, function, and execution environment. It's main role is to provide information about the current execution environment. Unlike `event`, the methods and properties of the `context` object remain the same regardless of the lambda was invoked or triggered

Sample Code:

```python
// Generated by ChatGPT
def lambda_handler(event, context):
    # Accessing event data
    print("Received event:", event)
    
    # Accessing context data
    print("Request ID:", context.aws_request_id)
    print("Function Name:", context.function_name)

    # Your processing logic here
    return {
        'statusCode': 200,
        'body': 'Hello from Lambda!'
    }

```

### Runtime&#x20;

It is mostly a script (**bootstrap executable file**) that executes everything in order for getting the proper work from everyone and giving the output to user, via Runtime API and Lambda service

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F2WAUe5xjAcYNbRc8HIIE%2Fimage.png?alt=media&amp;token=2b0f2331-00ae-4530-a2f8-6976de38d703" alt=""><figcaption></figcaption></figure>

So, runtime runs the function's setup code. It reads the handler name from an environment variable, reads the invocation event from lambda runtime API, passes the event data to function handler and posts the response from handler back to Lambda. It can distributed as public or private layers

Working and Execution Flow can be explained as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FADhtBGxXP8MxWXkHuaGL%2Fimage.png?alt=media&amp;token=55a75aca-3cf7-45ca-9c0e-b066448c4434" alt=""><figcaption><p>Source: <a href="https://attackdefense.com/listing?labtype=aws-cloud-security-bootcamp&#x26;subtype=aws-cloud-security-bootcamp-recordings">https://attackdefense.com/listing?labtype=aws-cloud-security-bootcamp&#x26;subtype=aws-cloud-security-bootcamp-recordings</a></p></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FugdA3UgqRcSW1iuuT0ny%2Fimage.png?alt=media&amp;token=c091addf-0088-4de3-b4be-72249509c695" alt=""><figcaption><p>Source: <a href="https://attackdefense.com/listing?labtype=aws-cloud-security-bootcamp&#x26;subtype=aws-cloud-security-bootcamp-recordings">https://attackdefense.com/listing?labtype=aws-cloud-security-bootcamp&#x26;subtype=aws-cloud-security-bootcamp-recordings</a></p></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FxiqF8gGzXsVAiOCHliKD%2Fimage.png?alt=media&amp;token=e5e57437-f3ea-4c10-a0fe-2f063ad69c02" alt=""><figcaption><p>Source: <a href="https://attackdefense.com/listing?labtype=aws-cloud-security-bootcamp&#x26;subtype=aws-cloud-security-bootcamp-recordings">https://attackdefense.com/listing?labtype=aws-cloud-security-bootcamp&#x26;subtype=aws-cloud-security-bootcamp-recordings</a></p></figcaption></figure>

Runtime API Path (<https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html>):

* Invocation Request - GET "http\://${AWS\_LAMBDA\_RUNTIME\_API}/2018-06-01/runtime/invocation/next"
* Invocation Response - POST "http\://${AWS\_LAMBDA\_RUNTIME\_API}/2018-06-01/runtime/invocation/AwsRequestId/response"
* Invocation Error - POST "http\://${AWS\_LAMBDA\_RUNTIME\_API}/2018-06-01/runtime/invocation/AwsRequestId/error"
* Invocation Error Path - POST "http\://${AWS\_LAMBDA\_RUNTIME\_API}/2018-06-01/runtime/init/error"

### Steps for using AWS Lambda

Example Scenario: Generate Symmetric keys using Lambda

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F0CIMSCFe7qfVDtNyw96w%2Fimage.png?alt=media&amp;token=7f68a9df-db8a-4fbc-aac6-e7697071e2c8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F10ER4kxjHLMU8Ll7jZnF%2Fimage.png?alt=media&amp;token=83b71abe-d4aa-4045-8421-543e77f703bc" alt=""><figcaption></figcaption></figure>

Now, to create a lambda function using dotnet cli, ensure that .NET SDK is installed from [here](https://dotnet.microsoft.com/en-us/download/dotnet/6.0).

Create a folder to host the source code

```powershell
cd <to-the-created-folder>
dotnet nuget add source https://api.nuget.org/v3/index.json -n nuget.org
dotnet new --install Amazon.Lambda.Templates
dotnet new lambda.EmptyFunction --name SymKeyGen
cd SymKeyGen
cd src
notepad SymKeyGen.csproj 
// make the following changes
```

```
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework> //Change here
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <AWSProjectType>Lambda</AWSProjectType>
    <!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
    <!-- Generate ready to run images during publishing to improve cold start time. -->
    <PublishReadyToRun>false</PublishReadyToRun> //Change here
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.Core" Version="2.3.0" />
  </ItemGroup>
</Project>
```

```powershell
dotnet add package Amazon.Lambda.Core
dotnet add package Amazon.Lambda.APIGatewayEvents
dotnet add package AWSSDK.S3
dotnet add package Newtonsoft.Json
notepad Function.cs
```

<pre class="language-csharp"><code class="lang-csharp"><strong>//Generated by ChatGPT
</strong><strong>
</strong><strong>using System;
</strong>using System.IO;
using System.Security.Cryptography;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.S3;
using Amazon.S3.Model;
using Newtonsoft.Json;
using System.Text.RegularExpressions;

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

public class Function
{
    private readonly string bucketName = "radifineuniquebucketname"; // Update with your S3 bucket name
    private readonly IAmazonS3 s3Client;

    public Function()
    {
        s3Client = new AmazonS3Client();
    }

    // Entry point for the Lambda function
    public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
    {
        return GenerateKey(request, context);
    }

    public APIGatewayProxyResponse GenerateKey(APIGatewayProxyRequest request, ILambdaContext context)
    {
        // Parse input parameters from the request
        if (request.QueryStringParameters == null || 
            !request.QueryStringParameters.TryGetValue("input", out var hexInput))
        {
            return new APIGatewayProxyResponse
            {
                StatusCode = 400,
                Body = JsonConvert.SerializeObject(new { Error = "Input parameter is required." }),
                Headers = new System.Collections.Generic.Dictionary&#x3C;string, string>
                {
                    { "Content-Type", "application/json" }
                }
            };
        }

        // Decode hex input to original string
        string inputParam = HexToString(hexInput);

        // Validate the input
        if (!IsValidInput(inputParam))
        {
            return new APIGatewayProxyResponse
            {
                StatusCode = 400,
                Body = JsonConvert.SerializeObject(new { Error = "Invalid input parameter." }),
                Headers = new System.Collections.Generic.Dictionary&#x3C;string, string>
                {
                    { "Content-Type", "application/json" }
                }
            };
        }

        // Generate a symmetric key based on the input parameter
        byte[] symmetricKey = GenerateKeyFromInput(inputParam);
        var base64Key = Convert.ToBase64String(symmetricKey);

        // Save the key to S3
        string fileName = $"{inputParam}.txt"; // Name the file using the input string
        var putRequest = new PutObjectRequest
        {
            BucketName = bucketName,
            Key = fileName,
            ContentBody = base64Key,
            ContentType = "text/plain"
        };

        // Upload the key to S3
        s3Client.PutObjectAsync(putRequest).Wait();

        // Return the key and success message
        var response = new
        {
            Key = base64Key,
            Message = "Key generated and saved successfully."
        };

        return new APIGatewayProxyResponse
        {
            StatusCode = 200,
            Body = JsonConvert.SerializeObject(response),
            Headers = new System.Collections.Generic.Dictionary&#x3C;string, string>
            {
                { "Content-Type", "application/json" }
            }
        };
    }

    private bool IsValidInput(string input)
    {
        // Check for null or empty
        if (string.IsNullOrWhiteSpace(input))
            return false;

        // Check length (e.g., maximum length of 255 characters)
        if (input.Length > 255)
            return false;

        // Validate against a regex pattern (adjust as necessary)
        string pattern = @"^[a-zA-Z0-9\-\.]+$"; // Example pattern: allows alphanumeric, hyphens, and dots
        return Regex.IsMatch(input, pattern);
    }

    private byte[] GenerateKeyFromInput(string input)
    {
        using (var sha256 = SHA256.Create())
        {
            // Hash the input to create a fixed-length key
            return sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
        }
    }

    private string HexToString(string hex)
    {
        StringBuilder result = new StringBuilder(hex.Length / 2);
        for (int i = 0; i &#x3C; hex.Length; i += 2)
        {
            result.Append((char)Convert.ToByte(hex.Substring(i, 2), 16));
        }
        return result.ToString();
    }
}

</code></pre>

```powershell
dotnet build
dotnet publish -c Release -o ./publish
Compress-Archive -Path * -DestinationPath ../SymKeyGenSrc.zip
```

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FOUeXot8HVg0LtPdpSTAd%2Fimage.png?alt=media&amp;token=e74c5dec-328d-42e0-9ead-55a8d0ba2293" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fn6NwkgimiomBrtJZOp4M%2Fimage.png?alt=media&amp;token=c9aa263c-1bd1-4a64-b79d-bb2c21ed5f7e" alt=""><figcaption></figcaption></figure>

&#x20;Edit the permissions for access to S3

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FN9YsLfLsddEGftYu2qsC%2Fimage.png?alt=media&amp;token=a0cbb1e2-cf00-44b1-a036-04f4a52c6f3c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fpbkc09wcXp8BldeBNyEQ%2Fimage.png?alt=media&amp;token=a8ce607f-eb67-4463-9fc2-1f46f07a290d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Facetv4QpMH2TqskvgTM3%2Fimage.png?alt=media&amp;token=5e4fb559-526b-49ef-8cab-0b3547018132" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FlES5NhkoqrRpP3YUgvQo%2Fimage.png?alt=media&amp;token=4bafd0b8-43a9-4bdd-8bd6-353e23668966" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FwxbGbr800ch5RerWnSVR%2Fimage.png?alt=media&amp;token=817f8f79-3577-4c6a-b894-fc05895924a6" alt=""><figcaption></figcaption></figure>

> For those interested, can head over API Gateway to have complete scenario based understanding.&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FCpxEwvBHIPtsvbhof51x%2Fimage.png?alt=media&amp;token=2897077b-6df1-48b7-a514-cc8df0396549" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FEWOkhuKlBotUqXxM5hT1%2Fimage.png?alt=media&amp;token=ed9a0d0b-0bc1-43a4-933a-100d847436b1" alt=""><figcaption></figcaption></figure>

Now, it should work


# Container Services

Containers are packages of software that contain all of the necessary elements to run in any environment. Simply speaking, they are just virtualized environments which has all dependencies (configuration, runtime environment and additional packages) to run a particular code (application). This makes them run on top of any operating system hence are OS platform agnostic.&#x20;

AWS App Runner, is one of the many such container service offered by AWS with a focus on web applications or APIs.&#x20;

### ECR

There is another service called ECR (Elastic Container Registry) which is a service for storing, managing and deploying container container images such as Docker images. It is like a library where one keep all the Docker images so they can be easily accessed and used later.&#x20;

#### Working of ECR:

**Image Repository:** Users can create repositories in ECR to store Docker images. Each repository can hold multiple image versions, making it a centralised hub for container images.

**Image Push and Pull:** Developers can push (upload) their Docker images to ECR, while deployment environments can pull (download) the images for running containerized applications.

**Integration with ECS and EKS:** ECR seamlessly integrates with ECS and EKS, simplifying container deployment and orchestration.

### ECS and EKS

There are two container orchestration services offered by AWS, namely,  Amazon Elastic Container Service ECS and Amazon Elastic Kubernetes Service EKS. Container orchestration services are tools that help manage the deployment, scaling, and operation of containerized applications. The main difference as EKS is Kubernetes based specifically and ECS supports Docker & other Open Container Initiative (OCI) standards based containers.

For ECS or EKS, user has to select two options for Compute Engine; they are EC2 and AWS Fargate. If EC2 is selected as compute engine, the onus to manage scaling and defining the compute resources such as no. of resources such as vCPU, RAM etc. and also the no. of such instances. AWS Fargate on the other hand is a serverless compute engine for use with container orchestration services. i.e. the user don't have to manage anything around scaling no. of instances to run containers. That part is taken up by AWS in the form of Fargate.&#x20;


# ECR and ECS

A **registry** is a storage location for Docker container images in AWS. It is a logical namespace that can contain multiple **repositories.** A **repository** is a collection of related Docker container images within a registry. It stores different versions (tags) of container images. A repository is where one can push, pull, and manage the lifecycle of Docker images.

### Steps for using ECR

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FfLnQCIVVfzv894ZBYrTi%2Fimage.png?alt=media&amp;token=d24a9225-5357-4be2-a3ff-51c98a6cec23" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fbf2EvK7PAZgRkmKsqdke%2Fimage.png?alt=media&amp;token=a060938b-e97f-44a4-9ac3-e4b77d58edd1" alt=""><figcaption></figcaption></figure>

* The **URI** is what is used to reference the repository images while creating containers on ECS clusters. Format: \<account-id>.dkr.ecr.\<region>.amazonaws.com/ \<repo-name>
* The **Tag immutability** column lists its status, if tag immutability is enabled it will prevent image pushes with pre-existing tags from overwriting the images.&#x20;
* The **Encryption type** column lists the encryption properties of the repository, it shows the default encryption types such as AES-256, or has KMS enabled encryption.&#x20;
* The **Pull through cache** column lists its status, if Pull through cache status is Active it will cache repositories in an external public repository into the private repository&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FR5FXSPVTscKuz0YITkjY%2Fimage.png?alt=media&amp;token=c5e044d2-7aae-40f9-b384-601bb3671554" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FaIQUXE8kSLDAXwsLlXgm%2Fimage.png?alt=media&amp;token=966562b8-b876-4065-92ef-ebd2b9592d07" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F01ITC6bqbuV2e8chqZaS%2Fimage.png?alt=media&amp;token=0726b33f-c8e5-422b-b3df-8f219ef2078d" alt=""><figcaption></figcaption></figure>

* The **Permissions** section allows to apply a registry policy to grant permissions to an AWS principal at the private registry level. These allow us to scope access to the Replication and pull through cache configuration features of private registry.&#x20;
* The **Pull through cache configuration** lets set pull through cache rules for the repository. The Replication configuration lets set rules to manage cross region and cross account repository replication. On the private repositories listing, The **Pull through cache** column lists its status, if Pull through cache status is Active it will cache repositories in an external public repository into the private repository
* The **Scanning configuration** has two options:
  * **Basic scanning** is a free service that allows manual scans and scans on push of images in the registry.&#x20;
  * **Enhanced scanning** provides automated continuous scanning that identifies vulnerabilities in both operating systems and enhanced scanning&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FxJf4FbNJ6hFzFCIABTbH%2Fimage.png?alt=media&amp;token=5e5535a2-779c-4a14-b907-e2a762aaa22a" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
The Public tab lists the repositories which are publicly accessible from this account. A unique default alias is added to the repository name at creation, it is used for identification of this repository from the multitude of public repositories on AWS.&#x20;
{% endhint %}

To Push Docker Images to ECR

* **Tag Docker Image**:

  ```bash
  docker tag your-image-name:latest <aws_account_id>.dkr.ecr.<region>.amazonaws.com/your-repository:your-tag
  ```
* **Login to ECR**: Authenticate Docker to your ECR registry:

  ```bash
  aws ecr get-login-password --region <region> | docker login --username AWS --password-stdin <aws_account_id>.dkr.ecr.<region>.amazonaws.com
  ```
* **Push the Image**: Push the tagged image to ECR:

  ```bash
  docker push <aws_account_id>.dkr.ecr.<region>.amazonaws.com/your-repository:your-tag
  ```
* **Pull the Image**:&#x20;

  `docker pull <aws_account_id>.dkr.ecr.<region>.amazonaws.com/your-repository:your-tag`

Example:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FtYSO26eI0O2tk1v1aYdF%2Fimage.png?alt=media&amp;token=35fa5221-da89-441a-9bd5-09e92319294f" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Integrate ECR with CI/CD tools (like AWS CodePipeline or Jenkins) to automate the process of building, tagging, and pushing images to ECR whenever changes are made to your codebase.
{% endhint %}

```bash
//After pulling an image, if one wants to run a docker image
docker images <-- this will give iamge ID
docker run -it -p <host-port>:<container-port> <ImageID> <-- It will run 
docker exec -it <container_id_or_name> bash
```

* Implement a tagging strategy that includes version numbers and identifiers for easy tracking and updates. When one create new versions of the application, use a consistent tagging strategy (like semantic versioning) to clearly indicate changes (e.g., `v1.0.0`, `v1.1.0`).
* After pushing new images, update deployment configurations in ECS or EKS to use the new tags. This is done on the basis of Task Definition as one can create it such that specifies container image with a particular tag. One can use environment variables or parameters to dynamically set the image tag based on requirements.

**ECS**, is a logical group of EC2 instances on which you can run an application without having to scale your own cluster management infrastructure because ECS manages that for you. If you manage to compromise service running in **ECS**, the **metadata endpoints change**.

<-Will update later, so ignore the below->

Deploy Images Using Tags in ECS or EKS //Give snapshot images below for the steps

* When creating or updating an ECS Task Definition or an EKS Deployment, specify the image URI with the tag:
  * Example: `<aws_account_id>.dkr.ecr.<region>.amazonaws.com/nameof-repository:tag-given`.
* For ECS, you can do this in the Task Definition:
  * Go to **ECS** in the console.
  * Select **Task Definitions** and either create a new one or edit an existing definition.
  * Under **Container Definitions**, specify the image URL with the tag.


# EKS

Some part of this page is summarized using ChatGPT

## PreContext

### What is Kubernetes?

Kubernetes  is an open-source platform that acts as an orchestration tool, meaning it automates the processes involved in deploying, managing, and scaling containers. This includes starting and stopping containers, monitoring their health, and handling failures. Kubernetes can manage hundreds or thousands of containers spread across multiple servers (nodes), handling load balancing, service discovery, and failover automatically.&#x20;

<figure><img src="https://lh7-us.googleusercontent.com/hYzBWIO__YgXPeYKTTu1N8M4DR8lbbyaLaK3P7q7MTfJFaGQRG2vw5LCiPm3abg0Fgc_f-jQsAAtpVaw-msR0GL1ptco3AcQaKrs96iVZrvg5VaYGla114YLhItSC0mSqIFvolgzQs8bgJO5rPVfUTI" alt=""><figcaption><p>Source: <a href="https://www.nccgroup.com/us/research-blog/detection-engineering-for-kubernetes-clusters/">https://www.nccgroup.com/us/research-blog/detection-engineering-for-kubernetes-clusters/</a></p></figcaption></figure>

### USP Of Kubernetes

Kubernetes provides the capability to scale up horizontally as opposed to scaling vertically, i.e., spreading the workload by adding more nodes instead of adding more resources to existing nodes

Kubernetes provides the capability to scale up horizontally as opposed to scaling vertically, i.e., spreading the workload by adding more nodes instead of adding more resources to existing nodes

### How different it is from from Docker?

While Docker handles the creation and management of individual containers, Kubernetes takes it a step further by orchestrating those containers across multiple hosts. Many organizations use Docker to create their containers and then deploy them in a Kubernetes cluster i.e., Kubernetes can use Docker as its container runtime, meaning that Kubernetes can manage and orchestrate containers created with Docker. However, Kubernetes is also compatible with other container runtimes.

### Concepts of Kubernetes:

Kubernetes uses services to define a logical set of pods and a policy for accessing them. This abstraction allows for stable communication between different parts of an application, even as the underlying pods change.

* **Containers:** At its core, Kubernetes manages containers. Containers are lightweight, portable units that package an application along with its dependencies, libraries, and configuration files. Containers ensure that an application runs consistently across different environments. Container  share the operating system kernel but run in isolated user spaces, which makes them efficient and quick to start.
* **Pods:** The smallest deployable units in Kubernetes are called pods. **A pod can contain one or more containers that share the same network namespace and storage as they can be closely related and need to work together**. This facilitates that containers within the pod can communicate with each other using `localhost`, while sharing storage volumes. Example: A Pod containing a Web Server Container and a Log Server Container.&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6BXQvQtg8XeHdAxGY3lC%2Fimage.png?alt=media&amp;token=a445cc33-6f13-4099-953e-a94f4b71259e" alt=""><figcaption><p>Source: <a href="https://kubernetes.io/images/docs/kubernetes-cluster-architecture.svg">https://kubernetes.io/images/docs/kubernetes-cluster-architecture.svg</a></p></figcaption></figure>

* **Cluster Architecture:** The Kubernetes cluster is made up of nodes. Nodes are the environment in which pods operate. A node can be both baremetal machine or Virtual Machine. The cluster consists of a master node (which manages the cluster) and worker nodes (where the containers run).  This architecture is what makes Kubernetes help to realize the essence of distributed computing.
  * **Master Node:** This node manages the Kubernetes cluster and is responsible for maintaining the desired state of the applications. It handles scheduling, scaling, and monitoring. It can automatically scale applications up or down based on demand. If more users are accessing the application, it can increase the number of pods to handle the load and then scale down when traffic decreases. It has following components:

    #### 1. etcd

    * **Definition:** etcd is a distributed key-value store used by Kubernetes to store all its configuration data and state information.
    * **Data Storage:** etcd holds the entire cluster state, including information about nodes, pods, services, and configurations.
    * **Consistency:** etcd ensures data consistency and reliability by data replication. This is crucial for fault tolerance.

    #### 2. API Server

    * **Definition:** The API server is the central management component of Kubernetes that exposes the Kubernetes API.
    * **Communication Hub:** It acts as the main interface for all interactions with the cluster, allowing users, applications, and other components to communicate.
    * **RESTful Interface:** The API server provides a RESTful interface for clients to send requests to create, update, or delete resources in the cluster.
    * **Authentication and Authorization:** It handles requests and applies security policies, ensuring that only authorized users and components can access or modify resources.&#x20;

      Kubernetes uses roles to determine if a user or pod is authorized to make a specific connection/call. Roles are scoped to either the entire cluster (ClusterRole) or a particular namespace (Role).

      These roles contain lists of resources (the object) the role can grant access to, and a list of verbs that the role can perform on the said resource, are declared and then attached to RoleBindings. RoleBindings pretty much link the role (permissions) with the users and systems. More information on this functionality can be found [here](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) in the Kubernetes official documentation.

      <pre class="language-yaml"><code class="lang-yaml"><strong>// Sample taken from Kubernetes documentation
      </strong><strong>
      </strong><strong>apiVersion: rbac.authorization.k8s.io/v1
      </strong>kind: Role
      metadata:
        namespace: default
        name: pod-reader
      rules:
      - apiGroups: [""]
        resources: ["pods"]
        verbs: ["get", "watch", "list"]
      </code></pre>

    #### 3. Scheduler

    * **Definition:** The scheduler is responsible for assigning pods to worker nodes based on resource availability and requirements.&#x20;
    * **Pod Placement:** When a new pod is created, the scheduler determines the best node to run that pod, considering factors like resource requests, node capacity, and affinity/anti-affinity rules.
    * **Load Balancing:** It helps balance workloads across nodes to ensure efficient resource utilization and prevent overloading any single node.
    * **Custom Scheduling Policies:** Users can define custom scheduling policies, such as placing pods closer to certain resources or spreading them across nodes for high availability.

    #### 4. Controllers

    * **Definition:** Kubernetes user can define the desired application state (how many replicas, what images to use, etc.) in configuration files, and Kubernetes works to ensure the current state matches the desired state with the help of controllers. Controllers are control loops that monitor the state of the cluster and make adjustments to ensure the desired state matches the actual state.
    * **Deployment Controller:** Manages deployments by ensuring that the desired number of pod replicas are running and up-to-date.
    * **ReplicaSet Controller:** Ensures that a specified number of replicas for a pod are running at any given time.
    * **Node Controller:** Monitors the health of nodes and manages node lifecycle events, such as marking nodes as unavailable when they fail. It has the ability to automatically replace or restart failed containers, ensuring that the desired state of the application is maintained
    * **Job and CronJob Controllers:** Manage the execution of jobs and scheduled tasks.
  * **Worker Nodes:** These nodes run the actual application workloads, hosting the pods that contain the containers.

    #### 1. Kubelet

    * **Definition:** It is an agent that runs on each worker node in a Kubernetes cluster. Its primary job is to manage the pods and containers on that node.
    * Kubelet receives pod specifications (instructions) from the Kubernetes API server and ensures that the specified containers are running in those pods.
    * It continuously monitors the health of the pods and their containers, reporting back to the Kubernetes control plane. If a container crashes or fails, Kubelet will attempt to restart it.&#x20;
    * Kubelet manages resources on the node, including CPU and memory, to ensure that pods have what they need to run efficiently.

    #### 2. Kube-proxy

    * **Definition:** It is a network proxy that runs on each worker node in a Kubernetes cluster. Its role is to facilitate communication between services and pods.
    * Kube-proxy maintains network rules on the nodes, allowing for load balancing and routing of requests to the appropriate pod based on the service configuration.
    * Kube-proxy supports various protocols, including TCP and UDP, allowing for versatile network communication

    #### 3. Pods

    * Already discussed about the pod in earlier points.
  * **Service:** Kubernetes services provide a stable endpoint for accessing a set of pods. Services allow for load balancing and automatic DNS resolution, making applications accessible within the cluster or externally. Some of the Kubernetes service are:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FaeTvTdh1BWvzb64qv2iv%2Fimage.png?alt=media&amp;token=15d56037-2796-4e3d-ba98-0dc082d3c0fb" alt=""><figcaption><p>Source: <a href="https://www.linkedin.com/pulse/day-33-working-namespaces-services-kubernetes-kartik-bhatt-hloyc">https://www.linkedin.com/pulse/day-33-working-namespaces-services-kubernetes-kartik-bhatt-hloyc</a></p></figcaption></figure>

* **Namespace:** Within a physical Kubernetes cluster, namespace is a logical, virtual cluster which provide a way to segregate and isolate resources and objects within a cluster, creating distinct scopes for applications and services

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FkggE3wKK2RSpqFsUceRL%2Fimage.png?alt=media&amp;token=57368aca-6229-44f3-8109-e6de57481bc4" alt=""><figcaption><p>Source: <a href="https://www.linkedin.com/pulse/day-33-working-namespaces-services-kubernetes-kartik-bhatt-hloyc">https://www.linkedin.com/pulse/day-33-working-namespaces-services-kubernetes-kartik-bhatt-hloyc</a></p></figcaption></figure>

{% hint style="info" %}
kubectl is the command-line tool used to interact with the Kubernetes cluster. It acts as the primary way to communicate with the Kubernetes API server. kubectl allows engineers to apply configuration files (YAML or JSON) that define how their applications should run in the cluster.
{% endhint %}

{% hint style="info" %}
**ConfigMaps** in Kubernetes are a way to manage configuration data for applications in a decoupled manner. They allow engineers to separate configuration from the application code, making it easier to manage and update configurations without rebuilding the container images. Here’s a breakdown of what ConfigMaps are and how they work:

A ConfigMap is a Kubernetes API object that allows to store non-confidential data in key-value pairs. This can include configuration settings, command-line arguments, environment variables, or any other configuration details needed by the applications.
{% endhint %}

## AWS EKS Features:

Amazon Elastic Kubernetes Service (AWS EKS) is a managed Kubernetes service that simplifies the deployment, management, and scaling of containerized applications using Kubernetes.&#x20;

AWS EKS abstracts the complexities of Kubernetes cluster management and offers a reliable and scalable platform for running containerized workloads. Key components include:

**EKS Cluster:** The EKS cluster is the central management entity that hosts multiple worker nodes and manages their orchestration. It’s responsible for maintaining the desired state of Kubernetes applications.

**Worker Nodes:** Worker nodes are EC2 instances within your EKS cluster that run containerized applications. These nodes are managed by the EKS control plane.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6x7L7IF7MbFlJsRaTUKz%2Fimage.png?alt=media&amp;token=267cbad9-85f5-4a76-9b5b-87ca4a398710" alt=""><figcaption><p>Source: <a href="https://www.devopsschool.com/blog/wp-content/uploads/2021/03/Amazon-Elastic-Kubernetes-Service-EKS-Explained-Diagram-5.png">https://www.devopsschool.com/blog/wp-content/uploads/2021/03/Amazon-Elastic-Kubernetes-Service-EKS-Explained-Diagram-5.png</a></p></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FV7uaYFEtZwMvSJzYdtez%2Fimage.png?alt=media&amp;token=57f9cf0b-ec44-4cac-aed0-8ee2100d56ae" alt=""><figcaption><p>Source: <a href="https://rafay.co/the-kubernetes-current/getting-started-with-amazon-eks/">https://rafay.co/the-kubernetes-current/getting-started-with-amazon-eks/</a></p></figcaption></figure>

## Bonus Learning: Rancher

Rancher is a powerful and popular open-source container management platform that simplifies the deployment, orchestration, and management of containerized applications in Kubernetes clusters  across multiple environments. It provides a comprehensive suite of tools and features that streamline the containerization journey for organisations, making it easier to harness the full potential of container technology.&#x20;

It provides a user-friendly interface for managing containers, clusters, and applications, making it easier to deploy and maintain container-based applications.&#x20;

{% hint style="info" %}
**In short, Rancher builds on top of Kubernetes to manage multiple Kubernetes cluster that can span across different Cloud Providers**
{% endhint %}

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FaREfCIPXGMli74NF0buL%2Fimage.png?alt=media&amp;token=aa8ba707-55f9-4996-8872-52fc685b408e" alt=""><figcaption><p>Source: <a href="https://miro.medium.com/v2/resize:fit:720/format:webp/1*TnFotcV01sGOnJ0_4Q8Eww.png">https://miro.medium.com/v2/resize:fit:720/format:webp/1*TnFotcV01sGOnJ0_4Q8Eww.png</a></p></figcaption></figure>

Some key aspects and benefits of using Rancher:

**Centralised Management:** Rancher offers a unified, web-based interface that allows users to manage and monitor multiple Kubernetes clusters across different environments from a single, centralised dashboard. This simplifies the management of complex container infrastructures, whether they are on-premises, in the cloud, or at the edge.

**Kubernetes Made Accessible:** Rancher abstracts much of the complexity of Kubernetes, making it accessible to a wider range of users, from DevOps teams to developers. It provides an intuitive user experience for cluster provisioning, scaling, and lifecycle management, reducing the learning curve associated with Kubernetes.

**Multi-Cluster Management:** Organisations often operate multiple Kubernetes clusters for various purposes, such as development, testing, and production. Rancher excels at managing multiple clusters, making it easy to ensure consistency, security, and compliance across these clusters. It simplifies the process of creating, upgrading, and patching clusters.

**Extensibility:** Rancher’s open architecture allows users to easily integrate additional tools and services. It supports a wide range of third-party plugins and extensions, making it adaptable to various infrastructure and application requirements. This extensibility enhances Rancher’s capabilities, such as networking, storage, and security.

**Security and Compliance:** Rancher offers robust security features, including role-based access control (RBAC), identity and access management (IAM), and security scanning for container images. These capabilities help organisations enforce security policies and ensure compliance with industry standards and regulations.

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fp2GRBDxuYBiMM68sdaRh%2Fimage.png?alt=media&amp;token=ab326ae0-eede-4863-a106-2a850fc55510" alt=""><figcaption><p>Source: <a href="https://www.webagesolutions.com/blog/rancher-introduction">https://www.webagesolutions.com/blog/rancher-introduction</a></p></figcaption></figure>

Additional Reading Material: <https://blog.devops.dev/rancher-multi-cloud-on-prem-kubernetes-management-b67fd1f11b9d>


# AppRunner


# Other AWS Services


# CloudFormation

It can be create AWS Environments at scale in a much quicker way, as it is a way to code a infrastructure.

It is a template to setup/configure resources which is given in YAML or JSON

It can be used to create stack (AWS Resources such as VPC or S3 or EC2 or any other service supported) as IAM user or Assume Role


# AWS Key Management Services (KMS)

When data is moved into the cloud, it is best to secure it at both the stages - when data is in transit and when the data is at rest and one of the services from AWS that can be foundational into dealing with keys for encryption is KMS or Key Management Service, mainly used to provide, store and manage encryption keys for data at rest.&#x20;

Note that KMS also allows auditing of who used the KMS keys with the help of [CloudTrail](/aws/other-aws-services/logging-and-monitoring/aws-cloudtrail). It is also possible to exercise access control to KMS keys by creating usage policies.

KMS allows centralized key management that has compatibility to a variety of other AWS services.

AWS KMS facilitates the creation of both Symmetric key and Asymmetric keys (like for EC2 access over ssh)

KMS keys can be of two types:

* Customer Master Keys (CMKs) - It can be customer managed (uploaded by the customer or generated by KMS for the customer) or AWS-managed (generated in KMS by AWS whenever required). It can act as one of the input in generating unique data keys as well as used to encrypt and decrypt the generated data keys, i.e. CMKs can  act as Key encryption keys and this process is known as Envelope Encryption
* Data Encryption Keys - It is also known as data keys, which is used to encrypt and decrypt the data. Note that master key never leaves the KMS and DEK generated each time is unique, for better security. &#x20;

Using the keys in KMS, AWS encrypts and decrypts the data in S3 or s3 glacier or EBS or EFS or FSx or RedShift or RDS or Amazon EMR and even CloudTrail. This process is called Server-Side Encryption. Different flavours of SSE are as follows:&#x20;

* Server Side Encryption using AWS Managed Keys (SSE-KMS) - Data Encryption key (DEK) is used, which itself is encrypted using Customer Master Key.&#x20;
  * [x] Example: To encrypt [EBS](/aws/aws-storage-services/amazon-ebs) volumes, KMS is used which holds the customer master keys (responsible for generating data keys) and data keys (for encryption of data on EBS volumes).
* Server Side Encryption using Customer Provided Encryption key (SSE-C) - The customer generated key is uploaded into KMS is used for encryption data directly, unlike in previous case, where DEK (data encryption key) is generated using Customer Master key

{% hint style="info" %}
Note that in most data at rest cases, let's just say s3; so when data is uploaded into s3, the DEK is part of metadata for the encrypted s3 object in the bucket, therefore when required access to the encrypted object is requested, AWS s3 should be able able to get that quickly
{% endhint %}

There is something called Client-Side Encryption, where the client only supplies 256-bit key and key encrypting key and encrypt the data and encrypted blob is directly uploaded as it is (encrypted) in s3.

Please note that it is essential for KMS Administrative tasks such as&#x20;

* Control access to IAM users and role that can administer and may or may not use the key
* Rotate the keys
* Disable keys and Re-enable keys when required
* Audit the usage of keys

AWS Console for KMS keys shows the following options:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FqIZUButh5QEjYsQ7kqSd%2Fimage.png?alt=media&amp;token=9951b535-b112-4d60-a457-19858a34fccf" alt=""><figcaption></figcaption></figure>

## Steps for triggering creation of AWS managed (KMS key/Customer Master key):

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FiRQNNOVRCu37OkslZ3m3%2Fimage.png?alt=media&amp;token=cbb75e1b-7832-4e72-b5b5-1d12ca3f5f60" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fi96Jiz8Ss6wgBAy4dblW%2Fimage.png?alt=media&amp;token=debd4cc4-59fd-4cf3-8096-4ff811669857" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F3hHVCEovLd1URX0tM4G9%2Fimage.png?alt=media&amp;token=62baa3ed-6b65-443a-b982-b6ae355a2f49" alt=""><figcaption></figcaption></figure>

## Steps for creating KMS generated Customer managed (KMS key/Customer Master key):

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FcDoqqAulpAnHFDvpq23D%2Fimage.png?alt=media&amp;token=9fd5ce04-9f7b-4f38-8732-c0f162695bd8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FjiC2uzHtlbPQFkkLfGYy%2Fimage.png?alt=media&amp;token=170228d8-5d6d-41f0-bd37-cd51990c831b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FyGdoe9ttLPn3gySZMhgy%2Fimage.png?alt=media&amp;token=1c83e2e9-0a00-4dee-b31e-83c83815517b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FXyUW2J0fo47Rim79dImR%2Fimage.png?alt=media&amp;token=3ba624b4-2690-4091-9df6-e22110992299" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FRdFm8A3X4yDGTRztH33H%2Fimage.png?alt=media&amp;token=622d134f-6a8a-4dca-85df-8e5c9592c019" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FzbRcpaPTQ7AInOPYZ2uW%2Fimage.png?alt=media&amp;token=cc3463b6-19a5-4168-b5c4-73a8913c284d" alt=""><figcaption></figcaption></figure>

## Steps for importing customer uploaded Customer managed (KMS key/Customer Master key):

<-will be added later->

## Steps for using customer provided data encryption key:

<-will be added later->


# AWS Secrets Manager

### Features

AWS Secrets Manager is where secrets (from POV of the customer or AWS account holder) can be stored. is a managed service provided by Amazon Web Services (AWS) that simplifies the secure storage and management of sensitive information . Secrets can include passwords, API keys, tokens, and other sensitive data that applications, services, or IT resources need to access. i.e., It can be used to store database credentials or API keys or tokens or any other app secret etc. It operates by allowing users to create and store secrets, in a centralized and highly secure manner.

The primary goal of AWS Secrets Manager is to safeguard access to services and applications by eliminating the need to hard-code sensitive information in plaintext, thereby enhancing security and compliance

Typical use case is webapp hosted on AWS securely gets access to RDS database. It also supports DocumentDB or RedShift.

Key features of AWS Secrets Manager include:

**Secret Creation:** Users can create secrets using the AWS Management Console, SDKs, or the AWS Command Line Interface (CLI). These secrets can include database credentials, API keys, or any other sensitive data.

**Centralized Management**: It provides a centralized place to manage all secrets, making it easier to organize, access, and control them across AWS environment.

**Encryption:** AWS Secrets Manager encrypts these secrets both at rest and in transit using industry-standard encryption protocols, ensuring the confidentiality and integrity of the stored data. The secrets managed by Secrets Manager can be encrypted using keys managed by KMS.

**Access Control:** Users can define fine-grained access control policies to specify who can access and manage secrets, helping to maintain the principle of least privilege.&#x20;

**Audit and Monitoring**: Integration with AWS CloudTrail provides a record of calls to AWS Secrets Manager for compliance and auditing purposes.&#x20;

**Cross-Region Replication**: It allows to replicate secrets across multiple AWS regions for disaster recovery purposes.

**Rotation:** One of the standout features of AWS Secrets Manager is its ability to automate the rotation of credentials. The secrets can be auto-rotated during configuration. It can periodically generate new credentials for a secret and update the applications that use them, thus enhancing security by regularly changing access credentials.

**Integration:** AWS Secrets Manager can seamlessly integrate with AWS services and other applications, allowing for secure retrieval of secrets during application runtime. This eliminates the need for hard coding credentials within applications.

### Steps for usage

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FMkGcS9MIaLUbvLGl23Ph%2Fimage.png?alt=media&amp;token=2d356f6b-935d-461b-8c1b-55bb5bde9323" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FttQEITbST2N5rOFih1n6%2Fimage.png?alt=media&amp;token=0365dfc9-d888-4692-a9e6-3905ce5702ca" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FLaCSINofiuQYXmXhkMpg%2Fimage.png?alt=media&amp;token=964078af-43aa-4e81-82f5-fd9374f35da0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fbtomh328sRvXmnyVv16P%2Fimage.png?alt=media&amp;token=2acb5303-87fd-47f2-be60-4d4791f423a8" alt=""><figcaption></figcaption></figure>

Once the rotation function is given, review and create the secret to later integrate it with the application


# AWS Certificate Manager (ACM)

ACM is useful only, if one wants to use SSL/TLS Certificate with other AWS services such as Elastic Load Balancing, Amazon CloudFront, Amazon Cognito, AWS Elastic Beanstalk, AWS App Runner, Amazon API Gateway, AWS Nitro Enclaves, AWS CloudFormation, AWS Amplify, Amazon OpenSearch Service, and AWS Network Firewall.

To get ACM certificate, steps are as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FkATVezFJQ5GXV1HtzyDo%2Fimage.png?alt=media&amp;token=56b3ed37-6782-4848-9886-9559d46a8362" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FFrPwQnN9828EGg2aytFD%2Fimage.png?alt=media&amp;token=1a7dc85f-625e-4851-811a-dfa0c7bd67fd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FRq5Y7jHp1Orzg7QZQ8O8%2Fimage.png?alt=media&amp;token=9c940104-3885-42b1-9150-64763255bb35" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fwv0sS42U4hHw5HqGlzBf%2Fimage.png?alt=media&amp;token=ac82b6cb-b862-47f6-8bb1-d92f19a95a22" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FYYkaVo0bfy3vRsB6Iojw%2Fimage.png?alt=media&amp;token=f53ab208-40c5-453a-bc06-afb365b8c7b2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FxDa75ICMRtUnPfA5DzIp%2Fimage.png?alt=media&amp;token=737c1863-93db-46d3-a787-dbb7b7c36b4d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fsy2B7QcRR1PusRQTz3WY%2Fimage.png?alt=media&amp;token=95a73f79-7d9b-45ca-a12f-f31a159a98e3" alt=""><figcaption></figcaption></figure>


# AWS Messaging Services

AWS SNS and AWS SQS are the two messaging services provided by Amazon Web Services.&#x20;

Both have use cases to be used to be integrated for applications for messaging

Example: Using Amazon SNS, messages are being subscribed to a topic which based on business logic can be queued to appropriate Lambda function as trigger

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F1rpDVMMZoMrNgpGpk1j4%2Fimage.png?alt=media&amp;token=e77c2a95-6635-44bf-8925-3b5055a07434" alt=""><figcaption><p>Source: <a href="https://miro.medium.com/v2/resize:fit:720/format:webp/1*Zh0muEji5v4nKw60pUeMAA.png">https://miro.medium.com/v2/resize:fit:720/format:webp/1*Zh0muEji5v4nKw60pUeMAA.png</a></p></figcaption></figure>

Another example can also be illustrated as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FyM67DoGwDB2OVaJcK1Mb%2Fimage.png?alt=media&amp;token=3c265351-f16a-451a-971b-e6c64d40082d" alt=""><figcaption><p>Source: <a href="https://media.amazonwebservices.com/blog/sns_sqs_image_proc_2.png">https://media.amazonwebservices.com/blog/sns_sqs_image_proc_2.png</a></p></figcaption></figure>

Order Fulfilment at eCommerce site:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fs3FBX2PoEPOhHNkj8Kv3%2Fimage.png?alt=media&amp;token=c19cbf70-0547-4c36-89fe-036f5c32986b" alt=""><figcaption><p>Source: <a href="https://www.slideshare.net/JungHakLee4/awskrug-aws-sns-sqs-and-ses">https://www.slideshare.net/JungHakLee4/awskrug-aws-sns-sqs-and-ses</a></p></figcaption></figure>


# AWS SNS (Simple Notification Service)

Amazon Simple Notification Service (AWS SNS) is a fully managed publish/subscribe messaging service.&#x20;

What is pub/sub messaging service? As per ChatGPT the following can be summarized:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FqazlSMprVfdux1aIr6tI%2Fimage.png?alt=media&amp;token=ddab68b1-405e-4b72-9eec-4811ec04d482" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Apache **KAFKA** is also an example of such messaging service&#x20;
{% endhint %}

It enables to create decoupled applications i.e., Publishers do not need to know the details of the subscribers, and subscribers do not need to know who publishes messages.

It enables the distribution of messages and notifications across different channels such as email, SMS, HTTP/HTTPS, push notifications etc. AWS SNS uses a publish-subscribe model, where publishers send messages to topics, and subscribers receive those messages based on their interest in specific topics i.e., **subscribers will receive notifications for what they have subscribed for.**

A Topic ARN is a unique identifier for an SNS topic within AWS. It’s used to address and target specific topics when publishing messages. Topic ARNs are essential for routing messages to the appropriate subscribers and play a key role in the access control policies that define who can publish and subscribe to specific topics.


# AWS Simple Queue Service (SQS)

Where AWS SNS lags is that it just passes messages, but cannot store the message for very long. This is where AWS Simple Queue Service comes into picture, where message can reside for upto 14 days.

It is also a fully managed service that is fully fault tolerant, meaning if something go down (such as power outages at the consumer end of the queue), because messages in queue can wait, it can be processed later.

SQS offers two types of queues:

* **Standard Queues**: These provide at-least-once delivery, meaning a message might be delivered multiple times **but is processed in no particular order**.
* **FIFO (First-In-First-Out) Queues**: These ensure that messages are processed exactly once and in the order they are sent.
* **Dead-Letter Queues:** If a message cannot be processed after a specified number of attempts, it can be sent to a dead-letter queue for further investigation and debugging.


# AWS Systems Manager

Previously called as Simple Systems Manager

### Features

AWS Systems Manager is for management of AWS Resources. It groups our resources into Resource Groups. It analyse our workloads to gain insights to operational data and it can also let AWS users perform actions on resource groups

Systems Manager Automation enables you to run a sequence of workflows (e.g., AWS API calls, provisioning instances, creating buckets, and firing off Lambda functions) through the convenience of a single SSM Automation document. AWS Automation can helps to automate mundane or repetitive tasks for maintenance or deployment of cloud native or hybrid infrastructure. Via a series of steps/actions defined in either JSON or YAML, SSM Automation offers useful plugins to carry out commands/API calls&#x20;

Chief use case is to achieve operational efficiency for the workload running in the cloud. Examples:

* Automation - Creation of golden AMI Image.
* Patch Management  - For deploying specific patches to worklaods in the cloud.
* Run Command - Can be used to execute commands onto all EC2 systems.
* Parameter Store - Can be used to store secrets and other configuration data in hierarchical storage.
* OpsCenter - Can be used to have centralized view to responds to alerts.
* Session Manager - Can be used to connect to private EC2 machines replacing bastion hosts.&#x20;

It has many sub services under Systems Manager:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FbPvaVBjG4eR61POLioKJ%2Fimage.png?alt=media&amp;token=10de2a83-1b43-432c-8c0d-99c5a8415369" alt=""><figcaption></figcaption></figure>


# Application Management

Two very vital services under application management subservice umbrella of AWS Systems Manager are AppConfig and Parameter Store. &#x20;

AppConfig as the name says, is used to to create, manage and deploy app configs and Parameter store secure hierarchial storage for secrets and data

### Steps for AppConfig

When an application is hosted on EC2, with the help of privileges assigned to IAM role, it can fetch the configuration of AppConfig, which internally can source configuration values from various sources such as S3, or Parameter store etc and can have multiple app config profiles with the help of Environments like Dev or Prod.&#x20;

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FQWk8XVy0knWrgHFH6pIt%2Fimage.png?alt=media&amp;token=6d997a7f-101d-44f7-9bc1-317a17215ef0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fi8kNc752CqpGaozstcyD%2Fimage.png?alt=media&amp;token=a9c3b424-8131-41fa-b10e-2c6a374dc299" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FNwq6WJ2ckBzJT325s3pr%2Fimage.png?alt=media&amp;token=ca9fd2b4-d90d-4513-93ff-0f6353918d75" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2F6aTlQbiST4AtNrHfqE3O%2Fimage.png?alt=media&amp;token=994571cd-2eee-4dcf-80c6-7d03bda1d962" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fz8yBskLAhAIqONiPXCpG%2Fimage.png?alt=media&amp;token=dbd867c8-5d5b-4f18-bda4-e2ff9bc274d6" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FqCehNrtLL695SUD3CBgT%2Fimage.png?alt=media&amp;token=412e98b6-7c05-4bf5-b9d8-9b103a7e6d4e" alt=""><figcaption></figcaption></figure>

### Steps for Parameter Store

As explained earlier, it can be used to hold key value pair to hold data in plaintext as well as secure format. This can include Database credentials also, which can internally be used in app config, which in turn can be used by the application to access the Database

Note every parameter can have version for tracking history

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FhRAOeyGNg8qdF0YRQsRc%2Fimage.png?alt=media&amp;token=9efe3523-8089-40a4-bbb0-0ca2c2201879" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FOJrzBgyDsg4XtWiiJsr2%2Fimage.png?alt=media&amp;token=84abe291-6c14-4fa7-af1d-6ace81ebcc8f" alt=""><figcaption></figcaption></figure>


# Node Management

As noted previously, **Systems Session Manager** is a service that is used to provide cli based access to EC2 workloads without the need to expose it on the internet or without the requirement of bastion host or jump host. It is part of Node Management sub service of AWS Systems Manager

AWS SSM Session Manager is an excellent feature to connect to and manage all hybrid infrastructure remotely without having to use SSH for Linux or RDP for Windows instances. It provides the added bonus of security, as IT Teams don't need SSH/RDP ports open and access control to who can establish shell sessions using IAM policies. It also allows for logging and auditing of all activity during a shell session via Session Manager.

For this to work, an SSM agent either needs to be preinstalled or needs to be installed on the EC2 instance. It is compatible with both Windows as well as Linux

The steps to setup the same are laid out in detail [here](https://guides.radifine.com/how-to-securely-access-and-transfer-file-to-an-ec2-instance-in-private-subnet-of-vpc-in-aws).

SSM agent allows administrators to remotely execute commands, automate tasks, and manage configuration settings on those instances. It provides a secure and efficient way to perform various operational tasks, such as software patching, inventory management, and software installation with the highest privileges on the EC2 instances

Note that to connect Virtual Machines in other cloud providers i.e., Non-AWS Virtual machines or on-prem machines, **Hybrid Activations** can also be used. However, it requires Key activation for SSM Agent when installed on them. It can as summarized below:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FazV5NaGciqUsWnLJkUMk%2Fimage.png?alt=media&amp;token=90918106-b5ca-48a8-af87-fbaa75b9eaee" alt=""><figcaption></figcaption></figure>

Note all of the instances that have AWS SSM agent installed can be collectively managed into **Fleet Manager**

Another important feature to understand the types of automation that can be done is to check SSM Documents (present under **Shared Resources -> Documents** ). A sample SSM Document format can look like as shown below:

&#x20;&#x20;


# Logging and Monitoring


# AWS CloudTrail

AWS CloudTrail is an AWS Service that records all activities performed in an AWS account (via cli or Mgmt Console or SDKs). This logging and auditing service from AWS can also be integrated in SIEM Solution for helping not only in Visibility, Incident Response, Debugging as well as fulfil the compliance requirements.

Event Logging in AWS:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FIAubal1NPz1q8Dx3srzg%2Fimage.png?alt=media&amp;token=e862afc5-59a9-4e91-bae5-2f45112dcb9b" alt=""><figcaption><p>Source: <a href="https://quizlet.com/616135849/aws-cloudtrail-flash-cards/">https://quizlet.com/616135849/aws-cloudtrail-flash-cards/</a></p></figcaption></figure>

As shown above,  there are mainly two types of events, management events: (control plane operations) and data events (data plane operations) and both types of events will log AWS Account, User ID/Role, IP Address, Time and resource details etc.&#x20;

Events from 90 days can be viewed from Event History.

Some of the things that should be considered while setting up CloudTrail

* Not all services are supported
* Only 5 trails per region are allowed

The logs collected in CloudTrail can be used with S3, Lamda, Athena and even CloudWatch for analysing, storage etc.

### CloudTrail Creation:

To create an audit trail in this service, steps can be as follows:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FbVlGh8mVAf87JWrqakua%2Fimage.png?alt=media&amp;token=880fc8ab-7937-40ab-b933-92536010ba4c" alt=""><figcaption></figcaption></figure>

Quick Trail Console:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fscp7Y5qkuWxzn8mwqBb5%2Fimage.png?alt=media&amp;token=8876de16-881f-4125-bad6-1a54e9fa3610" alt=""><figcaption></figcaption></figure>

More Detailed Console:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FQqMfctv0jc4geB6BH92c%2Fimage.png?alt=media&amp;token=ad1db314-d97d-4f92-8a2f-a59a33c88af9" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FjzTv5xBh80BAaFyKRpDj%2Fimage.png?alt=media&amp;token=f3718787-c65e-4ebc-9c28-f9197a644aab" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2Fb0qgGNP2rutTy4MmtUEb%2Fimage.png?alt=media&amp;token=13ea73c2-3014-4bf6-8f1d-557761ebe77e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FPTbeh7drxYpomROk1Qp5%2Fimage.png?alt=media&amp;token=ebddbacf-44df-4061-836d-d2694011d2c3" alt=""><figcaption></figcaption></figure>

Finally create the trail:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FxhnWiSoPEglLeJdcZmyJ%2Fimage.png?alt=media&amp;token=c0320da2-360d-4fb5-bd34-c66059d92c21" alt=""><figcaption></figcaption></figure>

Event History would look something like this:

<figure><img src="https://3681896347-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjfQTFfcSjS8MYnjfKw2c%2Fuploads%2FmyRGuCdsd5e7x8tNytKq%2Fimage.png?alt=media&amp;token=3394a9ea-fe95-4e9a-9b3e-44bf9f7dd54d" alt=""><figcaption></figcaption></figure>


# AWS CloudWatch


# AWS Macie


# AWS Inspector


# AWS GuardDuty


# Welcome to Notes of Radifine Labs!!

These are personalized notes of Yobroda to help the community in general with concepts

## Table of Contents

### Linux Fundamentals

You can visit it here: <https://notes.radifine.com/v/linux-fundamentals/>

### AWS Fundamentals

You can visit it here: <https://notes.radifine.com/v/aws>


