CloudFront Using AWS PowerShell

Suyash garg
15 min readOct 26, 2020

Introduction

In this article i am going to show how to do following task using powershell:-

  • Configuring apache web server on EC2 Instance
  • Mounting an EBS Block Device on the above EC2 Instance.
  • Creating website using the picture store in s3 bucket.
  • Setting up Content Delivery Network using CloudFront and using the origin domain as S3 bucket.
  • Finally place the Cloudfront URL on the website code.

NOTE:- I assume that you know how to set up aws powershell in windows and you have sufficient privilege for doing all the following task if not you can refer to my previous article AWS Powershell for Better Productivity

Configuring Apache web server on EC2 instance

Step 1:- Creating an ec2 instance

To create an ec2 instance use to below command:-

New-EC2Instance -ImageId ami-0e306788ff2473ccb -InstanceType t2.micro -SecurityGroupId sg-0014c758fbd768dd0 -KeyName egkeypair

ImageId:- is the unique id given to every AMI(Amazon Machine Image) you can google it to find the AMI id in my case i am using Amazon Linux 2 AMI for a good reason which i am going to let later

InstanceType:- is type of instances we are allocating to an instance in my case is t2.micro

KeyName:- The name of key pair I am going to use for the following task. if the key pair name is not provided we are not able to connect to ec2 instance for future work

SecurityGroupId:- this is the Security Group Id i am going to use for the following task you can use any security group. if security is not provided aws is going to use default security group

copy the reservation id for further references in my case is r-0d793e615a15fa553

Step 2:- Collecting necessary information for connecting to ec2 instances

To connect to ec2 instances we are going to need to need public ip address that was provided by amazon at the run time for finding this we need instances id but for no good reason powershell never provided instances id directly with any command but we can use reservation id print more detail about instances to that use following command:-

PS C:\Users\hp> (Get-EC2Instance -Filter @{name=”reservation-id”;value=”r-0d793e615a15fa553"}).Instances | Format-List -Property PublicIpAddress,InstanceId

Get-EC2Instance:- its used to print information but that command alone did not print instance id

Filter:- its use to filter instances in based on some parameter it very useful when you have 100s of instance and find only instances that uses particular AMI. .Instances is the tell to fetch the information we are asking is belong to an instance

| :- this symbol is know as pipe(|) is used to give output of one command to another command in my our case we give output to Format-List

Format-List:- to print data in list if you don’t use list format it use table by default table in powershell omit extra column which did not fit in the screen in my case is show instances id but this is not always and sometimes is omit required information so is always recommended to use Format-List.

Property:- Which property we need as a output you can specify any number of property if property did not exists it powershell never give error it only show property name with blank value as a output

copy the public ip and store somewhere for further uses

PublicIpAddress : 52.66.113.97
InstanceId : i-0760bc4342d192a5a

Step 2:- converting pem to ppk

Now for connecting ec2 instances we are going to need ssh client for windows their are many ssh client available for windows but for this task we are going to use Putty which is industrial grade software you can download putty form here https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html. use version that best fit to your windows version

Now amazon provide key which was in pem (Privacy-Enhanced Mail) format but putty only support ppk (putty private key) to convert pem to ppk use puttygen which is already comes with bundled with putty if it not present download from here https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html

Starting screen of puttygen

Steps to convert pem to ppk:-

  • Click on load button
  • locate the where is the key is store remember for dropdown box all file option must select, and click on open button
  • Click on save private key button
  • Click on yes (passphrase is work like password)
  • give any name to key but it always good practice to ppk key name same as pem key it helps very much in future when you have to work with 100s of keys
  • now close the puttygen

Step 4:- Using putty to connect to ec2 instance

Now we have all the sufficient information to connect to ec2 instance now open putty software and perform following steps

  • enter ip address like this ec2-user@52.66.113.97 (ec2-user is name from which we are going to connect and ip is the public ip which we found early ) after this step your putty is going to look like this
  • now click on ssh then click on auth
  • click on browse button select ppk key which we created early
  • click on open button
  • if every thing is write it show windows like this
  • don’t worry for this warning click on yes
  • finally we come to landing page of amazon linux which look like this
  • now we need root privilege(is the highest privilege in any linux os) for doing further task without any problem
  • to obtain root privilege use the sudo su root command

sudo:- this command is used to give one user the power on another user

su:- one of the main function of this command to change the current user

root:- name of the user

note:- this is only work because amazon use the setting like this in normally linux operating system this command is not always work you can also change the setting and disable this command in side amazon linux and give direct access to root user using ssh but this is not going cover in this article

Step 5:- Installing apache web server on amazon linux

This task is actually pretty easy just use yum install httpd

type y(for yes)

Step 6:- Starting apache web server

To start apache web server use systemctl start httpd command

generally this command did not provide any output if it run successfully without any error

is it always good practice to use systemctl enable httpd command this command automatically start apache web server whenever you restart your system

to test whether apache web server is running or not copy and paste ec2 public ip in any browser if it show page like this it means is working fine

Mounting an EBS Block Device on the above EC2 Instance

Step 1:- Creating an EBS block device

Now minimize the putty and go back to powershell and use following command to create new ebs volume:-

New-EC2Volume -AvailabilityZone ap-south-1a -VolumeType gp2 -Size 1

AvailabilityZone:- is compulsory to give provide AZ in my case is it Mumbai you can google it to find your AZ

VolumeType:- is not required you can also omit it if you omit it automatically select gp2

Size:- is it required to provide volume size in GiB in my case I provided 1GB of volume remember always use integer if you give decimal value like 1.4 or 0.9 its give error

copy volume id for further references in my case is vol-0834a574ad2a20c39

Step 2:- Attaching EBS volume to EC2 Instance

To attach volume to EC2 instances use the following command

Add-EC2Volume -VolumeId vol-0834a574ad2a20c39 -InstanceId i-0760bc4342d192a5a -Device /dev/sdf

VolumeId:- its the id of volume we want to attach

InstanceId:- its the id of instance we want to attach remember both instance and volume is must in same AZ or if not it gives error

Device:- is name the name of the device we want to give according amazon you can give name from sdf to sdp but don’t worry you can give any name from sde and saz also it only give error when you have attach volume same name.

note:- who guys don’t know what is meaning of /dev/sdf from previous example is a quick summary for this

  • /dev is the folder in which all information about device is store
  • /sd is name of hard disk
  • f is the number of hard disk f means 6 and g means 7 it’s not important to have a-e before creating f you can directly create say z or if you want to goes beyond sdz you can use sdaa, sdab up to sdzzz(which is equivalent 18278 according linux official documents)

so in summary /dev/sdf means hard disk number 6(which is equivalent to f)

note:- amazon instances did not use /dev/sdf internally it’s uses /dev/xdvf (xdv stands for xen virtual disk number 6(which is equivalent to f))

Step 3:- Creating partition, formatting and mounting

Now we are to full linux mode if you are not comfortable with partition, formatting and mounting, concept pleases refer to some other article it is different topic in it self.

Now minimize powershell and go back to putty and type the fdisk -l command to see all the disk that is connected to now ec2 instance if it show name of hard disk (dev/xvdf) which we use in previous step it means our hard disk is connected without any error

Now to create partition use fdisk /dev/xvdf command

Now press n to create new partition and press three times enter key and finally w to save the partition this will create one partition of size nearly 1GB final screen some show like this

You can use lsblk command to check whether partition is created or not

In my case one partition of size 1023MB (nearly equal to 1Gb) is created with name /dev/xvdf1

For formatting partition use mkfs.ext4 /dev/xvdf1 command to format partition

mkfs:- is stand for make file system

ext4:- extend version 4 this most commonly used format type in linux (you can also use ext2, ext3, fat in some linux version default is ext2)

/dev/xvdf1:- is the name of partition we want to format

Now for mounting the formatted partition use mount /dev/xvdf1 /var/www/html command

generally this command did not provide any output if it run successfully without any error

mount:- command that helps to mount formatted partition

/dev/xvdf1:- name of formatted partition that we mount

/var/www/html:- directory where we mount our formatted partition this is also the default directory form where apache web server use to read file we can also change default directory in apache web server configuration file but for now this blog this is more than enough

Creating website using the picture store in S3 bucket.

Step 1:- Creating s3 bucket

Now minimize the putty and go back to powershell and type the following command to create new s3 bucket

New-S3Bucket -BucketName suyash1234

Bucketname:- name of the bucket we want to create

Step 2:- Uploading image in s3 bucket

To upload image in s3 bucket use the following command

Write-S3Object -BucketName suyash1234 -File .\logo.jpeg -PublicReadOnly

BucketName:- Name of the bucket where we want to upload a file

File:- name of the file which we want to upload .\ this tell powershell to look file in a current directory in my case it is G:\ you can also specify the path of the file in my case the full path is G:\logo.jpeg

PublicReadOnly:- this make file viewable by anyone on the internet who has the url of the file

Key:- this parameter change the name of the file at the time of uploading for eg if we use -Key cover.jpeg in previous example this upload the logo.jpeg in s3 bucket and name it as cover.jpeg

Powershell also show the progress bar when uploading file if file size is big you can see it clearly like this

Step 4:- Creating a simple web page in EC2 using the image we upload in S3 bucket

Generally developer didn’t directly use ec2 instance to create website they create web site in their local computer and then upload it ec2 instances it has two main reason

  • first reason ec2 charge hourly based and website creation is not a 1 or 2 hour process it takes many days to create full fledged website if developer use ec2 instance for creation amazon going to charge high amount on money.
  • second ec2 is 100% command based so it doesn’t provide and fancy graphical ide this make website creation time very long

But for our demo we are going to create small website so it is fine for us to create web site directly inside instance

Now minimize powershell and go back to putty it time to create a simple website and put a image in that website

now go to default directory apache web server which is /var/www/html for this use the cd /var/www/html/ command

we didn’t install any graphical text editor/ide inside ec2 instance but we can use vi (it didn’t have any full form and it always written as small case)

vi page.html

vi:- name of the program

page.html:- file name that vi going to use if file doesn’t exists it create new if exists it open open existing file

if are new in vi didn’t use an keyboard shortcut vi didn’t support any they have their own command tones of command in this article we are only going to use necessary command

now press i this command enter vi in editing mode(generally also known as insertion mode)

now type html code as much as you like but in article i am going to use a h1 header tag with image that comes from s3 bucket that we upload early

<h1>Hello from ec2 instance</h1>

<image src=”https://suyash1234.s3.ap-south-1.amazonaws.com/logo.jpeg”>

now where this url come from we created this, powershell didn’t not provide any command directly to find the object url but we use bucket name, availability zone id, and file name to create this url on the go like this https://suyash1234.s3.ap-south-1.amazonaws.com/logo.jpeg first break url in six part that look like this

  1. https:// (it always start form this protocol only)
  2. bucket name (in my case suyash1234)
  3. .s3. (service name it always going to s3)
  4. availability zone id (availability zone id where our s3 bucket created in my case is ap-south-1 (which is equivalent to Asia Pacific (Mumbai)))
  5. .amazonaws.com/
  6. file name (full path of the and file name that we want to access in that particular bucket)

If you follow this six steps you can create any url on file store in any bucket

now let go back to our vi now press esc key in keyboard (esc key is used to put vi in command mode) and type :wq and enter

all command in vi begin with : (colon)

w:- stand for write

q:- stand for quit

together they stand for (save and quite)

if everything's write now we are able to see web page any browser using ec2 public ip like this 52.66.113.97/page.html like this

Setting up Content Delivery Network using CloudFront and using the origin domain as S3 bucket

Step 1:- create cloudfront web distribution

Now finally we are going setup CDN(Content Delivery Network) using amazon cloudfront now minimize putty and go to powershell and use the following command to set up a cloudfront distribution

$origin = New-Object Amazon.CloudFront.Model.Origin
$origin.DomainName = “
suyash1234.s3.ap-south-1.amazonaws.com
$origin.Id = “myid”
$origin.S3OriginConfig = New-Object Amazon.CloudFront.Model.S3OriginConfig
$origin.S3OriginConfig.OriginAccessIdentity = “”

New-CFDistribution -DistributionConfig_Enabled $true -DistributionConfig_Comment “PowerShell Example” -Origins_Item $origin -Origins_Quantity 1 -DistributionConfig_CallerReference Client -DefaultCacheBehavior_TargetOriginId $origin.Id -TrustedSigners_Enabled $false -TrustedSigners_Quantity 0 -DefaultCacheBehavior_ViewerProtocolPolicy allow-all -DefaultCacheBehavior_MinTTL 1000 -ForwardedValues_QueryString $true -Cookies_Forward all

DistributionConfig_Enabled:- enable or disable the distribution as soon as it created (true = enable, false = disable)

DistributionConfig_Comment:- a comment at the time of creation distribution two distribution may have same comment

DistributionConfig_CallerReference:- A unique value that ensures that the request can’t be replayed CallerReference is a value that you already sent in a previous request to create a distribution, CloudFront returns a Distribution Already Exists error.

TrustedSigners_Enabled:- it define whether person with cloud distribution url is able to content or not (true = he/she can’t see the content, false = he/she can see the content)

TrustedSigners_Quantity:- maximum number of person can store inside a trusted signer cache a given point of time(0 = infinity)

DefaultCacheBehavior_ViewerProtocolPolicy:- which protocol use has to use when accessing cloudfront url (allow-all means user can use both http and https protocol at starting of the url)

DefaultCacheBehavior_MinTTL = set minimum cache ttl time

copy and save both etag and end part of location in my this is

etag = E2J84HD4MVNNS5
id = E1IXZGJ2PWGQLM

now finally use this Get-CFDistribution -Id E1IXZGJ2PWGQLM command to find the cloudfront domain name

copy and save domain name field in my case it is dtwkvusmqtpec.cloudfront.net

note:- amazon provide two command for creating distribution for creating web based distribution command is New-CFDistribution and for creating rtmp based distribution command is New-CFStreamingDistribution

Step 2:- Updating web app to use cloudfront url

Now minimize powershell and go to putty open our web which is in /var/www/html/ folder and page name (in my case is page.html) open it using vi page.html command now do below steps

press i to go in insert mode

write new html code in file like this

<h1>Hello cloudfront</h1

<image src="https://dtwkvusmqtpec.cloudfront.net/logo.jpeg”>

press esc key in keyboard (esc key is used to put vi in command mode) and type :wq and enter

if everything’s write now we are able to see web page any browser using ec2 public ip like this 52.66.113.97/page.html

Getting help

Find help of any command is not much difficult in powershell you can use

help [command-name] for eg

help New-EC2Volume

give the help about New-EC2Volume command you can also use some parameter:-

  • -Full:- this parameter show the full help of that command along all the parameter its support it’s uses and whether is required or not
  • -Example:- this parameter show the example of that command
  • -Online:- this parameter show open help file in default browser you must have internet connectivity for this parameter

Closing Note

every command we in this blog support some common parameters

  • (-AccessKey, -SecretKey):- when you want to use another account
  • -Region:- when you want do some work other than default region
  • -ProfileName:- when you want to use profile other than default profile you can create any number of profile using Set-AWSCredential

Thank for everyone to read my article till end if you have any doubt please comment if you have any suggestion please mail all comment both positive and negative is more than welcomed

Contact Detail

LinkeDin [https://www.linkedin.com/in/suyash-garg-50245b1b7]

Additional Tags

#awscloud #awscli #aws #vimaldaga #righteducation #educationredefine #rightmentor #worldrecordholder #linuxworld #makingindiafutureready #righeudcation #awsbylw #arthbylw

--

--