<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ryan Adcock on Medium]]></title>
        <description><![CDATA[Stories by Ryan Adcock on Medium]]></description>
        <link>https://medium.com/@ryan.a.adcock?source=rss-8822cf9b0f81------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*i5ryo5xVA3e1K2dhHuRgCQ.jpeg</url>
            <title>Stories by Ryan Adcock on Medium</title>
            <link>https://medium.com/@ryan.a.adcock?source=rss-8822cf9b0f81------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:48:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryan.a.adcock/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Terraform: Using an Autoscaling Group with S3 Bucket as a Remote Backend and DynamoDB]]></title>
            <link>https://medium.com/@ryan.a.adcock/terraform-using-an-autoscaling-group-with-s3-bucket-as-a-remote-backend-and-dynamodb-ccd3bd6da997?source=rss-8822cf9b0f81------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccd3bd6da997</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Ryan Adcock]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 03:39:34 GMT</pubDate>
            <atom:updated>2023-04-13T03:46:20.025Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I am going to show you step-by-step how to use Terraform to create an autoscaling group using a launch template to launch EC2 Instances in AWS that are bootstrapped with an Apache Web Server. And how to create an S3 bucket that has a custom policy, blocks public access, and is used as a remote backend with an AWS DynamoDB Table.</p><h3><strong>Prerequisites:</strong></h3><ul><li>Basic understanding and knowledge of using the CLI on a Linux OS</li><li>An AWS account</li><li>Access to an IDE (Cloud 9, Visual Studio, etc.)</li></ul><h3>Real World Scenario</h3><p>An e-commerce company needs to handle a surge in traffic during the holiday season. The company wants to ensure that their website remains available and responsive to customers even during high traffic periods.</p><p>The project can be used to launch an Auto Scaling group that spans two subnets in the default VPC, ensuring high availability and fault tolerance. The Auto Scaling group will automatically scale up or down based on traffic, ensuring that the website remains responsive to customers at all times.</p><p>To ensure that the instances in the Auto Scaling group are secure, a security group is created that allows traffic from the internet and associates it with the instances. Additionally, a script is included in the user data to launch an Apache web server, ensuring that the website is available to customers.</p><p>To ensure that the Auto Scaling group has the appropriate capacity, it is set to have a minimum of two instances and a maximum of five. This ensures that the website can handle a surge in traffic during the holiday season, while also minimizing costs during periods of low traffic.</p><p>To verify that everything is working correctly, the public IP addresses of the two instances are checked. One of the instances is manually terminated to verify that another one spins up to meet the minimum requirement of two instances.</p><p>Finally, to ensure that the infrastructure is reliable and can be easily managed, an S3 bucket is created and set as the remote backend for Terraform. This ensures that the infrastructure is versioned and can be easily rolled back if necessary.</p><p><strong>*Tip </strong>— Be sure to use Variables where you feel appropriate to make your code as reusable as possible. Generally if it’s a value you think could change in the future or if it’s a value that’s repeated, then it should be a variable.</p><h3>Objectives Breakdown:</h3><ol><li>Launch an Auto Scaling group that spans 2 subnets in your default vpc.</li><li>Create a security group that allows traffic from the internet and associate it with the Auto Scaling group instances.</li><li>Include a script in your user data to launch an apache webserver. The Auto Scaling group should have a min of 2 and max of 5.</li><li>To verify everything is working check the public ip addresses of the two instances. Manually terminate one of the instances to verify that another one spins up to meet the minimum requirement of 2 instances.</li><li>Create an S3 bucket and set it as your remote backend.</li></ol><h3>What is Apache Web Server?</h3><p>The Apache Web Server is a free and <a href="https://en.wikipedia.org/wiki/Open-source_software">open-source</a> cross-platform <a href="https://en.wikipedia.org/wiki/Web_server">web server</a> software, released under the terms of <a href="https://en.wikipedia.org/wiki/Apache_License">Apache License 2.0</a>. Apache is developed and maintained by an open community of developers under the auspices of the <a href="https://en.wikipedia.org/wiki/Apache_Software_Foundation">Apache Software Foundation</a>. <a href="https://en.wikipedia.org/wiki/Apache_HTTP_Server"><em>(source)</em></a></p><h3><strong>Compile variables.tf code</strong></h3><p>Let’s start by creating our <strong>variables.tf </strong>file in a new directory called <strong>terraform-wk21</strong> and use <strong>Visual Studio Code.</strong></p><pre>mkdir terraform-wk20<br>code variables.tf</pre><p>I am going to be using my default VPC so there is no need to write code to create a new VPC. But we will need the ID of the default VPC, so head on over to your AWS console to get the ID of the default VPC. Now, copy the IDs of 2 subnets from the default VPC. Finally, grab an AMI ID and an Instance Type for the instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*B69LR6Pv1YMEVLcK.jpeg" /></figure><p>Here is how the <strong>variables.tf </strong>file looks:</p><pre>variable &quot;subnet-1&quot; {<br>  description = &quot;Subnet 1&quot;<br>  default     = &quot;subnet-0c23be44ab1c5564c&quot;<br>}<br><br>variable &quot;subnet-2&quot; {<br>  description = &quot;Subnet 2&quot;<br>  default     = &quot;subnet-0c1fed6313c663cb2&quot;<br>}<br><br>variable &quot;default-vpc&quot; {<br>  description = &quot;Default VPC&quot;<br>  default     = &quot;vpc-05f530a52657d4677&quot;<br>}<br><br>variable &quot;ami_id&quot; {<br>  description = &quot;AMI ID&quot;<br>  default     = &quot;ami-007855ac798b5175e&quot;<br>}<br><br>variable &quot;instance-type&quot; {<br>  description = &quot;EC2 Instance Type&quot;<br>  default     = &quot;t2.micro&quot;<br>}</pre><h3>Compile main.tf code</h3><p>Now, let’s create our <strong>main.tf </strong>file in the same directory,<strong>terraform-wk21,</strong> and use <strong>Visual Studio Code.</strong></p><pre>code main.tf</pre><p>Now, since we want to utilize AWS services we need to set the correct required providers. For more information regarding this code, click <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">here</a>. Enter this code into the <strong>main.tf </strong>file:</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br># Configure the AWS Provider<br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}</pre><p>Let’s create our security group that will be assigned to our EC2 instance. To get started, click <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group">here</a> to refer to the hashicorp/aws documentation about security groups. We want the security group allow traffic from port 80 (the default port for Apache). By default AWS creates an “Allow All” egress rule however, Terraform will delete this default so we need to recreate it using the “egress” block. Enter the following code into the <strong>main.tf</strong> file:</p><pre>#Create the Security Group<br>resource &quot;aws_security_group&quot; &quot;Web-Store-SG&quot; {<br>  vpc_id = var.default-vpc<br><br>  ingress {<br>    description = &quot;HTTP&quot;<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><p>Now, we need to create our EC2 instance lauch template. To write this code, I will be using the hashicorp/aws documentation about <strong>aws_launch_template</strong> <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/launch_template">here</a>. We also need to pass specific commands to the instances created by the launch template via the user_data argument. You will notice <strong>base64encode()</strong>, this is vital to avoid the following error message (<strong>Error: InvalidUserData.Malformed: Invalid BASE64 encoding of user data)</strong>. To better understand the template_file code structure, I will be referencing the hashicorp/template documentation <a href="https://registry.terraform.io/providers/hashicorp/template/latest/docs/data-sources/file">here</a>. For a complete explanation of the necessary commands to install the Apache Web Server, refer to an article I wrote previously on the subject <a href="https://medium.com/@ryan.a.adcock/how-to-install-apache-web-server-on-ubuntu-18-04-bionic-beaver-lts-using-the-command-line-ddb3c4ff2f4c">here</a>. Enter the following code into the <strong>main.tf</strong> file:</p><pre>data &quot;template_file&quot; &quot;instances_user_data&quot; {<br>  template = &lt;&lt;-EOF<br>    #!/bin/bash<br>    apt update -y<br>    apt install -y apache2<br>    echo &quot;Welcome to my Web-Store-ASG!&quot; &gt; var/www/html/index.html<br>    systemctl enable apache2<br>    systemctl start apache2<br>  EOF<br>}<br><br>resource &quot;aws_launch_template&quot; &quot;Web-Store-Template&quot; {<br>  image_id      = var.ami_id<br>  instance_type = var.instance-type<br>  key_name      = &quot;KeyPair1&quot;<br>  name_prefix   = &quot;Web-Store&quot;<br>  network_interfaces {<br>    associate_public_ip_address = &quot;true&quot;<br>    security_groups             = [aws_security_group.Web-Store-SG.id]<br>  }<br><br>  user_data = base64encode(data.template_file.instances_user_data.rendered)<br><br>  tags = {<br>    Name      = &quot;Web-Store&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}</pre><p>In the above code, you will see <strong>key_name = “KeyPair1”</strong>, that is a key pair that I have previously used and it will allow me to SSH into the instance after creation if I ever needed to in the future. I would also need to update the security group to allow access on port 22 from my IP Address. (Not necessary to complete the objectives for this scenario)</p><p>Next, let’s create the autoscaling group that will utilize the launch template we just created. To write this code, I will be using the hashicorp/aws documentation about aws_instance <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/autoscaling_group">here</a>. Enter the following code into the <strong>main.tf</strong> file:</p><pre>resource &quot;aws_autoscaling_group&quot; &quot;Web-Store-ASG&quot; {<br>  max_size            = 5<br>  min_size            = 2<br>  desired_capacity    = 2<br>  health_check_type   = &quot;ELB&quot;<br>  vpc_zone_identifier = [var.subnet-1, var.subnet-2]<br>  launch_template {<br>    id      = aws_launch_template.Web-Store-Template.id<br>    version = &quot;$Latest&quot;<br>  }<br>}</pre><p>Now, we need to create our S3 Bucket that will be used as the remote backend. We will also create a policy that will be passed to the S3 Bucket that will allow it to be the remote backend. <strong>(*Note — We will have to add code after the S3 Bucket is created to set it as the remote backed. If we try to set the S3 Bucket as the remote backend prior to it’s creation we will receive an error when we run the Terraform code)</strong>. To write this code, I will be using the hashicorp/aws documentation about aws_s3_bucket <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket">here</a>, aws_s3_bucket_policy <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_policy">here</a>, and aws_s3_bucket_versioning <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_versioning">here</a>. S3 Bucket Versioning is not necessary but it is highly recommended, read more about why <a href="https://developer.hashicorp.com/terraform/language/settings/backends/s3">here</a>. Enter the following code into the <strong>main.tf</strong> file:</p><pre>#Create S3 Bucket<br>resource &quot;aws_s3_bucket&quot; &quot;web-store-s3&quot; {<br>  bucket = &quot;web-store-s3&quot;<br><br>  tags = {<br>    Name      = &quot;Web-Store&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_policy&quot; &quot;s3-backend-policy&quot; {<br>  bucket = aws_s3_bucket.web-store-s3.id<br>  policy = &lt;&lt;-EOF<br>  {<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>      {<br>        &quot;Effect&quot;: &quot;Allow&quot;,<br>        &quot;Principal&quot;: &quot;*&quot;,<br>        &quot;Action&quot;: [ &quot;s3:*&quot; ],<br>        &quot;Resource&quot;: [<br>          &quot;${aws_s3_bucket.web-store-s3.arn}&quot;,<br>          &quot;${aws_s3_bucket.web-store-s3.arn}/*&quot;<br>        ]<br>      }<br>    ]<br>  }<br>EOF<br>}<br><br>resource &quot;aws_s3_bucket_versioning&quot; &quot;terraform_state&quot; {<br>  bucket = aws_s3_bucket.web-store-s3.id<br><br>  versioning_configuration {<br>    status = &quot;Enabled&quot;<br>  }<br>}</pre><p>Finally, we need to create our DynamoDB Table. To write this code, I will be using the hashicorp/aws documentation about aws_dynamodb_table <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/dynamodb_table">here</a>. Enter the following code into the <strong>main.tf</strong> file:</p><pre>resource &quot;aws_dynamodb_table&quot; &quot;s3-db-backend&quot; {<br>  name           = &quot;s3-db-backend&quot;<br>  read_capacity  = 1<br>  write_capacity = 1<br>  hash_key       = &quot;LockID&quot;<br><br>  attribute {<br>    name = &quot;LockID&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  tags = {<br>    Name      = &quot;Web-Store&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}</pre><p>Here is the final version of the complete <strong>main.tf</strong> file.</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br># Configure the AWS Provider<br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}<br><br>#Create the Security Group<br>resource &quot;aws_security_group&quot; &quot;Web-Store-SG&quot; {<br>  vpc_id = var.default-vpc<br><br>  ingress {<br>    description = &quot;HTTP&quot;<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}<br><br>data &quot;template_file&quot; &quot;instances_user_data&quot; {<br>  template = &lt;&lt;-EOF<br>    #!/bin/bash<br>    apt update -y<br>    apt install -y apache2<br>    echo &quot;Welcome to my Web-Store-ASG!&quot; &gt; var/www/html/index.html<br>    systemctl enable apache2<br>    systemctl start apache2<br>  EOF<br>}<br><br>resource &quot;aws_launch_template&quot; &quot;Web-Store-Template&quot; {<br>  image_id      = var.ami_id<br>  instance_type = var.instance-type<br>  key_name      = &quot;KeyPair1&quot;<br>  name_prefix   = &quot;Web-Store&quot;<br>  network_interfaces {<br>    associate_public_ip_address = &quot;true&quot;<br>    security_groups             = [aws_security_group.Web-Store-SG.id]<br>  }<br><br>  user_data = base64encode(data.template_file.instances_user_data.rendered)<br><br>  tags = {<br>    Name      = &quot;Web-Store&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}<br><br>resource &quot;aws_autoscaling_group&quot; &quot;Web-Store-ASG&quot; {<br>  max_size            = 5<br>  min_size            = 2<br>  desired_capacity    = 2<br>  health_check_type   = &quot;ELB&quot;<br>  vpc_zone_identifier = [var.subnet-1, var.subnet-2]<br>  launch_template {<br>    id      = aws_launch_template.Web-Store-Template.id<br>    version = &quot;$Latest&quot;<br>  }<br>}<br><br>#Create S3 Bucket<br>resource &quot;aws_s3_bucket&quot; &quot;web-store-s3&quot; {<br>  bucket = &quot;web-store-s3&quot;<br><br>  tags = {<br>    Name      = &quot;Web-Store&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_policy&quot; &quot;s3-backend-policy&quot; {<br>  bucket = aws_s3_bucket.web-store-s3.id<br>  policy = &lt;&lt;-EOF<br>  {<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>      {<br>        &quot;Effect&quot;: &quot;Allow&quot;,<br>        &quot;Principal&quot;: &quot;*&quot;,<br>        &quot;Action&quot;: [ &quot;s3:*&quot; ],<br>        &quot;Resource&quot;: [<br>          &quot;${aws_s3_bucket.web-store-s3.arn}&quot;,<br>          &quot;${aws_s3_bucket.web-store-s3.arn}/*&quot;<br>        ]<br>      }<br>    ]<br>  }<br>EOF<br>}<br><br>resource &quot;aws_s3_bucket_versioning&quot; &quot;terraform_state&quot; {<br>  bucket = aws_s3_bucket.web-store-s3.id<br><br>  versioning_configuration {<br>    status = &quot;Enabled&quot;<br>  }<br>}<br><br>resource &quot;aws_dynamodb_table&quot; &quot;s3-db-backend&quot; {<br>  name           = &quot;s3-db-backend&quot;<br>  read_capacity  = 1<br>  write_capacity = 1<br>  hash_key       = &quot;LockID&quot;<br><br>  attribute {<br>    name = &quot;LockID&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  tags = {<br>    Name      = &quot;Web-Store&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}</pre><h3>Run the code!</h3><p>We have created all the code for our <strong>main.tf</strong>, now let’s run it. First, run <strong>“terraform init”</strong> in the directory of the <strong>main.tf</strong> file to initialize Terraform.</p><pre>input:<br><br>terraform init<br><br>output:<br><br>Initializing provider plugins...<br>- Reusing previous version of hashicorp/aws from the dependency lock file<br>- Finding latest version of hashicorp/template...<br>- Using previously-installed hashicorp/aws v4.62.0<br>- Installing hashicorp/template v2.2.0...<br>- Installed hashicorp/template v2.2.0 (signed by HashiCorp)<br><br>Terraform has made some changes to the provider dependency selections recorded<br>in the .terraform.lock.hcl file. Review those changes and commit them to your<br>version control system if they represent changes you intended to make.<br><br>Terraform has been successfully initialized!<br><br>You may now begin working with Terraform. Try running &quot;terraform plan&quot; to see<br>any changes that are required for your infrastructure. All Terraform commands<br>should now work.<br><br>If you ever set or change modules or backend configuration for Terraform,<br>rerun this command to reinitialize your working directory. If you forget, other<br>commands will detect it and remind you to do so if necessary.</pre><p>Next, let’s run <strong>“terraform validate”</strong> to ensure the configuration is valid.</p><pre>input:<br><br>terraform validate<br><br>output:<br><br>Success! The configuration is valid.</pre><p>Success! Next, let’s run <strong>“terraform plan”</strong> to ensure there are no errors in our code.</p><pre>input:<br><br>terraform plan<br><br>output:<br><br>data.template_file.instances_user_data: Reading...<br>data.template_file.instances_user_data: Read complete after 0s [id=6d08f0bd69fb13bfa5cfc206856a93515fd4946ca3a7713dba2dff86997e7962]<br><br>Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:<br>  + create<br><br>Terraform will perform the following actions:<br><br>  # aws_autoscaling_group.Web-Store-ASG will be created<br>  + resource &quot;aws_autoscaling_group&quot; &quot;Web-Store-ASG&quot; {<br>      + arn                       = (known after apply)<br>      + availability_zones        = (known after apply)<br>      + default_cooldown          = (known after apply)<br>      + desired_capacity          = 2<br>      + force_delete              = false<br>      + force_delete_warm_pool    = false<br>      + health_check_grace_period = 300<br>      + health_check_type         = &quot;ELB&quot;<br>      + id                        = (known after apply)<br>      + max_size                  = 5<br>      + metrics_granularity       = &quot;1Minute&quot;<br>      + min_size                  = 2<br>      + name                      = (known after apply)<br>      + name_prefix               = (known after apply)<br>      + protect_from_scale_in     = false<br>      + service_linked_role_arn   = (known after apply)<br>      + vpc_zone_identifier       = [<br>          + &quot;subnet-0c1fed6313c663cb2&quot;,<br>          + &quot;subnet-0c23be44ab1c5564c&quot;,<br>        ]<br>      + wait_for_capacity_timeout = &quot;10m&quot;<br><br>      + launch_template {<br>          + id      = (known after apply)<br>          + name    = (known after apply)<br>          + version = &quot;$Latest&quot;<br>        }<br>    }<br><br>  # aws_dynamodb_table.s3-db-backend will be created<br>  + resource &quot;aws_dynamodb_table&quot; &quot;s3-db-backend&quot; {<br>      + arn              = (known after apply)<br>      + billing_mode     = &quot;PROVISIONED&quot;<br>      + hash_key         = &quot;LockID&quot;<br>      + id               = (known after apply)<br>      + name             = &quot;s3-db-backend&quot;<br>      + read_capacity    = 1<br>      + stream_arn       = (known after apply)<br>      + stream_label     = (known after apply)<br>      + stream_view_type = (known after apply)<br>      + tags             = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + tags_all         = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + write_capacity   = 1<br><br>      + attribute {<br>          + name = &quot;LockID&quot;<br>          + type = &quot;S&quot;<br>        }<br>    }<br><br>  # aws_launch_template.Web-Store-Template will be created<br>  + resource &quot;aws_launch_template&quot; &quot;Web-Store-Template&quot; {<br>      + arn             = (known after apply)<br>      + default_version = (known after apply)<br>      + id              = (known after apply)<br>      + image_id        = &quot;ami-007855ac798b5175e&quot;<br>      + instance_type   = &quot;t2.micro&quot;<br>      + key_name        = &quot;KeyPair1&quot;<br>      + latest_version  = (known after apply)<br>      + name            = (known after apply)<br>      + name_prefix     = &quot;Web-Store&quot;<br>      + tags            = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + tags_all        = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + user_data       = &quot;IyEvYmluL2Jhc2gKYXB0IHVwZGF0ZSAteQphcHQgaW5zdGFsbCAteSBhcGFjaGUyCmVjaG8gIldlbGNvbWUgdG8gbXkgV2ViLVN0b3JlLUFTRyEiID4gdmFyL3d3dy9odG1sL2luZGV4Lmh0bWwKc3lzdGVtY3RsIGVuYWJsZSBhcGFjaGUyCnN5c3RlbWN0bCBzdGFydCBhcGFjaGUyCg==&quot;<br><br>      + network_interfaces {<br>          + associate_public_ip_address = &quot;true&quot;<br>          + security_groups             = (known after apply)<br>        }<br>    }<br><br>  # aws_s3_bucket.web-store-s3 will be created<br>  + resource &quot;aws_s3_bucket&quot; &quot;web-store-s3&quot; {<br>      + acceleration_status         = (known after apply)<br>      + acl                         = (known after apply)<br>      + arn                         = (known after apply)<br>      + bucket                      = &quot;web-store-s3&quot;<br>      + bucket_domain_name          = (known after apply)<br>      + bucket_prefix               = (known after apply)<br>      + bucket_regional_domain_name = (known after apply)<br>      + force_destroy               = false<br>      + hosted_zone_id              = (known after apply)<br>      + id                          = (known after apply)<br>      + object_lock_enabled         = (known after apply)<br>      + policy                      = (known after apply)<br>      + region                      = (known after apply)<br>      + request_payer               = (known after apply)<br>      + tags                        = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + tags_all                    = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + website_domain              = (known after apply)<br>      + website_endpoint            = (known after apply)<br>    }<br><br>  # aws_s3_bucket_policy.s3-backend-policy will be created<br>  + resource &quot;aws_s3_bucket_policy&quot; &quot;s3-backend-policy&quot; {<br>      + bucket = (known after apply)<br>      + id     = (known after apply)<br>      + policy = (known after apply)<br>    }<br><br>  # aws_s3_bucket_versioning.terraform_state will be created<br>  + resource &quot;aws_s3_bucket_versioning&quot; &quot;terraform_state&quot; {<br>      + bucket = (known after apply)<br>      + id     = (known after apply)<br><br>      + versioning_configuration {<br>          + mfa_delete = (known after apply)<br>          + status     = &quot;Enabled&quot;<br>        }<br>    }<br><br>  # aws_security_group.Web-Store-SG will be created<br>  + resource &quot;aws_security_group&quot; &quot;Web-Store-SG&quot; {<br>      + arn                    = (known after apply)<br>      + description            = &quot;Managed by Terraform&quot;<br>      + egress                 = [<br>          + {<br>              + cidr_blocks      = [<br>                  + &quot;0.0.0.0/0&quot;,<br>                ]<br>              + description      = &quot;&quot;<br>              + from_port        = 0<br>              + ipv6_cidr_blocks = []<br>              + prefix_list_ids  = []<br>              + protocol         = &quot;-1&quot;<br>              + security_groups  = []<br>              + self             = false<br>              + to_port          = 0<br>            },<br>        ]<br>      + id                     = (known after apply)<br>      + ingress                = [<br>          + {<br>              + cidr_blocks      = [<br>                  + &quot;0.0.0.0/0&quot;,<br>                ]<br>              + description      = &quot;HTTP&quot;<br>              + from_port        = 80<br>              + ipv6_cidr_blocks = []<br>              + prefix_list_ids  = []<br>              + protocol         = &quot;tcp&quot;<br>              + security_groups  = []<br>              + self             = false<br>              + to_port          = 80<br>            },<br>        ]<br>      + name                   = (known after apply)<br>      + name_prefix            = (known after apply)<br>      + owner_id               = (known after apply)<br>      + revoke_rules_on_delete = false<br>      + tags_all               = (known after apply)<br>      + vpc_id                 = &quot;vpc-05f530a52657d4677&quot;<br>    }<br><br>Plan: 7 to add, 0 to change, 0 to destroy.</pre><p>Great, everything looks good! Now, let’s run <strong>“terraform apply — — auto-approve ”.</strong></p><pre>input:<br><br>terraform apply --auto-approve<br><br>output:<br><br>data.template_file.instances_user_data: Reading...<br>data.template_file.instances_user_data: Read complete after 0s [id=6d08f0bd69fb13bfa5cfc206856a93515fd4946ca3a7713dba2dff86997e7962]<br><br>Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:<br>  + create<br><br>Terraform will perform the following actions:<br><br>  # aws_autoscaling_group.Web-Store-ASG will be created<br>  + resource &quot;aws_autoscaling_group&quot; &quot;Web-Store-ASG&quot; {<br>      + arn                       = (known after apply)<br>      + availability_zones        = (known after apply)<br>      + default_cooldown          = (known after apply)<br>      + desired_capacity          = 2<br>      + force_delete              = false<br>      + force_delete_warm_pool    = false<br>      + health_check_grace_period = 300<br>      + health_check_type         = &quot;ELB&quot;<br>      + id                        = (known after apply)<br>      + max_size                  = 5<br>      + metrics_granularity       = &quot;1Minute&quot;<br>      + min_size                  = 2<br>      + name                      = (known after apply)<br>      + name_prefix               = (known after apply)<br>      + protect_from_scale_in     = false<br>      + service_linked_role_arn   = (known after apply)<br>      + vpc_zone_identifier       = [<br>          + &quot;subnet-0c1fed6313c663cb2&quot;,<br>          + &quot;subnet-0c23be44ab1c5564c&quot;,<br>        ]<br>      + wait_for_capacity_timeout = &quot;10m&quot;<br><br>      + launch_template {<br>          + id      = (known after apply)<br>          + name    = (known after apply)<br>          + version = &quot;$Latest&quot;<br>        }<br>    }<br><br>  # aws_dynamodb_table.s3-db-backend will be created<br>  + resource &quot;aws_dynamodb_table&quot; &quot;s3-db-backend&quot; {<br>      + arn              = (known after apply)<br>      + billing_mode     = &quot;PROVISIONED&quot;<br>      + hash_key         = &quot;LockID&quot;<br>      + id               = (known after apply)<br>      + name             = &quot;s3-db-backend&quot;<br>      + read_capacity    = 1<br>      + stream_arn       = (known after apply)<br>      + stream_label     = (known after apply)<br>      + stream_view_type = (known after apply)<br>      + tags             = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + tags_all         = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + write_capacity   = 1<br><br>      + attribute {<br>          + name = &quot;LockID&quot;<br>          + type = &quot;S&quot;<br>        }<br>    }<br><br>  # aws_launch_template.Web-Store-Template will be created<br>  + resource &quot;aws_launch_template&quot; &quot;Web-Store-Template&quot; {<br>      + arn             = (known after apply)<br>      + default_version = (known after apply)<br>      + id              = (known after apply)<br>      + image_id        = &quot;ami-007855ac798b5175e&quot;<br>      + instance_type   = &quot;t2.micro&quot;<br>      + key_name        = &quot;KeyPair1&quot;<br>      + latest_version  = (known after apply)<br>      + name            = (known after apply)<br>      + name_prefix     = &quot;Web-Store&quot;<br>      + tags            = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + tags_all        = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + user_data       = &quot;IyEvYmluL2Jhc2gKYXB0IHVwZGF0ZSAteQphcHQgaW5zdGFsbCAteSBhcGFjaGUyCmVjaG8gIldlbGNvbWUgdG8gbXkgV2ViLVN0b3JlLUFTRyEiID4gdmFyL3d3dy9odG1sL2luZGV4Lmh0bWwKc3lzdGVtY3RsIGVuYWJsZSBhcGFjaGUyCnN5c3RlbWN0bCBzdGFydCBhcGFjaGUyCg==&quot;<br><br>      + network_interfaces {<br>          + associate_public_ip_address = &quot;true&quot;<br>          + security_groups             = (known after apply)<br>        }<br>    }<br><br>  # aws_s3_bucket.web-store-s3 will be created<br>  + resource &quot;aws_s3_bucket&quot; &quot;web-store-s3&quot; {<br>      + acceleration_status         = (known after apply)<br>      + acl                         = (known after apply)<br>      + arn                         = (known after apply)<br>      + bucket                      = &quot;web-store-s3&quot;<br>      + bucket_domain_name          = (known after apply)<br>      + bucket_prefix               = (known after apply)<br>      + bucket_regional_domain_name = (known after apply)<br>      + force_destroy               = false<br>      + hosted_zone_id              = (known after apply)<br>      + id                          = (known after apply)<br>      + object_lock_enabled         = (known after apply)<br>      + policy                      = (known after apply)<br>      + region                      = (known after apply)<br>      + request_payer               = (known after apply)<br>      + tags                        = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + tags_all                    = {<br>          + &quot;Name&quot;      = &quot;Web-Store&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + website_domain              = (known after apply)<br>      + website_endpoint            = (known after apply)<br>    }<br><br>  # aws_s3_bucket_policy.s3-backend-policy will be created<br>  + resource &quot;aws_s3_bucket_policy&quot; &quot;s3-backend-policy&quot; {<br>      + bucket = (known after apply)<br>      + id     = (known after apply)<br>      + policy = (known after apply)<br>    }<br><br>  # aws_s3_bucket_versioning.terraform_state will be created<br>  + resource &quot;aws_s3_bucket_versioning&quot; &quot;terraform_state&quot; {<br>      + bucket = (known after apply)<br>      + id     = (known after apply)<br><br>      + versioning_configuration {<br>          + mfa_delete = (known after apply)<br>          + status     = &quot;Enabled&quot;<br>        }<br>    }<br><br>  # aws_security_group.Web-Store-SG will be created<br>  + resource &quot;aws_security_group&quot; &quot;Web-Store-SG&quot; {<br>      + arn                    = (known after apply)<br>      + description            = &quot;Managed by Terraform&quot;<br>      + egress                 = [<br>          + {<br>              + cidr_blocks      = [<br>                  + &quot;0.0.0.0/0&quot;,<br>                ]<br>              + description      = &quot;&quot;<br>              + from_port        = 0<br>              + ipv6_cidr_blocks = []<br>              + prefix_list_ids  = []<br>              + protocol         = &quot;-1&quot;<br>              + security_groups  = []<br>              + self             = false<br>              + to_port          = 0<br>            },<br>        ]<br>      + id                     = (known after apply)<br>      + ingress                = [<br>          + {<br>              + cidr_blocks      = [<br>                  + &quot;0.0.0.0/0&quot;,<br>                ]<br>              + description      = &quot;HTTP&quot;<br>              + from_port        = 80<br>              + ipv6_cidr_blocks = []<br>              + prefix_list_ids  = []<br>              + protocol         = &quot;tcp&quot;<br>              + security_groups  = []<br>              + self             = false<br>              + to_port          = 80<br>            },<br>        ]<br>      + name                   = (known after apply)<br>      + name_prefix            = (known after apply)<br>      + owner_id               = (known after apply)<br>      + revoke_rules_on_delete = false<br>      + tags_all               = (known after apply)<br>      + vpc_id                 = &quot;vpc-05f530a52657d4677&quot;<br>    }<br><br>Plan: 7 to add, 0 to change, 0 to destroy.<br>aws_security_group.Web-Store-SG: Creating...<br>aws_dynamodb_table.s3-db-backend: Creating...<br>aws_s3_bucket.web-store-s3: Creating...<br>aws_s3_bucket.web-store-s3: Creation complete after 1s [id=web-store-s3]<br>aws_s3_bucket_versioning.terraform_state: Creating...<br>aws_s3_bucket_policy.s3-backend-policy: Creating...<br>aws_s3_bucket_policy.s3-backend-policy: Creation complete after 0s [id=web-store-s3]<br>aws_security_group.Web-Store-SG: Creation complete after 2s [id=sg-08cbc95d0bfbe1a70]<br>aws_launch_template.Web-Store-Template: Creating...<br>aws_s3_bucket_versioning.terraform_state: Creation complete after 1s [id=web-store-s3]<br>aws_launch_template.Web-Store-Template: Creation complete after 0s [id=lt-05435e178bf138271]<br>aws_autoscaling_group.Web-Store-ASG: Creating...<br>aws_dynamodb_table.s3-db-backend: Creation complete after 6s [id=s3-db-backend]<br>aws_autoscaling_group.Web-Store-ASG: Still creating... [10s elapsed]<br>aws_autoscaling_group.Web-Store-ASG: Still creating... [20s elapsed]<br>aws_autoscaling_group.Web-Store-ASG: Still creating... [30s elapsed]<br>aws_autoscaling_group.Web-Store-ASG: Creation complete after 37s [id=terraform-20230413012954347000000004]<br><br>Apply complete! Resources: 7 added, 0 changed, 0 destroyed.</pre><p>Fantastic, everything was created correctly but it will take a few minutes for it all to completely initialize. After a few minutes, view your running instances in the AWS Console, there should be 2 instances running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lay5Tx4yBM8qRA4qDCQb8Q.png" /></figure><p>Now, put the public IP address of the instances into your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DxyJ2o4Xo42t5H5gfkQRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5w7aJcSPNOOT1mbgcxaEVQ.png" /></figure><p>Perfect! The Apache Web Server was installed correctly and our custom webpage is visible.</p><p>Now, let’s manually terminate an instance and check to make sure a new instance is spun up from our autoscaling group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usP66LZH02WQAzNkNZdJeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHP56I8Hx7GVeeV-imglgA.png" /></figure><p>Fantastic, after a few minutes a new instance is up and running to replace the terminated instance!</p><p>Now, let’s verify the DynamoDB Table was created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9cBAaZ2WBmFsdHFHSyDN0g.png" /></figure><h3>Set S3 Bucket as Remote Backend &amp; Block Public Access</h3><p>Now that the S3 Bucket has been created, let’s set it as our remote backend. To write this code, I will be using the hashicorp/aws documentation about backend type: S3 <a href="https://developer.hashicorp.com/terraform/language/settings/backends/s3">here</a>. To follow best practices regarding S3 Bucket security, let’s block public access to the bucket. To write this code, I will be using the hashicorp/aws documentation aws_s3_bucket_public_access_block <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_public_access_block">here</a>. <strong>(*Note — We couldn’t restrict public access at the time of the bucket creation because we were passing a bucket policy. If we had tried to block public access during the bucket creation, it would caused a restricted access error.)</strong> To avoid changing the <strong>main.tf</strong> file, I have created 2 new files: <strong>s3-backend.tf </strong>and <strong>s3-block-public-access.tf</strong>.</p><pre>s3-backend.tf<br><br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;web-store-s3&quot;<br>    key            = &quot;terraform.tfstate&quot;<br>    region         = &quot;us-east-1&quot;<br>    dynamodb_table = &quot;s3-db-backend&quot;<br>  }<br>}</pre><pre>s3-block-public-access.tf<br><br>#Block Public access to S3 Bucket<br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;block_public_access_s3&quot; {<br>  bucket = aws_s3_bucket.web-store-s3.id<br><br>  block_public_acls       = true<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br>}</pre><p>Now, let’s run it. First, run <strong>“terraform init”</strong> in the same directory to re-initialize Terraform.</p><pre>input:<br><br>terraform init<br><br>output: <br><br>Initializing the backend...<br>Do you want to copy existing state to the new backend?<br>  Pre-existing state was found while migrating the previous &quot;local&quot; backend to the<br>  newly configured &quot;s3&quot; backend. No existing state was found in the newly<br>  configured &quot;s3&quot; backend. Do you want to copy this state to the new &quot;s3&quot;<br>  backend? Enter &quot;yes&quot; to copy and &quot;no&quot; to start with an empty state.<br><br>  Enter a value: yes<br><br><br>Successfully configured the backend &quot;s3&quot;! Terraform will automatically<br>use this backend unless the backend configuration changes.<br><br>Initializing provider plugins...<br>- Reusing previous version of hashicorp/aws from the dependency lock file<br>- Reusing previous version of hashicorp/template from the dependency lock file<br>- Using previously-installed hashicorp/template v2.2.0<br>- Using previously-installed hashicorp/aws v4.62.0<br><br>Terraform has been successfully initialized!<br><br>You may now begin working with Terraform. Try running &quot;terraform plan&quot; to see<br>any changes that are required for your infrastructure. All Terraform commands<br>should now work.</pre><p>Now, let’s run <strong>“terraform apply — — auto-approve ”,</strong></p><pre>input:<br><br>terraform apply --auto-approve<br><br>output:<br><br>data.template_file.instances_user_data: Reading...<br>data.template_file.instances_user_data: Read complete after 0s [id=6d08f0bd69fb13bfa5cfc206856a93515fd4946ca3a7713dba2dff86997e7962]<br>aws_dynamodb_table.s3-db-backend: Refreshing state... [id=s3-db-backend]<br>aws_security_group.Web-Store-SG: Refreshing state... [id=sg-08cbc95d0bfbe1a70]<br>aws_s3_bucket.web-store-s3: Refreshing state... [id=web-store-s3]<br>aws_launch_template.Web-Store-Template: Refreshing state... [id=lt-05435e178bf138271]<br>aws_autoscaling_group.Web-Store-ASG: Refreshing state... [id=terraform-20230413012954347000000004]<br>aws_s3_bucket_policy.s3-backend-policy: Refreshing state... [id=web-store-s3]<br>aws_s3_bucket_versioning.terraform_state: Refreshing state... [id=web-store-s3]<br><br>Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:<br>  + create<br><br>Terraform will perform the following actions:<br><br>  # aws_s3_bucket_public_access_block.block_public_access_s3 will be created<br>  + resource &quot;aws_s3_bucket_public_access_block&quot; &quot;block_public_access_s3&quot; {<br>      + block_public_acls       = true<br>      + block_public_policy     = true<br>      + bucket                  = &quot;web-store-s3&quot;<br>      + id                      = (known after apply)<br>      + ignore_public_acls      = true<br>      + restrict_public_buckets = true<br>    }<br><br>Plan: 1 to add, 0 to change, 0 to destroy.<br>aws_s3_bucket_public_access_block.block_public_access_s3: Creating...<br>aws_s3_bucket_public_access_block.block_public_access_s3: Creation complete after 1s [id=web-store-s3]<br><br>Apply complete! Resources: 1 added, 0 changed, 0 destroyed.</pre><p>Finally, let’s verify that our S3 Bucket has our custom policy and blocks public access. We can also check to see that a <strong>terraform.tfstate </strong>file was uploaded to the bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*0mlT8FxhUu1dYbinIQfyFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKEvzLaeRVEm7UcY_KO32A.png" /></figure><p>Congratulations, we have successfully used Terraform create an autoscaling group using a launch template to launch EC2 Instances in AWS that are bootstrapped with an Apache Web Server. And created an S3 bucket that has a custom policy, blocks public access, and is used as a remote backend with an AWS DynamoDB Table.</p><h3>GitHub Link:</h3><p><a href="https://github.com/radcock757/Terraform/tree/main/terraform-wk21">https://github.com/radcock757/Terraform/tree/main/terraform-wk21</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*Kg-pJIyvZ5AheTsd5L10DQ.gif" /><figcaption>Congratulations!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccd3bd6da997" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform: Launch an EC2 Instance Bootstrapped with Jenkins and Create an S3]]></title>
            <link>https://awstip.com/terraform-launch-an-ec2-instance-bootstrapped-with-jenkins-and-create-an-s3-2ecb4b202485?source=rss-8822cf9b0f81------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ecb4b202485</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[visual-studio]]></category>
            <dc:creator><![CDATA[Ryan Adcock]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 14:30:08 GMT</pubDate>
            <atom:updated>2023-04-13T03:36:09.320Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I am going to show you step-by-step how to use Terraform to launch an EC2 Instance in AWS that is bootstrapped with Jenkins and create an S3 bucket that blocks public access.</p><p><strong>Prerequisites:</strong></p><ul><li>Basic understanding and knowledge of using the CLI on a Linux OS</li><li>An AWS account</li><li>Access to an IDE (Cloud 9, Visual Studio, etc.)</li></ul><h3><strong>Scenario</strong></h3><p>Your team would like to start using Jenkins as their CI/CD tool to create pipelines for DevOps projects. They need you to create the Jenkins server using Terraform so that it can be used in other environments and so that changes to the environment are better tracked. (Hardcode everything into a single main.tf monolith file.)</p><h3>Objectives</h3><ol><li>Deploy an EC2 Instances in your Default VPC.</li><li>Bootstrap the EC2 instance with a script that will install and start Jenkins. Review the official Jenkins Documentation for more information: <a href="https://www.jenkins.io/doc/book/installing/linux/">https://www.jenkins.io/doc/book/installing/linux/</a></li><li>Create and assign a Security Group to the Jenkins EC2 that allows traffic on port 22 from your IP address and allows traffic from port 8080.</li><li>Create a S3 bucket for your Jenkins Artifacts that is NOT open to the public.</li><li>Verify that you can reach your Jenkins install via port 8080 in your browser.</li></ol><h3>What is Jenkins?</h3><p>Jenkins is an open source automation server that provides tons of plugins to support building, deploying, and automating your projects. It is a fantastic CI/CD tool to create and manage pipelines for DevOps projects. To learn more about Jenkins, head on over to their website: (<a href="https://www.jenkins.io/">https://www.jenkins.io/</a>)</p><h3>Compile main.tf code</h3><p>Let’s start by creating our <strong>main.tf </strong>file in a new directory called <strong>terraform-wk20</strong> and use <strong>Visual Studio Code.</strong></p><pre>mkdir terraform-wk20<br>code main.tf</pre><p>Now, since we want to utilize AWS services we need to set the correct required providers. For more information regarding this code, click <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">here</a>. Enter this code into the <strong>main.tf </strong>file:</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br># Configure the AWS Provider<br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}</pre><p>I am going to be using my default VPC so there is no need to write code to create a new VPC. But we will need the ID of the default VPC, so head on over to your AWS console to get the ID of the default VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qMi1vjELmd20m6oBYzVFCQ.jpeg" /></figure><p>Let’s create our security group that will be assigned to our EC2 instance. To get started, click <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group">here</a> to refer to the hashicorp/aws documentation about security groups. We want the security group allow traffic on port 22 from my IP address and allows traffic from port 8080 (the default port for Jenkins). By default AWS creates an “Allow All” egress rule however, Terraform will delete this default so we need to recreate it using the “egress” block. Enter the following code into the <strong>main.tf</strong> file:</p><pre>#Create the Security Group<br>resource &quot;aws_security_group&quot; &quot;Jenkins_sg&quot; {<br>  vpc_id = &quot;vpc-05f530a52657d4677&quot;<br><br>  ingress {<br>    description = &quot;HTTP&quot;<br>    from_port   = 8080<br>    to_port     = 8080<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  #Allow access from my IP address via SSH<br>  ingress {<br>    description = &quot;SSH&quot;<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;70.160.118.0/24&quot;]<br>  }<br><br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><p>Now, we need to create our EC2 instance. To write this code, I will be using the hashicorp/aws documentation about aws_instance <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance">here</a> and the instructions for how to install Jenkins on Linux <a href="https://www.jenkins.io/doc/book/installing/linux/">here</a>. For the instance ami, refer to the AWS console for the Ubuntu ami. Enter the following code into the <strong>main.tf</strong> file:</p><pre># Create EC2 Instance<br>resource &quot;aws_instance&quot; &quot;Jenkins_EC2&quot; {<br>  ami                    = &quot;ami-007855ac798b5175e&quot;<br>  instance_type          = &quot;t2.micro&quot;<br>  key_name               = &quot;KeyPair1&quot;<br>  vpc_security_group_ids = [aws_security_group.Jenkins_sg.id]<br>  user_data              = &lt;&lt;-EOF<br>#!/bin/bash<br>sudo wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key |sudo gpg --dearmor -o /usr/share/keyrings/jenkins.gpg<br>sudo sh -c &#39;echo deb [signed-by=/usr/share/keyrings/jenkins.gpg] http://pkg.jenkins.io/debian-stable binary/ &gt; /etc/apt/sources.list.d/jenkins.list&#39;<br>curl -fsSL https://pkg.jenkins.io/debian/jenkins.io-2023.key | sudo tee /usr/share/keyrings/jenkins-keyring.asc &gt; /dev/null<br>echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] https://pkg.jenkins.io/debian binary/ | sudo tee /etc/apt/sources.list.d/jenkins.list &gt; /dev/null<br>sudo apt update -y<br>sudo apt install openjdk-11-jdk -y<br>sudo apt install jenkins -y<br>sudo systemctl start jenkins.service<br>EOF<br><br>  tags = {<br>    Name      = &quot;Jenkins&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}</pre><p>In the above code, you will see <strong>key_name = “KeyPair1”</strong>, that is a key pair that I have previously used and it will allow me to SSH into the instance after creation from my IP address only.</p><p>Finally, we need to create our S3 Bucket and restrict public access to the S3 bucket. To write this code, I will be using the hashicorp/aws documentation about aws_s3_bucket <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket">here</a> and aws_s3_bucket_public_access_block <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_public_access_block">here</a>. Enter the following code into the <strong>main.tf</strong> file:</p><pre>#Create S3 Bucket<br>resource &quot;aws_s3_bucket&quot; &quot;ryana-jenkins-artifacts-s3&quot; {<br>  bucket = &quot;ryana-jenkins-artifacts-s3&quot;<br><br>  tags = {<br>    Name      = &quot;Jenkins&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}<br><br>#Block Public access to S3 Bucket<br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;block_public_access_s3&quot; {<br>  bucket = aws_s3_bucket.ryana-jenkins-artifacts-s3.id<br><br>  block_public_acls       = true<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br>}</pre><p>Here is the final version of the complete <strong>main.tf</strong> file.</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br># Configure the AWS Provider<br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}<br><br>#Create the Security Group<br>resource &quot;aws_security_group&quot; &quot;Jenkins_sg&quot; {<br>  vpc_id = &quot;vpc-05f530a52657d4677&quot;<br><br>  ingress {<br>    description = &quot;HTTP&quot;<br>    from_port   = 8080<br>    to_port     = 8080<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  #Allow access from my IP address via SSH<br>  ingress {<br>    description = &quot;SSH&quot;<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;70.160.118.0/24&quot;]<br>  }<br><br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}<br><br># Create EC2 Instance<br>resource &quot;aws_instance&quot; &quot;Jenkins_EC2&quot; {<br>  ami                    = &quot;ami-007855ac798b5175e&quot;<br>  instance_type          = &quot;t2.micro&quot;<br>  key_name               = &quot;KeyPair1&quot;<br>  vpc_security_group_ids = [aws_security_group.Jenkins_sg.id]<br>  user_data              = &lt;&lt;-EOF<br>#!/bin/bash<br>sudo wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key |sudo gpg --dearmor -o /usr/share/keyrings/jenkins.gpg<br>sudo sh -c &#39;echo deb [signed-by=/usr/share/keyrings/jenkins.gpg] http://pkg.jenkins.io/debian-stable binary/ &gt; /etc/apt/sources.list.d/jenkins.list&#39;<br>curl -fsSL https://pkg.jenkins.io/debian/jenkins.io-2023.key | sudo tee /usr/share/keyrings/jenkins-keyring.asc &gt; /dev/null<br>echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] https://pkg.jenkins.io/debian binary/ | sudo tee /etc/apt/sources.list.d/jenkins.list &gt; /dev/null<br>sudo apt update -y<br>sudo apt install openjdk-11-jdk -y<br>sudo apt install jenkins -y<br>sudo systemctl start jenkins.service<br>EOF<br><br>  tags = {<br>    Name      = &quot;Jenkins&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}<br><br>#Create S3 Bucket<br>resource &quot;aws_s3_bucket&quot; &quot;ryana-jenkins-artifacts-s3&quot; {<br>  bucket = &quot;ryana-jenkins-artifacts-s3&quot;<br><br>  tags = {<br>    Name      = &quot;Jenkins&quot;<br>    Terraform = &quot;true&quot;<br>  }<br>}<br><br>#Block Public access to S3 Bucket<br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;block_public_access_s3&quot; {<br>  bucket = aws_s3_bucket.ryana-jenkins-artifacts-s3.id<br><br>  block_public_acls       = true<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br>}<br><br>resource &quot;aws_s3_bucket_acl&quot; &quot;no-public-access&quot; {<br>  bucket = aws_s3_bucket.ryana-jenkins-artifacts-s3.id<br>  acl    = &quot;private&quot;<br>}<br><br>#Print EC2 instance public IP address<br>output &quot;instance_public_ip&quot; {<br>  description = &quot;Public IP address of Jenkins_EC2 instance&quot;<br>  value       = [aws_instance.Jenkins_EC2.public_ip]<br>}</pre><p>I also added an output to print the public IP address so that I can verify Jenkins is accessible on port 8080 in my browser.</p><h3>Run the code!</h3><p>We have created all the code for our <strong>main.tf</strong>, now let’s run it. First, run <strong>“terraform init”</strong> in the directory of the <strong>main.tf</strong> file to initialize Terraform. Next, let’s run <strong>“terraform plan”</strong> to ensure there are no errors in our code. Here is how the output should look:</p><pre>terraform plan<br><br>Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:<br>  + create<br><br>Terraform will perform the following actions:<br><br>  # aws_instance.Jenkins_EC2 will be created<br>  + resource &quot;aws_instance&quot; &quot;Jenkins_EC2&quot; {<br>      + ami                                  = &quot;ami-007855ac798b5175e&quot;<br>      + arn                                  = (known after apply)<br>      + associate_public_ip_address          = (known after apply)<br>      + availability_zone                    = (known after apply)<br>      + cpu_core_count                       = (known after apply)<br>      + cpu_threads_per_core                 = (known after apply)<br>      + disable_api_stop                     = (known after apply)<br>      + disable_api_termination              = (known after apply)<br>      + ebs_optimized                        = (known after apply)<br>      + get_password_data                    = false<br>      + host_id                              = (known after apply)<br>      + host_resource_group_arn              = (known after apply)<br>      + iam_instance_profile                 = (known after apply)<br>      + id                                   = (known after apply)<br>      + instance_initiated_shutdown_behavior = (known after apply)<br>      + instance_state                       = (known after apply)<br>      + instance_type                        = &quot;t2.micro&quot;<br>      + ipv6_address_count                   = (known after apply)<br>      + ipv6_addresses                       = (known after apply)<br>      + key_name                             = &quot;KeyPair1&quot;<br>      + monitoring                           = (known after apply)<br>      + outpost_arn                          = (known after apply)<br>      + password_data                        = (known after apply)<br>      + placement_group                      = (known after apply)<br>      + placement_partition_number           = (known after apply)<br>      + primary_network_interface_id         = (known after apply)<br>      + private_dns                          = (known after apply)<br>      + private_ip                           = (known after apply)<br>      + public_dns                           = (known after apply)<br>      + public_ip                            = (known after apply)<br>      + secondary_private_ips                = (known after apply)<br>      + security_groups                      = (known after apply)<br>      + source_dest_check                    = true<br>      + subnet_id                            = (known after apply)<br>      + tags                                 = {<br>          + &quot;Name&quot;      = &quot;Jenkins&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + tags_all                             = {<br>          + &quot;Name&quot;      = &quot;Jenkins&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + tenancy                              = (known after apply)<br>      + user_data                            = &quot;291c8069b70bc4595ac3243a2ba35d17f604b28d&quot;<br>      + user_data_base64                     = (known after apply)<br>      + user_data_replace_on_change          = false<br>      + vpc_security_group_ids               = (known after apply)<br>    }<br><br>  # aws_s3_bucket.ryana-jenkins-artifacts-s3 will be created<br>  + resource &quot;aws_s3_bucket&quot; &quot;ryana-jenkins-artifacts-s3&quot; {<br>      + acceleration_status         = (known after apply)<br>      + acl                         = (known after apply)<br>      + arn                         = (known after apply)<br>      + bucket                      = &quot;ryana-jenkins-artifacts-s3&quot;<br>      + bucket_domain_name          = (known after apply)<br>      + bucket_prefix               = (known after apply)<br>      + bucket_regional_domain_name = (known after apply)<br>      + force_destroy               = false<br>      + hosted_zone_id              = (known after apply)<br>      + id                          = (known after apply)<br>      + object_lock_enabled         = (known after apply)<br>      + policy                      = (known after apply)<br>      + region                      = (known after apply)<br>      + request_payer               = (known after apply)<br>      + tags                        = {<br>          + &quot;Name&quot;      = &quot;Jenkins&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + tags_all                    = {<br>          + &quot;Name&quot;      = &quot;Jenkins&quot;<br>          + &quot;Terraform&quot; = &quot;true&quot;<br>        }<br>      + website_domain              = (known after apply)<br>      + website_endpoint            = (known after apply)<br>    }<br><br>  # aws_s3_bucket_public_access_block.block_public_access_s3 will be created<br>  + resource &quot;aws_s3_bucket_public_access_block&quot; &quot;block_public_access_s3&quot; {<br>      + block_public_acls       = true <br>      + block_public_policy     = true <br>      + bucket                  = (known after apply)<br>      + id                      = (known after apply)<br>      + ignore_public_acls      = true <br>      + restrict_public_buckets = true<br>    }<br><br>  # aws_security_group.Jenkins_sg will be created<br>  + resource &quot;aws_security_group&quot; &quot;Jenkins_sg&quot; {<br>      + arn                    = (known after apply)<br>      + description            = &quot;Managed by Terraform&quot;<br>      + egress                 = [<br>          + {<br>              + cidr_blocks      = [<br>                  + &quot;0.0.0.0/0&quot;,<br>                ]<br>              + description      = &quot;&quot;<br>              + from_port        = 0<br>              + ipv6_cidr_blocks = []<br>              + prefix_list_ids  = []<br>              + protocol         = &quot;-1&quot;<br>              + security_groups  = []<br>              + self             = false<br>              + to_port          = 0<br>            },<br>        ]<br>      + id                     = (known after apply)<br>      + ingress                = [<br>          + {<br>              + cidr_blocks      = [<br>                  + &quot;0.0.0.0/0&quot;,<br>                ]<br>              + description      = &quot;HTTP&quot;<br>              + from_port        = 8080<br>              + ipv6_cidr_blocks = []<br>              + prefix_list_ids  = []<br>              + protocol         = &quot;tcp&quot;<br>              + security_groups  = []<br>              + self             = false<br>              + to_port          = 8080<br>            },<br>          + {<br>              + cidr_blocks      = [<br>                  + &quot;70.160.118.0/24&quot;,<br>                ]<br>              + description      = &quot;SSH&quot;<br>              + from_port        = 22<br>              + ipv6_cidr_blocks = []<br>              + prefix_list_ids  = []<br>              + protocol         = &quot;tcp&quot;<br>              + security_groups  = []<br>              + self             = false<br>              + to_port          = 22<br>            },<br>        ]<br>      + name                   = (known after apply)<br>      + name_prefix            = (known after apply)<br>      + owner_id               = (known after apply)<br>      + revoke_rules_on_delete = false<br>      + tags_all               = (known after apply)<br>      + vpc_id                 = &quot;vpc-05f530a52657d4677&quot;<br>    }<br><br>Plan: 4 to add, 0 to change, 0 to destroy.<br><br>Changes to Outputs:<br>  + instance_public_ip = [<br>      + null,<br>    ]</pre><p>Great, everything looks good! Now, let’s run <strong>“terraform apply — —auto-approve ”, </strong>your output should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoVd7Wb7BBZR0LG2Nu1mcg.png" /></figure><p>Fantastic, everything was created correctly but it will take a few minutes for it all to completely initialize. After a few minutes, input the IP address followed by <strong>:8080 </strong>and you should see the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJuaUvA82IP47yGDc4Aw1g.png" /></figure><p>Fantastic, that’s what we expected to see. Now, let’s check to ensure the S3 bucket we created isn’t accessible to the public.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beZ1RF1vDvJeNPFv97g7zQ.png" /></figure><p>Congratulations, we have successfully used Terraform to launch an instance bootstrapped with Jenkins and created an S3 bucket that does not have public access!</p><h3><strong>GitHub Link:</strong></h3><p><a href="https://github.com/radcock757/Terraform/blob/main/terraform-wk20/main.tf">https://github.com/radcock757/Terraform/blob/main/terraform-wk20/main.tf</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LqqALymhhTT7HMxrPVX-qA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ecb4b202485" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/terraform-launch-an-ec2-instance-bootstrapped-with-jenkins-and-create-an-s3-2ecb4b202485">Terraform: Launch an EC2 Instance Bootstrapped with Jenkins and Create an S3</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes: Creating deployments and service with a yaml file]]></title>
            <link>https://medium.com/@ryan.a.adcock/kubernetes-creating-deployments-and-service-with-a-yaml-file-f2df8e4661d3?source=rss-8822cf9b0f81------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2df8e4661d3</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[node-port]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[kubernetes-deployment]]></category>
            <category><![CDATA[kubernetes-service]]></category>
            <dc:creator><![CDATA[Ryan Adcock]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 15:21:47 GMT</pubDate>
            <atom:updated>2023-03-23T15:21:47.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BUo9SV9idWAKP85w8L3Eg.png" /></figure><p>In this article, I will be showing you step-by-step how to create two Kubernetes deployments and a service using a yaml file.</p><h3>Objectives:</h3><ul><li>Spin up two deployments. One deployment contains 2 pods running the nginx image. Include a ConfigMap that points to a custom index.html page that contains the line “This is Deployment One”. The other deployment contains 2 pods running the nginx image. Include a ConfigMap that points to a custom index.html page that contains the line “This is Deployment Two”.</li><li>Create a service that points to both deployments. You should be able to both deployments using the same ip address and port number.</li><li>Use the curl command to validate that you eventually see the index.html pages from both Deployment 1 and Deployment 2.</li></ul><h3><strong>Setup/Install kubectl</strong></h3><p>Be sure that you have kubectl installed on your linux os by running the following command:</p><pre>kubectl version --client</pre><p>If you get an error message, use this link for instructions on how to install kubectl (<a href="https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/">instructions</a>). Also, be sure to have your Docker Desktop running.</p><h3>Create Custom index.html file with ConfigMap</h3><p>To begin, use the vim command to open a new file that will become our custom index.html file using ConfigMap for our nginx images in the Kubernetes deployments (we will create two files, one for each deployment). Save the files as <strong>“index-html-deployment1.yaml”</strong>, and enter the code below:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: index-html-configmap1<br>  namespace: default<br>data:<br>  index.html: |<br>    &lt;html&gt;<br>    &lt;h1&gt;Hi! This is Deployment 1! &lt;/h1&gt;<br>    &lt;/html</pre><p>We then need to create the ConfigMap by using this file with the <strong>kubectl apply </strong>command. Run the following:</p><pre>kubectl apply -f index-html-deployment1.yaml</pre><p>Here’s how your output should look:</p><pre>output: configmap/index-html-configmap created</pre><p>Now repeat the process and change the code to Deployment 2.</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: index-html-configmap2<br>  namespace: default<br>data:<br>  index.html: |<br>    &lt;html&gt;<br>    &lt;h1&gt;Hi! This is Deployment 2! &lt;/h1&gt;<br>    &lt;/html</pre><pre>kubectl apply -f index-html-deployment2.yaml</pre><p>Great! We’ve created our ConfigMap’s for our custom index.html pages for our nginx servers that will be in our Kubernetes deployments.</p><h3>Create Deployments &amp; Service</h3><p>To begin, use the vim command to open a new file that will become our yaml file for our Kubernetes deployment and let’s give the file this name, <strong>nginx-2deployments-service.yaml</strong>. In Kubernetes, this yaml file is called a <strong>“manifest”</strong>. We will use this <strong>manifest</strong> to create the 2 deployments and the service. Use the code below in your manifest. Each of the deployments and service will be separated by 3 dashes ( — — — ).</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment1<br>  labels:<br>    app: nginx<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>      - name: nginx<br>        image: nginx:latest<br>        ports:<br>        - containerPort: 80<br>        volumeMounts:<br>            - name: nginx-index-file<br>              mountPath: /usr/share/nginx/html/index.html<br>              subPath: index.html<br>      volumes:<br>        - name: nginx-index-file<br>          configMap:<br>            name: index-html-configmap1<br><br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment2<br>  labels:<br>    app: nginx<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>      - name: nginx<br>        image: nginx:latest<br>        ports:<br>        - containerPort: 80<br>        volumeMounts:<br>            - name: nginx-index-file<br>              mountPath: /usr/share/nginx/html/index.html<br>              subPath: index.html<br>      volumes:<br>        - name: nginx-index-file<br>          configMap:<br>            name: index-html-configmap2<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nginx-service<br>spec:<br>  type: NodePort<br>  selector:<br>    app: nginx<br>  ports:<br>  - port: 80<br>    nodePort: 30052</pre><p>Let’s breakdown the code for our deployments and our service. Both of our deployments will be running the latest nginx image and we are adding a volume mount named <strong>nginx-index-file, </strong>including the <strong>mountPath</strong>, and a volume named <strong>nginx-index-file</strong> and mapping the configmap we created earlier. For the service, we are using a <strong>NodePort</strong>, which builds on top of the ClusterIP Service and provides a way to expose a group of Pods to the outside world. <strong>NodePorts</strong> can range from 30000–32767. We have set the <strong>NodePort</strong> to 30052.</p><p>Now that we have our manifest completed with both deployments and our service, let’s run it by using the following command:</p><pre>kubebctl apply -f nginx-2deployments-service.yaml</pre><p>Here is the output of this command:</p><pre>output:<br>deployment.apps/nginx-deployment1 created<br>deployment.apps/nginx-deployment2 created<br>service/nginx-service created</pre><p>And we can verify the creation of by running:</p><pre>kubectl get all</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sk-kHiywVEfeiKV5h6pckw.png" /></figure><p>You can see we have 2 deployments with 2 pods each and we have our service. Now let’s check to see if our custom index file worked and that both deployments are reached from the nodeport. We will need to run the following command a few times to see it switch between deployments. Run:</p><pre>curl localhost:30052</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XaAS-Ayme-Es6azoYc0DWg.png" /></figure><p>We can also go to our browser and see the same thing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quHVUByy7YyNXcz5FHd6rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YL47cpjLyHeVJmqB4pWhQ.png" /></figure><p>Congratulations! We have successfully created a <strong>manifest</strong> that created 2 deployments with custom nginx index.html files and a service that points to those deployments. To clean up run the following commands:</p><pre>kubectl delete deployment nginx-deployment1 nginx-deployment2<br>kubectl delete service nginx-service</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2df8e4661d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Docker Swarm in AWS]]></title>
            <link>https://medium.com/@ryan.a.adcock/working-with-docker-swarm-in-aws-e0b29de7f19f?source=rss-8822cf9b0f81------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0b29de7f19f</guid>
            <category><![CDATA[docker-swarm]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Ryan Adcock]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 05:22:55 GMT</pubDate>
            <atom:updated>2023-03-13T05:22:55.818Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*0e5RxZAo9VBqu-_UOLabQA.png" /></figure><p>In this step-by-step article, I will be walking you through the basics of docker swarm with 1 manager node and 3 worker nodes.</p><h3>Prerequisites:</h3><p>You should have a basic understanding of the following concepts:</p><ul><li><a href="https://hub.docker.com/">Docker</a></li><li>Linux CLI</li><li>AWS services (i.e. EC2 instances, security group, etc.)</li></ul><h3>Objectives:</h3><p>Using AWS, create a Docker Swarm that consists of one manager and three worker nodes.</p><p>Verify the cluster is working by deploying the following tiered architecture:</p><ul><li>a service based on the Redis docker image with 4 replicas</li><li>a service based on the Apache docker image with 10 replicas</li><li>a service based on the Postgres docker image with 1 replica</li></ul><h3>Swarm Setup</h3><p>In order to accomplish our objectives, we will first need to spin up 4 instances (1 will be a manager and 3 will be workers). Be sure to update the OS on startup of the instances. I also updated the names of each instance in the AWS console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWRkloasR6jjg-Jy5K7EyA.png" /></figure><p>Next, we will need to update the inbound rules on the security group for the instances in order to open specific ports so we can use Docker properly (<a href="https://docs.docker.com/engine/swarm/swarm-tutorial/">Docker Documentation</a>). According to the documentation, we will need to add the following to the inbound rules:</p><ul><li><strong>TCP port 2377</strong> for cluster management communications</li><li><strong>TCP</strong> and <strong>UDP port 7946</strong> for communication among nodes</li><li><strong>UDP port 4789</strong> for overlay network traffic</li></ul><p>Now, select one instance to be the manager and SSH into that instance, I’ll be using <strong>Docker_Swarm</strong> as my manager instance. Once inside the instance run the following commands to install docker and then enable and start docker.</p><pre>sudo yum install docker<br>sudo systemctl enable docker<br>sudo systemctl start docker</pre><p>Next, we need to add our user to the <strong>docker </strong>group in each instance This will help us avoid permissions errors when we go to join the swarm (For futher documentation of this command, read <a href="https://dhananjay4058.medium.com/what-does-sudo-usermod-a-g-group-user-do-on-linux-b1ab7ffbba9c#:~:text=sudo%20usermod%20%2Da%20%2DG%20docker%20%24USER&amp;text=sudo%20means%3A%20Run%20this%20command,our%20example%20%E2%80%93%20see%20below).">here</a>).</p><pre>sudo usermod -aG docker $USER</pre><p>Next, we want to start a docker swarm. We will need to run the following command with the instance’s IP address:</p><pre>sudo docker swarm init --advertise-addr &lt;IP address&gt;</pre><p>The output of this command will also provide us with the join token command for the 3 worker nodes (<em>tip: </em>be sure to save this command in a word doc file so you can re-use it easily). Here is my join token command:</p><pre>sudo docker swarm join --token SWMTKN-1-5znsl24tj6ad4adtv1ehsjowrrwvyyx8ogzbqpof392i4yho9w-4g9ps9aeb2kgq3ccrhldn3epi 172.31.48.28:2377</pre><p>We’ve successfully configured our manager node, next, we need to SSH into the remaining 3 instances and run the following commands:</p><pre>sudo yum install docker -y<br>sudo systemctl enable docker<br>sudo systemctl start docker<br>sudo usermod -aG docker $USER<br>sudo docker swarm join --token SWMTKN-1-5znsl24tj6ad4adtv1ehsjowrrwvyyx8ogzbqpof392i4yho9w-4g9ps9aeb2kgq3ccrhldn3epi 172.31.48.28:2377</pre><p>You should receive and output that says,<strong> “This node joined a swarm as a worker.”</strong> Fantastic! Our swarm is ready for services!</p><h3>Starting Swarm Services</h3><p>We’ve got our swarm started and added all of our workers, now, let’s deploy our desired services. Docker swarm had some amazing features, one of which is its ability to auto-load balance the deployment of our services across our 4 nodes.</p><p>Let’s start by deploying the Redis image. We’ll start by navigating over to <a href="https://hub.docker.com/_/redis">https://hub.docker.com/_/redis</a> to check for a recent Redis image and any necessary commands. I’ll be using <strong>redis:7.0.9</strong>. To deloy our Redis image with 4 replicas we will need to run the following command:</p><pre>sudo docker service create --replicas 4 --name my-redis redis:7.0.9</pre><p>And then to verify that the service has been launched, run the following command:</p><pre>sudo docker service ls</pre><p>Here’s how your output should look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6n2FcK0mmAsf6g9iH9dSQ.png" /></figure><p>And if we wanted to see which nodes the service is running on we could run the following command:</p><pre>sudo docker service ps my-redis</pre><p>Here’s how your output should look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pCao3qiObM1kJkeB16oNQ.png" /></figure><p>As you can see, the 4 services have been spread across the 4 nodes.</p><p>Next, we’ll deploy the apache image, first, let’s take a look at <a href="https://hub.docker.com/_/httpd">https://hub.docker.com/_/httpd</a> to get our image version. I’ll be using <strong>httpd:2.4.56</strong>. To deloy our Apache image with 10 replicas we will need to run the following command:</p><pre>sudo docker service create --replicas 10 --name my-apache httpd:2.4.56</pre><p>Then we can run the following command to make sure it deployed properly:</p><pre>sudo docker service ps my-apache</pre><p>Here’s how your output should look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NChkPC9dHkZP-whbYSjdPA.png" /></figure><p>Great, let’s deploy the last service, <strong>Postgres.</strong> First let’s do some research at <a href="https://hub.docker.com/_/postgres">https://hub.docker.com/_/postgres</a> to see an image version and how to run this image. I’ll be using <strong>postgres:15.2</strong> and you will also notice that it requires a password, To deploy, run the following command:</p><pre>sudo docker service create --replicas 1 --name my-SQL -e POSTGRES_PASSWORD=mypassword postgres:15.2</pre><p>Then we can run the following command to make sure it deployed properly:</p><pre>sudo docker service ps my-SQL</pre><p>Here’s how your output should look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGED05mMvu5mn_aWrBvirg.png" /></figure><p>Perfect, we have deployed our Postgres! As a final check, let’s take a look at all of the services we deployed and check to make sure they have all of replicas needed, run:</p><pre>sudo docker service ls</pre><p>Here’s how your output should look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5dD_NApnrPQpO9oHtR6oA.png" /></figure><p>Congratulations! You have successfully created your first Docker Swarm!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*K-Lp5lBH91477h7n0lN-HQ.gif" /><figcaption>Leo is impressed!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0b29de7f19f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker: Create a custom image, Create Containers and bind mounts]]></title>
            <link>https://medium.com/@ryan.a.adcock/docker-create-a-custom-image-create-containers-and-bind-mounts-37d496b164f3?source=rss-8822cf9b0f81------2</link>
            <guid isPermaLink="false">https://medium.com/p/37d496b164f3</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Ryan Adcock]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 22:04:21 GMT</pubDate>
            <atom:updated>2023-03-06T22:04:21.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*OE8yX-3CCSOS5Rf34BoYuw.jpeg" /></figure><h3>Objectives:</h3><ul><li>Build docker file for Boto3 / Python</li><li>Use the Ubuntu official image on Dockerhub</li><li>Download any three repos to local host</li><li>Create three containers (* Each container should have a bind mount to one of the repo directories)</li><li>Log into each container and verify access to each repo directory</li></ul><h3>Getting Started</h3><p>To start, I created a new repository in my GitHub account, called <strong>Docker</strong>, and then cloned that new repository to my local machine using the <strong>git clone</strong> command with the repository url. Next, I made a new directory inside the my Docker repo called <strong>“Docker-Project”</strong>, which is where we will store the files for this project.</p><h3>Build Docker file</h3><p>Now lets create and build our docker file, let’s start by creating our docker file called <strong>“Dockerfile”</strong>, enter</p><pre>vim Dockerfile</pre><p>Next, let’s head over to hub.docker.com and look up the supported Ubuntu images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOYvfnkurJ_s1fB9LRXVuA.png" /></figure><p>Let’s choose the <strong>Ubuntu 22.04 </strong>build for our dockerfile. It’s best to use a specific build instead of <strong>latest</strong> to prevent automatic updates that would change the image version. Here’s how we want our finished <strong>Dockerfile</strong> to look:</p><pre>FROM ubuntu:22.04<br><br>RUN apt-get update<br><br>RUN apt-get -y install python3-pip \<br>    &amp;&amp; pip install boto3</pre><p>Great, we’ve got our dockerfile setup, now, let’s build the image. Use the following command to build the image:</p><pre>docker build -t ryanadcock/ubuntu.22.04 .</pre><p>The output should look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*lm7lyvoMiHot5R45oMF2Ng.png" /></figure><p>And we can run <strong>docker image ls</strong> to confirm the image has been built:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*SmvNjdPf1jVgoGapCyZCBA.png" /></figure><p>Perfect, we have created our image!</p><h3>Download any 3 repos from GitHub</h3><p>For my 3 repos to clone, I am going to be choosing 3 repos from Bret Fisher’s GitHub account (<a href="https://github.com/BretFisher?tab=repositories">https://github.com/BretFisher?tab=repositories</a>). Run <strong>git clone &lt;repo URL&gt;</strong> for 3 repos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*vU0TvBc3SYUhjleB85Pn3Q.png" /></figure><p>Now run <strong>ls</strong>, to confirm the repos have been cloned and show up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*dH9GyFDTCrYcqRQD8V4Gtg.png" /></figure><p>Great, we have sucessfully cloned the 3 repos.</p><h3>Build 3 Containers (* with bind mounts to a repo)</h3><p>Let’s build our containers! To do this we will be using the <strong>docker container run</strong> command with some additional command options. Those options are<br>--<strong>name </strong>to name the container, <strong>-v </strong>to bind mount a volume (which will be the file location or path to the desired repo on our local machine), <strong>-d</strong> to run the container in the background and print the container ID, and <strong>-t</strong> to allocate a pseudo-TTY (let’s open a terminal inside the container). Let’s work on getting the paths we will need for our 3 repos. To do this we will use the following command:</p><pre>find $(pwd) -name &lt;directory name&gt;<br>find $(pwd) -name awesome-swarm<br>find $(pwd) -name docker-build-workflow<br>find $(pwd) -name docker-mastery-for-nodejs<br></pre><p>Keep these close, as we will need their respective paths in the next step.</p><p>We will call the first container <strong>Container1</strong>. Run:</p><pre>docker container run -d -t --name &lt;name&gt; -v &lt;repo path&gt; &lt;image name&gt;<br>docker container run -d -t --name Container1 -v /home/radcock757/Docker/Docker-Project/awesome-swarm:/awesome-swarm ryanadcock/ubuntu22.04</pre><p>Repeat 2 more times for the other to repos:</p><pre>docker container run -d -t --name Container2 -v /home/radcock757/Docker/Docker-Project/docker-build-workflow:/docker-build-workflow ryanadcock/ubuntu22.04<br>docker container run -d -t --name Container3 -v /home/radcock757/Docker/Docker-Project/docker-mastery-for-nodejs:/docker-mastery-for-nodejs ryanadcock/ubuntu22.04</pre><p>After running those 3 commands your output should look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*icxyoKJqrxrv13rNEi7qFA.png" /></figure><p>We can confirm the containers are running by running the <strong>docker container ps </strong>command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*CagXVU9mxaesfyPJvA-P2g.png" /></figure><h3>Log into each container and verify access to each repo directory</h3><p>The last thing we have to do is to login to each of the containers to verify they each have access to the respective repo. Let’s start with <strong>Container1</strong>, run:</p><pre>docker exec -it Container1 bash</pre><p>Here is what the output should look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*oNMwea_3jAQEoadzHui9EA.png" /><figcaption>Terminal inside Container1</figcaption></figure><p>Type in <strong>“exit”</strong> to exit the terminal. And repeat the process on <strong>Container2</strong> and <strong>Container3:</strong></p><pre>docker exec -it Container2 bash<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*28955kyprut1EFwMNoF07A.png" /><figcaption>Terminal inside Container2</figcaption></figure><pre>docker exec -it Container3 bash</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*ywfh8DUNojpVCPU_anwJwg.png" /><figcaption>Terminal inside Container3</figcaption></figure><p>Success!!</p><p>GitHub Link: <a href="https://github.com/radcock757/Docker/blob/main/Dockerfile">https://github.com/radcock757/Docker/blob/main/Dockerfile</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*-NizOSmQUDHjjCITv6fv9Q.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37d496b164f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using an API Gateway to trigger a Lambda Function to send a message to an SQS Queue]]></title>
            <link>https://medium.com/@ryan.a.adcock/using-an-api-gateway-to-trigger-a-lambda-function-to-send-a-message-to-an-sqs-queue-3f120a5b4993?source=rss-8822cf9b0f81------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f120a5b4993</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[sqs-lambda]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ryan Adcock]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 06:26:17 GMT</pubDate>
            <atom:updated>2023-03-01T06:26:17.684Z</atom:updated>
            <content:encoded><![CDATA[<h3>Objectives:</h3><ol><li>Create a Standard SQS Queue using Python.</li><li>Create a Lambda function in the console with a Python 3.7 or higher runtime</li><li>Modify the Lambda to send a message to the SQS queue. Your message should contain the current time. You can use the built-in test function for testing.</li><li>Create an API gateway HTTP API type trigger.</li><li>Test the trigger to verify the message was sent.</li></ol><h3>Prerequisites:</h3><p>Before reading this article, you should have a basic understanding of the following principles:</p><p>— <a href="https://aws.amazon.com/sqs/">Amazon SQS</a></p><p><a href="https://www.python.org/">— Python</a> (be sure to have the most up-to-date version installed)</p><p>— <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">Boto3</a> (be sure boto3 is installed)</p><p>— <a href="https://aws.amazon.com/what-is/ide/">IDE</a> — Use an Integrated Development Environment or code editor of your choosing (I will be using Cloud9 which has already been configured for my use)</p><h3>Create an SQS queue using Python</h3><p>We’ll start by creating our Amazon SQS queue. In order to get the python code needed we will need to reference the Boto3 documentation (<a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.html?highlight=sqs#SQS.Client.create_queue">click here to view</a>) to view the code requirements for creating an SQS queue. First, we will import the Boto3 and instantiate the SQS client, enter:</p><pre>import boto3<br>sqs = boto3.client(&#39;sqs&#39;)</pre><p>Next, we will create the queue, enter:</p><pre>response = sqs.create_queue(<br>    QueueName=&#39;my_queue&#39;<br>)</pre><p>And finally, we will have the code print a response when the code is run to let us know the queue was created, enter:</p><pre>print(&#39;Queue created&#39;)</pre><p>Let’s run the code! (Be sure to save your file with a .py extension — i.e. Create_SQS_queue.py) We will first need to ensure we have the proper permissions to execute the code, enter:</p><pre>chmod u+x Create_SQS_queue.py</pre><p>Now to run the code, enter:</p><pre>input: ./Create_SQS_queue.py<br><br>output: Queue created</pre><p>We received a sucessful output message, now let’s head over to our AWS Console and make sure we see the queue created there as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNNATR0QrI9klrDnUo5mhw.png" /></figure><p>Great, it worked as intended! As a recap, here is our full Python code for creating this SQS queue:</p><pre>#!/usr/bin/env python3.7<br><br>#Import Boto3<br>import boto3<br><br>sqs = boto3.client(&#39;sqs&#39;)<br><br>response = sqs.create_queue(<br>    QueueName=&#39;my_queue&#39;<br>)<br><br>print(&#39;Queue created&#39;)</pre><h3>Create a Lambda Function using Python 3.7 or higher</h3><p>Now that we’ve created our SQS queue using python, let’s work on creating our Lambda function that will print a message to our newly created queue when triggered. The message we want the Lambda function to send to the SQS queue is the current date and time in the Eastern timezone of the US.</p><p>From the AWS Console, navigate over to the Lambda homepage and <em>click</em> <strong>create function</strong>. Below is the information to enter in order to create the Lambda function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3ZvIhTkTKgoJ4XrJj0yPg.png" /><figcaption>Lambda creation input</figcaption></figure><p>Our Lambda function has been created but we need to make some adjustments to the permissions for the role that was just created and attached to the Lambda function. Under the<strong>“Configurations”</strong> tab, <em>click</em> on the attached role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdcQ2e1sf4yhbLCqoZyw9Q.png" /><figcaption><em>Click on the attached role</em></figcaption></figure><p>From there, <em>click</em> on <strong>add permissions</strong>, then search for <strong>“sqs”, </strong><em>click</em> on <strong>AmazonSQSFullAccess, </strong>and then <em>click</em> <strong>“Add permissions”</strong> (in the blue box at the bottom of the page)<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAL_PkCDLEzeC4FhE3lcjg.png" /></figure><p>Great! So now our Lambda function has the basic Lambda function permissions and Full SQS Access permissions assigned to the attached role. Lastly, we also need to add our queue as a destination of the Lambda function. <em>Click</em> <strong>“Add destination” </strong>and then enter in the following configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGav4-E2J2WED-FTCfySAg.png" /><figcaption>Add queue as a destination</figcaption></figure><h3>Modify the Lambda function to Send Message to the SQS Queue</h3><p>Navigate back over to our newly created Lambda function so we can modify the code. We will again need to refer back to the Boto3 Documentation to find the code we will use to send a message to the SQS queue. You will see the code we need below(<a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.html?highlight=sqs#SQS.Client.send_message">link to Boto3 Documentation</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqyCGj8FWfZnIl0rkVGCDw.png" /></figure><p>Not all of the parameters are required, we will only need to use the ‘QueueURL’ and ‘MessageBody’. To get the ‘QueueURL’, navigate back over to our queue and you will see the ‘QueueURL’ under the queue details (save it for later).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvZGvTtcGpor9lnRgKjjPA.jpeg" /><figcaption>QueueURL</figcaption></figure><p>The next parameter we need is the ‘MessageBody’ and we want that to contain the current date and time in the Eastern timezone of the US. To do this, we will need to import two additional modules; datetime and dateutil.tz. Here is the structure of our finished code to input into the Lambda function:</p><pre>import json<br>import boto3<br>from datetime import datetime <br>import dateutil.tz<br><br># Define the lambda handler<br>def lambda_handler(event, context):<br>    <br>    sqs = boto3.client(&#39;sqs&#39;)<br>    <br>    # Get the current time<br>    est = dateutil.tz.gettz(&#39;US/Eastern&#39;)<br>    current_time = datetime.now(est)<br>    time = current_time.strftime(&quot;%I:%M:%S %p&quot;)<br>    <br>    # Send the message to the SQS queue<br>    response = sqs.send_message(<br>        QueueUrl = &#39;https://sqs.us-east-1.amazonaws.com/026662593498/my_queue&#39;,<br>        MessageBody = json.dumps(f&quot;US Eastern current time: {time}&quot;)<br>    )<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps(&#39;Message sent to queue&#39;)<br>    }    }</pre><p>Now, before we move on, let’s test our code. <em>Click</em> <strong>“Deploy”</strong> to save the added code to the function and then <em>click</em> <strong>“test” </strong>and <strong>“configure test event”</strong>. Give the test an name, i.e. <strong>test</strong>, and then for the template select <strong>“apigateway-aws-proxy”</strong> and <em>click</em> <strong>“save”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5c4qI9v0CHv5ZPjrPoyjA.png" /><figcaption>Create test event</figcaption></figure><p>Now, <em>click</em> the blue <strong>“Test”</strong> button to run the test!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opWDJ_AfjUYThaRSyzAfzA.png" /><figcaption>Successful test result</figcaption></figure><p>Fantastic, look like our code is running correctly!</p><h3><strong>Create an API gateway HTTP API type trigger</strong></h3><p>Let’s create the API gateway that will trigger our Lambda function. From the Lambda function overview, <em>click</em> <strong>“Add trigger”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SG2V9b8xg_TWz12s9S3Y_Q.png" /><figcaption>Add trigger</figcaption></figure><p>Select <strong>“API Gateway”</strong>, for intent <strong>“create new api”</strong>, for api type <strong>“HTTP API”</strong>, and for security <strong>“open”</strong>, then <em>click</em> <strong>Save</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kwLza6HwJty_0tGyQG40g.png" /><figcaption>API Gateway trigger</figcaption></figure><p>Now from the <strong>“Configurations”</strong> tab of our Lambda function, <em>click</em> on the API Gateway’s URL address. It should direct you to a website with the following message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7IyEigwvACLATpcv1-OlQ.png" /><figcaption>URL message</figcaption></figure><p>Great, that’s the message we were expecting to see. Now lets head over to our queue and poll for message to see if the Lambda function sent a message to the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQGcrASO2-8V3EOIxkEeYw.png" /><figcaption>Messages in the queue</figcaption></figure><p>Let’s see what the latest message says:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjIyAZfTAEq1Y60MES56QQ.png" /><figcaption>Current time</figcaption></figure><p>Bravo! We have successfully completed all of our objectives!</p><h3>GitHub Links:</h3><p><em>click </em><a href="https://github.com/radcock757/Red_LUIT_Python/blob/main/Week15Project/Create_SQS_queue.py">Create SQS queue</a><br><em>click</em> <a href="https://github.com/radcock757/Red_LUIT_Python/blob/main/Week15Project/Lambda_SQS_code.py">Lambda Code</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*K-Lp5lBH91477h7n0lN-HQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f120a5b4993" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Boto3 and Python: Create a DynamoDB Table, Batch Write to the table, and Scan the table]]></title>
            <link>https://medium.com/@ryan.a.adcock/using-boto3-and-python-create-a-dynamodb-table-batch-write-to-the-table-and-scan-the-table-892d29c55482?source=rss-8822cf9b0f81------2</link>
            <guid isPermaLink="false">https://medium.com/p/892d29c55482</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ryan Adcock]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 18:38:19 GMT</pubDate>
            <atom:updated>2023-02-20T18:38:19.044Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4ixwYXDs-K-idh6ZMOErDw.png" /></figure><p>This article will provide the reader with a step-by-step guide on how to create a dynamodb table, batch write items to the table, and how to scan the table using boto3 and Python.</p><h3>Objectives:</h3><ol><li>Create an empty DynamoDB table for something of your choosing</li><li>Add at least 10 items to the table</li><li>Use boto3 and Python to scan the DyanamoDB table</li></ol><h3>Prerequisites:</h3><p>Before reading this article, you should have a basic understanding of the following principles:</p><p>— <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a></p><p>—<a href="https://www.python.org/"> Python</a> (be sure to have the most up-to-date version installed)</p><p>— <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">Boto3</a> (be sure boto3 is installed)</p><p>— <a href="https://aws.amazon.com/what-is/ide/">IDE</a> - Use an Integrated Development Environment or code editor of your choosing (I will be using Cloud9 which has already been configured for my use)</p><h3>Objective 1:</h3><p>Let’s get started by creating an empty DynamoDB table. To start, in Cloud9 open a new file from a template using Python. Delete all of the characters that come pre-loaded in the file and enter this text at the top of the file:</p><pre>#!/usr/bin/env python3.7</pre><p>This will make the script portable (which is important because we want other users to be able to run this script) because it will interpret your $PATH and specify the Python version.</p><p>Next, we want to utilize the functionality of the Boto3 module to create, configure, and manage AWS services. However, you must import it to be able to use it. Enter:</p><pre>import boto3</pre><p>Now, we want to get the service resource, in our case we are looking to use Dynamodb. (For more in-depth information about using boto3 and Dynamodb can be found <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/guide/dynamodb.html?highlight=dynamodb">here</a>) Enter:</p><pre>dynamoddb = boto3.resource(&#39;dynamodb&#39;)</pre><p>Lastly, let’s create the table. Let’s set the variable for the table to ‘my_table’. The table name is going to be ‘Movies’ (the table name must conform to the DynamoDB naming rules, and must be unique for the current AWS account and Region) and the table will contain a list of movies (‘movies_title’) and their directors (‘director_name’). Enter:</p><pre>my_table = dynamodb.create_table( # Create the DynamoDB table.<br>    TableName=&#39;Movies&#39;,<br>    KeySchema=[<br>        {<br>            &#39;AttributeName&#39;: &#39;movie_title&#39;,<br>            &#39;KeyType&#39;: &#39;HASH&#39;<br>        },<br>        {<br>            &#39;AttributeName&#39;: &#39;director_name&#39;,<br>            &#39;KeyType&#39;: &#39;RANGE&#39;<br>        }<br>    ],<br>    AttributeDefinitions=[<br>        {<br>            &#39;AttributeName&#39;: &#39;movie_title&#39;,<br>            &#39;AttributeType&#39;: &#39;S&#39;<br>        },<br>        {<br>            &#39;AttributeName&#39;: &#39;director_name&#39;,<br>            &#39;AttributeType&#39;: &#39;S&#39;<br>        },<br>    ],<br>    ProvisionedThroughput={<br>        &#39;ReadCapacityUnits&#39;: 5,<br>        &#39;WriteCapacityUnits&#39;: 5<br>    }<br>)</pre><p><strong>Hash and Range Primary Key </strong>— The primary key is made of two attributes. The first attribute is the <strong>hash attribute</strong> and the second attribute is the <strong>range attribute</strong>. In our example, the ‘Movies’ table can have ‘movie_title’ and ‘director_name’ as its primary key, where ‘movie_title’ is the hash attribute and ‘director_name’ is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.</p><p><strong>Provisioned Throughput</strong> — Provisioned is the default setting and is free-tier eligible, so we will set the read and write capacities to 5. (for more information regarding provisioned vs. on-demand, click <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html#HowItWorks.OnDemand">here</a>)</p><p>Under the code we just wrote to create the table, we are going to add some additional code that will cause a pause in the iteration of our code so it will wait for the table to be created. Once the table is created the code will move on and finish executing. Enter:</p><pre>my_table.wait_until_exists()</pre><p>Fantastic! We have our empty table created, now let’s start adding items to the table.</p><h3>Objective 2:</h3><p>With our DynamoDB table created, we can now start adding items to the list. We are going to use the batch.write_items to add items to the table. Enter:</p><pre>with my_table.batch_writer () as batch: #Add items to the table<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Titanic&#39;,<br>            &#39;director_name&#39; : &#39;James Cameron&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;North by Northwest&#39;,<br>            &#39;director_name&#39; : &#39;Alfred Hitchcock&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Citizen Kane&#39;,<br>            &#39;director_name&#39; : &#39;Orson Welles&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;The Quiet Man&#39;,<br>            &#39;director_name&#39; : &#39;John Ford&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Goodfellas&#39;,<br>            &#39;director_name&#39; : &#39;Martin Scorsese&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Jaws&#39;,<br>            &#39;director_name&#39; : &#39;Steven Spielberg&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;The Shining&#39;,<br>            &#39;director_name&#39; : &#39;Stanley Kubrick&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Beetlejuice&#39;,<br>            &#39;director_name&#39; : &#39;Tim Burton&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Avatar&#39;,<br>            &#39;director_name&#39; : &#39;James Cameron&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;The Sixth Sense&#39;,<br>            &#39;director_name&#39; : &#39;M. Night Shyamalan&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Top Gun: Maverick&#39;,<br>            &#39;director_name&#39; : &#39;Joseph Kosinski&#39;<br>            }<br>        )</pre><p>Great! This code will add 11 items to the created DynamoDB table. We can now move on to the final objective, scanning the table.</p><h3>Objective 3:</h3><p>With the table created and items added to the table, we will now run a scan on the table. To do so, enter:</p><pre>response = my_table.scan() # Scan the table<br>item = response[&#39;Items&#39;]<br>print(*item, sep = &quot;\n&quot;) # Print the results of the table scan</pre><p>This will scan the table and then print the results of the table scan with each item on its own line. The result should look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*MdFkO1rfLs3Y9XQCnHXJ4A.png" /></figure><p>Let’s check on our AWS console to ensure the table has created and the items have been added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18cLxb8GcYxZb7KMGKeOsw.png" /><figcaption>Confirms table has been created</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6QduoptiXF1Gnpfut9_FJA.png" /><figcaption>Confirms items have been added to the table</figcaption></figure><p>Congratulations! We have successfully created a DynamoDB table, added items to the table, and scanned the table using Boto3 and Python.</p><h3>Final code:</h3><pre>#!/usr/bin/env python3.7<br><br>import boto3 #import boto3 module<br><br>dynamodb = boto3.resource(&#39;dynamodb&#39;) # Get the service resource.<br><br>my_table = dynamodb.create_table( # Create the DynamoDB table.<br>    TableName=&#39;Movies&#39;,<br>    KeySchema=[<br>        {<br>            &#39;AttributeName&#39;: &#39;movie_title&#39;,<br>            &#39;KeyType&#39;: &#39;HASH&#39;<br>        },<br>        {<br>            &#39;AttributeName&#39;: &#39;director_name&#39;,<br>            &#39;KeyType&#39;: &#39;RANGE&#39;<br>        }<br>    ],<br>    AttributeDefinitions=[<br>        {<br>            &#39;AttributeName&#39;: &#39;movie_title&#39;,<br>            &#39;AttributeType&#39;: &#39;S&#39;<br>        },<br>        {<br>            &#39;AttributeName&#39;: &#39;director_name&#39;,<br>            &#39;AttributeType&#39;: &#39;S&#39;<br>        },<br>    ],<br>    ProvisionedThroughput={<br>        &#39;ReadCapacityUnits&#39;: 5,<br>        &#39;WriteCapacityUnits&#39;: 5<br>    }<br>)<br><br>my_table.wait_until_exists() # Wait until the table exists.<br><br>with my_table.batch_writer () as batch: #Add items to the table<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Titanic&#39;,<br>            &#39;director_name&#39; : &#39;James Cameron&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;North by Northwest&#39;,<br>            &#39;director_name&#39; : &#39;Alfred Hitchcock&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Citizen Kane&#39;,<br>            &#39;director_name&#39; : &#39;Orson Welles&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;The Quiet Man&#39;,<br>            &#39;director_name&#39; : &#39;John Ford&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Goodfellas&#39;,<br>            &#39;director_name&#39; : &#39;Martin Scorsese&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Jaws&#39;,<br>            &#39;director_name&#39; : &#39;Steven Spielberg&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;The Shining&#39;,<br>            &#39;director_name&#39; : &#39;Stanley Kubrick&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Beetlejuice&#39;,<br>            &#39;director_name&#39; : &#39;Tim Burton&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Avatar&#39;,<br>            &#39;director_name&#39; : &#39;James Cameron&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;The Sixth Sense&#39;,<br>            &#39;director_name&#39; : &#39;M. Night Shyamalan&#39;<br>            }<br>        )<br>    batch.put_item(<br>        Item={<br>            &#39;movie_title&#39; : &#39;Top Gun: Maverick&#39;,<br>            &#39;director_name&#39; : &#39;Joseph Kosinski&#39;<br>            }<br>        )<br><br>print(my_table.item_count) # Print out the number of items in the table.<br><br>response = my_table.scan() # Scan the table<br>item = response[&#39;Items&#39;]<br>print(*item, sep = &quot;\n&quot;) # Print the results of the table scan</pre><h3>GitHub Link:</h3><pre>https://github.com/radcock757/Red_LUIT_Python/blob/main/Week14-Project.py</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=892d29c55482" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Basics: Creating Dictionaries and Printing Lists]]></title>
            <link>https://medium.com/@ryan.a.adcock/python-basics-creating-dictionaries-and-printing-lists-4c0533bec90b?source=rss-8822cf9b0f81------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c0533bec90b</guid>
            <category><![CDATA[cloud9]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Ryan Adcock]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 17:01:18 GMT</pubDate>
            <atom:updated>2023-02-20T17:26:28.617Z</atom:updated>
            <content:encoded><![CDATA[<h3>Task:</h3><p>Your company needs to learn about the files located on various machines. You have been asked to build a script that extracts information such as the name and size about the files in the current working directory and stores it in a list of dictionaries.</p><h3>Objectives:</h3><p>1. Use a Python script to find the current working directory (CWD)<br> 2. Use a Python script to extract information (name, size, permissions) about files in the current working directory and store this information in a dictionary<br> 3. Add the dictionary to a list and print the list</p><p>I will be writing my code in a Python file on AWS Cloud9 and storing it in a repository on my GitHub. Link to GitHub file: <a href="https://github.com/radcock757/Red_LUIT_Python/blob/main/LUIT-wk13.py">https://github.com/radcock757/Red_LUIT_Python/blob/main/LUIT-wk13.py</a></p><h3>Objective 1</h3><p>Objective 1 is writing our script to find the CWD. We will need to do some prep work to be able to accomplish this objective. Let’s get started!</p><p>In Cloud9 open a new file from a template using Python. Delete all of the characters that come pre-loaded in the file and enter this text at the top of the file:</p><pre>#!/usr/bin/env python3.7</pre><p>This will make the script portable (which is important because we want other users to be able to run this script) because it will interpret your $PATH and specify the Python version.</p><p>Next, we want to utilize the functionality of the OS module that is already a part of the standard library on Python 3, however, you must import it to be able to use it. OS provides a portable way of using operating system-dependent functionality. We also want to utilize the STAT module which will return file attributes(permissions, etc.); this also must be imported. Enter:</p><pre>import os<br>import stat</pre><p>Next, we will create an <strong>empty</strong> list that will eventually contain the final information we are looking for. Let’s call this list “files_list”, enter:</p><pre>files_list = []</pre><p>We are now ready to find the CWD. We will set the current working directory as a variable that we can call on later in the script. Let’s call this variable “my_path” and set it equal to the CWD, enter:</p><pre>my_path = os.getcwd()</pre><p>Fantastic! We have found our CWD. Let’s move on to the next objective.</p><h3>Objective 2</h3><p>Objective 2 is to extract information about the files in the CWD. We will start by making a list of all the files in the CWD. To do this, we will utilize the OS module. Let’s call this list “dir_list”, enter:</p><pre>dir_list = os.listdir(my_path)</pre><p>Now that we have the list of files in the CWD, we need to extract information about these files and publish them in a dictionary. We want to utilize Python dictionaries because they store data values in key:value pairs. Let’s start by creating variables that will hold the values for each key in the dictionary. To do this we will use a <strong>for-loop</strong> statement. <strong>For-loop</strong> statements are used to when you have a block of code which you want to repeat a fixed number of times (ie. on all of the files in our list). This for-loop statement is going to extract the file permissions, file names, and file sizes, enter:</p><pre>for file in dir_list:<br>    status = os.stat(file)<br>    permissions = stat.filemode(status.st_mode)<br>    file_path = os.path.join(my_path, file)<br>    file_size = os.stat(file_path)</pre><p>Now, let’s put all of this extracted information in a dictionary. We will start by creating our dictionary, then we will define the key and value pairs inside the dictionary. Let’s call this dictionary “my_dictionary” and our dictionary keys will be “Permissions”, “Path”, “File Name”, and “File Size”. We will use the variables from above for the values. Enter:</p><pre>my_dictionary = {<br>        &#39;File Permissions&#39; : permissions,<br>        &#39;Path&#39; : file_path,<br>        &#39;File Name&#39; : file,<br>        &#39;File Size&#39; : file_size.st_size<br>}</pre><p><strong>*Important note:</strong> “my_dictionary” needs to be nested inside the for-loop (be mindfull of indentions. This is how they should look put together:</p><pre>for file in dir_list:<br>    status = os.stat(file)<br>    permissions = stat.filemode(status.st_mode)<br>    file_path = os.path.join(my_path, file)<br>    file_size = os.stat(file_path)<br><br>    #Create a dictionary<br>    my_dictionary = {<br>        &#39;File Permissions&#39; : permissions,<br>        &#39;Path&#39; : file_path,<br>        &#39;File Name&#39; : file,<br>        &#39;File Size&#39; : file_size.st_size<br>    }</pre><h3>Objective 3</h3><p>To complete our task, we will need to we need to update or <strong>append</strong> our empty list with the dictionary.</p><p>*This should also be nested in the for-loop statement*, enter:</p><pre>files_list.append(my_dictionary)</pre><p>Then print the updated list (not nested in the for-loop statement), enter:</p><pre>print(files_list)</pre><p>You may notice that this isn’t very easy to read, let’s have it print each list item on a new line to make it easier to read, change the previous code to this:</p><pre>print(*files_list, sep = &quot;\n&quot;)</pre><h3>Final Result</h3><p>Here is how all of our code looks put together in our Python file:</p><pre>#!/usr/bin/env python3.7<br><br>#Import os &amp; stat module<br>import os<br>import stat<br><br>#Create an empty list<br>files_list = []<br><br>#Set the CWD as a variable<br>my_path = os.getcwd()<br><br>#Create list of files in CWD<br>dir_list = os.listdir(my_path)<br><br><br>#Set variables for dictionary<br>for file in dir_list:<br>    status = os.stat(file)<br>    permissions = stat.filemode(status.st_mode)<br>    file_path = os.path.join(my_path, file)<br>    file_size = os.stat(file_path)<br><br>    #Create a dictionary<br>    my_dictionary = {<br>        &#39;File Permissions&#39; : permissions,<br>        &#39;Path&#39; : file_path,<br>        &#39;File Name&#39; : file,<br>        &#39;File Size&#39; : file_size.st_size<br>    }<br>    #Append list with dictionary<br>    files_list.append(my_dictionary)<br><br>#Print the updated list<br>print(*files_list, sep = &quot;\n&quot;)</pre><p>Switch over to the terminal and let run this code. First we will need the proper permissions to execute this file, enter:</p><pre>chmod u+x &lt;path to file&gt;</pre><p>Now that we have the proper permissions, enter:</p><pre>./&lt;file name&gt;</pre><p>Your result should look similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46xYLGXzyDuorbSEOzrVnw.png" /><figcaption>Printed list</figcaption></figure><p>Congratulations! We have successfully completed all of the objectives need to accomplish the task at hand. You should now have a better understanding of how to create lists and create dictionaries using Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LqqALymhhTT7HMxrPVX-qA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c0533bec90b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Highly Available 3-Tier Architecture for a Web Application in AWS]]></title>
            <link>https://medium.com/@ryan.a.adcock/how-to-create-a-highly-available-3-tier-architecture-for-a-web-application-in-aws-45dc76ce7477?source=rss-8822cf9b0f81------2</link>
            <guid isPermaLink="false">https://medium.com/p/45dc76ce7477</guid>
            <category><![CDATA[application-load-balancer]]></category>
            <category><![CDATA[auto-scaling-groups]]></category>
            <category><![CDATA[3-tier-architecture]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <dc:creator><![CDATA[Ryan Adcock]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 23:51:00 GMT</pubDate>
            <atom:updated>2023-01-16T23:51:00.144Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTAWZNYvV7Jhl0TKNaxvTw.png" /></figure><p>We are going to be creating a highly available 3-tier architecture for a web application in AWS. There will be a Web tier, an Application tier, and a Database tier. Below is a breakdown of each tier:</p><p><strong>Web Tier<br></strong>1. 2 public subnets<br>2. Minimum of 2 EC2 instances with an OS of your choice (free tier) in an Auto Scaling Group.<br>3. EC2 Web Server Security Group allowing inbound permission from the internet.<br>4. Boot strap static web page or create a custom AMI that already includes the static web page.<br>5. Create a public route table and associate the 2 public subnets.</p><p><strong>Application Tier<br></strong>1. 2 private subnets<br>2. Minimum of 2 EC2 instances with an OS of your choice (free tier) in an Auto Scaling Group.<br>3. EC2 Application Server Security Group allowing inbound permission from the Web Server Security Group.<br>4. Associate with private route table.<br> Note: This is not a true application tier as we don’t have any provided code to run on the EC2 instances.</p><p><strong>Database Tier</strong><br>1. A free Tier MySql RDS Database.<br>2. The Database Security Group should allow inbound traffic for MySQL from the Application Server Security Group.<br>3. 2 private subnets.<br>4. Associate with private route table.</p><p><strong>Testing<br></strong>1. Make sure you can access the web tier web page from the internet.<br>2. From the web tier verify that you can ping the application tier from the web tier by running the ping command from an EC2 instance in the web tier.</p><p>To accomplish all of this we will need to use a VPC, an Internet Gateway, a NAT Gateway, Auto Scaling Groups, Route Tables, an Application Load Balancer, and much more. Let’s start by creating a VPC</p><h3>Creating a VPC</h3><p>Starting by clicking <strong><em>Create VPC </em></strong>from the <strong>VPC dashboard</strong> in the <strong>AWS console. </strong>Now, give the VPC a name (3-Tier-VPC), enter in the IPv4 CIDR block (10.10.0.0/16), and 2 availability zones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kuPepAunOyTHO5y0NkTp8Q.png" /></figure><p>Scroll down, and select 2 public subsets and 4 private subnets. Then assign each of the subnets an IPv4 CIDR block (10.10.1.0/24, 10.10.2.0/24, 10.10.3.0/24, 10.10.4.0/24, 10.10.5.0/24, and 10.10.6.0/24).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*snTEsg0O98dV3h1K-cAlxQ.png" /></figure><p>Scroll down, and select 1 per AZ for the <strong>NAT gateway</strong>, select None for VPC endpoints, enable both DNS hostnames and DNS resolution, and finally <strong>Create VPC</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJTFKWZsVB9DGAMhtVtooQ.png" /></figure><p>Success the VPC is created with 2 public subnets and 4 private subnets. Also, an <strong>Internet Gateway</strong> has been created and attached to the VPC. 5 <strong>Route Tables</strong> have also been created, a public route table and 4 private route tables. The public and the private subnets have been associated with these <strong>route tables</strong> and a default route to the internet (0.0.0.0/0) has been added to the <strong>route table</strong>. However, we just need 2 <strong>route tables</strong> for this example. Remove all subnet associations with the route tables and then delete them. We will then create 2 new <strong>route tables, </strong>a <strong>public</strong> and a <strong>private. </strong>From the <strong>VPC dashboard</strong> under <strong>route tables</strong> on the left-hand side, click <strong>route tables</strong> and then <strong>create route table. </strong>Give the route table a name (3-Tier-Public), then select our VPC (3-Tier-VPC) for VPC, and then click <strong>Create Route Table.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEFxVD6ZV9JuNQEKDy-_zA.png" /></figure><p>Then click Actions, edit subnet associations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8iMIQWYk_V91_bYwZApuw.png" /></figure><p>Then select the 2 public subnets and click save associations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hu3FSApjRkTxsTfxhmqOHQ.png" /></figure><p>Then click actions, then edit routes. From there input 0.0.0.0/0 for destination and then for target select our <strong>internet gateway</strong> and save changes. Repeat the same process to create a <strong>Private Route Table</strong> and add the 4 private subnet associations but do not add the internet gateway.</p><p>Under <strong>Edit Subnet settings</strong>, we need to <strong>ENABLE </strong>auto-assign public IPv4 Address for both <strong>public subnets</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBjj01-AjtsxMXWlbLbp2Q.png" /></figure><p>Now, go back into our <strong>3-Tier-Private</strong> route table, and add a new route with a destination of 0.0.0.0/0 and a target of the <strong>NAT Gateway</strong> in one of our public subnets. This will allow our private instances access to the Internet for essential software updates while blocking incoming traffic from the outside world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzWRp1Jdfc0w1ikY2NKeqw.png" /></figure><h3>Application Load Balancers</h3><p>We will now create 2 Application load balancers, one for the public Web Tier side and one for the private Application Tier side. Let’s first create the Web Tier ALB. From the <strong>EC2 dashboard</strong>, under <strong>Load Balancers</strong>, click <strong>create Load Balancer,</strong> then click <strong>create</strong> under the <strong>Application Load Balancer. </strong>Give the ALB a name (WebTier-Public-ALB), this ALB will be <strong>internet facing</strong>, select <strong>IPv4</strong>, then select our VPC (3-Tier-VPC), then for mapping select both of our public subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQGzY7fmyJPOMAbbcTMlHw.png" /></figure><p>For <strong>Security Groups</strong>, select the Public SG security group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-IVuWnJfcaiGN9OJ3j79w.png" /></figure><p>Under <strong>Listeners and routing</strong>, select <strong>create target group. </strong>Select <strong>instances</strong>, name the target group (WebTier-Public), select our VPC (3-Tier-VPC), then HTTP1, and click <strong>next</strong> then on the next page click <strong>create target group.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zb_AtU3SqYbAXgEe_se3hg.png" /></figure><p>Now, go back to our <strong>Load Balancer</strong> configuration page, and select the <strong>Target Group</strong> we just created (you may need to click the refresh button next to the target group). Then click <strong>create load balancer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCbxOoBVq6jdQjuhJMGL3Q.png" /></figure><p>We will follow very similar steps to create the second <strong>Application Load Balancer </strong>for the Application Tier<strong>. </strong>This ALB is not truly necessary at this time since there is no added code to run an application but I will still show you how it’s accomplished.</p><p>Start by naming the ALB (ApplicationTier-Private-ALB), then select <strong>internal</strong>, <strong>IPv4</strong>, select our VPC (3-Tier-VPC), for mapping select both AZs and our private subnets 1 &amp; 2, and our <strong>Private SG</strong> security group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*89DXtqvvVX8sJoPUmQqXtQ.png" /></figure><p>Then select <strong>create target group</strong> like before, and select instances, name it ApplicationTier-Private, then select our VPC (3-Tier-VPC), then HTTP1, then click <strong>next</strong> and then on the next page click <strong>create target group.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*_mKUegOnVrKtumcf3E3oGQ.png" /></figure><p>Now, go back to our <strong>Load Balancer</strong> configuration page, and select the <strong>Target Group</strong> we just created (again, you may need to click the refresh button next to the target group). Then click <strong>create load balancer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQfLMIpZM5ZIRp9XWW0cZg.png" /></figure><h3><strong>EC2 Launch instances and Auto Scaling Groups</strong></h3><p>Navigate to <strong>EC2 &gt; Instances &gt; Launch Template</strong>, and we will create an EC2 Launch Template. Give the template a name (3-Tier-Public-LT), fill in the template description (Public-3-Tier), and select “Provide guidance to help me set up a template that I can use with EC2 Auto Scaling”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsR-8xiuCo38gK2CgDzNZQ.png" /></figure><p>Select the Amazon Linux 2 AMI (free tier eligible) and 64-bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cm-liiPV6kcGAov83cBQA.png" /></figure><p>Select <strong>t2.micro</strong> for our instance type and then create a key pair. Under <strong>Network Settings,</strong> select Create Security Group, then name the security group (Public SG), select our VPC (3-Tier-VPC), add the following security group rules 1. (ssh-TCP-22 &amp; Anywhere-0.0.0.0/0)and 2. (HTTP-TCP-80 &amp; Anywhere-0.0.0.0/0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7Bj7_Ghm-dL9VdScM3keQ.png" /></figure><p>Scroll down to <strong>Advanced details, </strong>under <strong>user data</strong> enter the following command:</p><pre>#!/bin/bash<br><br>#Update the OS<br>sudo yum update -y<br><br>#Install, enable, and start Apache Web Server<br>sudo yum install -y httpd<br>sudo systemctl enable httpd<br>sudo systemctl start httpd<br><br>#Modify the webpage<br>sudo echo &quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello World and welcome to my web tier!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot; &gt; /var/www/html/index.html</pre><p>and then click <strong>Create launch template.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvLHUNobsDS_NTJtX8R9zw.png" /></figure><p>We will now repeat the <strong>Create Launch Template</strong> process for the private side. Name the Launch Template (3-Tier-Private-LT), give it a template description (Private 3 Tier), and “Provide guidance to help me set up a template that I can use with EC2 Auto Scaling”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GjDpbjy7FJnqgorDSV7m2A.png" /></figure><p>Select the Amazon Linux 2 AMI (free tier eligible) and 64-bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxIIc2FQFBSyo5HakiO9qw.png" /></figure><p>Select <strong>t2.micro</strong> for instance type and then create or reuse the previous key pair. Under <strong>Network Settings,</strong> select <strong>Create Security Group</strong>, then name the security group (Private SG), select our VPC (3-Tier-VPC), add the following security group rules 1. (ssh-TCP-22 &amp; Custom-Public SG) {this allows us access to the Application Tier from an EC2 instance in the Web tier}, 2. (HTTP-TCP-80 &amp; Custom-0.0.0.0/0), 3. (MSQL/Aurora-Custom-0.0.0.0/0 {*we will change this in a later step}). We don’t need to add anything to the <strong>user data</strong> for this example so click <strong>Create Launch Template</strong>. (*Note: This is not a true application tier as we don’t have any provided code to run on the EC2 instances.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpR7jHlrqI7WMn-N91_ZdQ.png" /></figure><p>Ok, we’ve got both <strong>ALBs</strong> configured and both <strong>EC2 Launch Templates</strong> created. We will now create our <strong>Auto Scaling Groups.</strong></p><h3>Create 2 Auto Scaling Groups</h3><p>We will use our <strong>EC2 Launch Templates</strong> to create our 2<strong> Auto Scaling Groups. </strong>From the <strong>EC2 dashboard</strong> under <strong>Auto Scaling, </strong>select <strong>Auto Scaling Groups</strong> then <strong>create auto scaling group. </strong>Name the ASG (WebTier-Public-ASG), then select our public launch template, and click <strong>next</strong> at the bottom of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-4EwLpM07kEcHZxywtqqg.png" /></figure><p>Under <strong>Network</strong>, select our VPC (3-Tier-VPC), select both public subnets, and then click <strong>next.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8OI9_dN_tJCyNCzbvhryQ.png" /></figure><p>On the next page, select <strong>Attach to an existing load balancer</strong>, then <strong>choos from your load balancer target groups,</strong> then select our <strong>WebTier-Public </strong>target group, and click <strong>next.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvcHBgGNx3z07zSfV5O9HQ.png" /></figure><p>We have a desired capacity of 2 instances running, a minimum capacity of 2 instances, and a maximum capacity of 5 instances running, then click <strong>skip to review </strong>and then click <strong>create auto scaling group.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Z-zVen7hStsz1sM_DFdGw.png" /></figure><p>Now lets create our ASG for the Application Tier, name the ASG (ApplicationTier-Private-ASG), select our Private launch template, and click <strong>next.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWs1nrOJh1btxC-ubAMlXg.png" /></figure><p>Then select our VPC (3-Tier-VPC), select 2 private subnets 1 &amp; 2, then click <strong>next.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYCzLruc1msMS-onnLiVOA.png" /></figure><p>On the next page, select <strong>Attach to an existing load balancer</strong>, then <strong>choos from your load balancer target groups,</strong> then select our <strong>ApplicaitonTier-Private </strong>target group, and click <strong>next.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LvwVVU34MNc2dIgw0xTAcg.png" /></figure><p>We have a desired capacity of 2 instances running, a minimum capacity of 2 instances, and a maximum capacity of 5 instances running, then click <strong>skip to review </strong>and then click <strong>create auto scaling group.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eh-Nva_XhZJQjXi28ED31Q.png" /></figure><h3><strong>Bastion Host</strong></h3><p>A bastion host is a dedicated instance/server that allows authorized users to access a private network from an external network such as the internet. We will be using a bastion host instance in the public subnet to allow access to the private subnets. We will start by launching a new instance named <strong>BastionHost</strong>, select the Amazon Linux AMI, and t2.micro instance type, select/create a key pair. Be sure to select our VPC (3-Tier-VPC), select the public1-us-east-1a subnet, create a <strong>Bastion Host SG</strong> security group, and add 1 rule for SSH from your IP address. Then launch the instance. Then go back into the <strong>Bastion Host SG </strong>and create an outbound rule to SSH into <strong>Private SG. </strong>And then add a new inbound rule for the <strong>Private SG</strong>, that allows all traffic, custom, and select the <strong>Bastion Host SG</strong> and save rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wZuSaG2FKSXOxtiks8I0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBz9hkShWZEv1brzy22z_Q.png" /></figure><h3>Database Tier — Create a MySQL RDS Database</h3><p>Navigate over to the <strong>RDS dashboard</strong> by searching for <strong>RDS</strong> in the search bar of the <strong>AWS console,</strong> then select <strong>create database. </strong>Use the <strong>Standard Create</strong> option, select MySQL, version MySQL 8.0.28, and then free tier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnbEMgxcQHWojesMkIdR3A.png" /></figure><p>Next, give the database a name (DB-3-Tier), choose a Master username (admin), and choose a master password (Make sure you write them down and keep it closeby).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M0cx_VVIuPylsL6kLGCdtw.png" /></figure><p>We will use a <strong>db.t2.micro </strong>instance type, select <strong>don’t connect to an EC2 compute resource</strong>, select <strong>IPv4</strong>, select our VPC, select <strong>no</strong> for public access, create a new security group called <strong>Database SG </strong>and select <strong>us-east-1a</strong> for the AZ, then select <strong>create database.</strong> This process will take a few minutes to provision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*ALlplPeD8CZAHO3aZLE2Uw.png" /></figure><p>Once that is created we will need to make a few adjustments to the <strong>Private SG </strong>and <strong>Database SG</strong>. Head over to the <strong>VPC dashboard</strong>, and select <strong>Security Group</strong>. Then select the <strong>Private SG</strong>, then <strong>edit inbound rules. </strong>Delete the placeholder MYSQL/Aurora rule and create a new MYSQL/Aurora and then select <strong>custom</strong> and our <strong>Database SG </strong>for the source, and save the rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0aO3xXQA0H6oScX9yVk2A.png" /></figure><p>Next, select the <strong>Database SG</strong>, then <strong>edit inbound rules</strong>, delete the current rule and create a new rule with <strong>MYSQL/Aurora</strong> as the type, <strong>custom </strong>and <strong>Private SG</strong> for the source, and save the rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QxFJtdctVp8t5gspEur3bw.png" /></figure><p>This completes the building section of our task and we will now move on to test our 3 Tier Architecture!</p><h3>Testing</h3><p>To test our 3 Tier Architecture we will start by testing that the Web Tier is accessible from the internet. From the <strong>EC2 dashboard, </strong>under <strong>Load Balancing,</strong> select <strong>load balancers, </strong>and select <strong>WebTier-Public-ALB</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ra94ICYqbxddZhg7gQAcQ.png" /></figure><p>Then copy the <strong>DNS name</strong> and paste it into the browser address in a new tab. This is how your website should show up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AO8ANakCSGunhJZI5aG0Cw.png" /><figcaption>Success!</figcaption></figure><p>Fantastic! This proves our <strong>Web Tier</strong> is accessible from the internet! Next, we will now SSH into our <strong>Bastion Host</strong> instance to then ping the <strong>Application Tier</strong> from the <strong>Web Tier. </strong>(If you need guidance on how to SSH into an instance, click here <a href="http://can ping the application tier from the web tier by running the ping command from an EC2 instance in the web tier.">SSH into an instance</a>) Here is the command we will run from the CLI to ping the <strong>Application Tier.</strong></p><pre>$ ping &lt;ApplicationTier-Private-ALB DNS name&gt;</pre><p>And here is the output of that command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Dl1UQNFbldumn60YMBtiQ.png" /></figure><p>Excellent! We were able to successfully ping the Application Tier from the Bastion Host in the Web Tier!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LqqALymhhTT7HMxrPVX-qA.gif" /></figure><p>Congratulations on creating a highly available 3 Tier Architecture!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45dc76ce7477" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating and Interacting with an Amazon DynamoDB table from an EC2 instance CLI with an IAM role]]></title>
            <link>https://medium.com/@ryan.a.adcock/creating-and-interacting-with-an-amazon-dynamodb-table-from-an-ec2-instance-cli-with-an-iam-role-c35f938794d3?source=rss-8822cf9b0f81------2</link>
            <guid isPermaLink="false">https://medium.com/p/c35f938794d3</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Ryan Adcock]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 15:06:37 GMT</pubDate>
            <atom:updated>2023-01-09T15:06:37.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mul-HvDYWQQzwEpsjY7lQA.png" /></figure><h3>What is Amazon DynamoDB?</h3><p>Amazon DynamoDB is a fully managed, serverless, key-value NoSQL database designed to run high-performance applications at any scale. DynamoDB offers built-in security, continuous backups, automated multi-Region replication, in-memory caching, and data import and export tools.<a href="https://aws.amazon.com/dynamodb/"><em>(source)</em></a></p><h3>Prerequisites:</h3><p>— Basic Linux CLI AWS commands</p><p>— Basic knowledge and understanding of the AWS Console</p><p>— Understanding of how to launch an EC2 instance with internet access (VPC, Internet gateway, route tables, etc.)</p><p>— Understanding of how to SSH into an EC2 instance from the CLI</p><h3>Objectives:</h3><ol><li>Create a DynamoDB table for something of your choosing (e.g. movies, food, games)</li><li>Add 10 or more items to the table</li><li>Create a t.2micro Ec2 instance</li><li>Using an IAM role and the principle of least privilege, grant the EC2 instance read access to DynamoDB.</li><li>Use the AWS CLI in the EC2 instance to scan the DynamoDB table</li><li>Use the AWS CLI in the EC2 instance to validate you cannot write an item to the DynamoDB table</li></ol><h3><strong>Create an Amazon DynamoDB table</strong></h3><p>We will start by navigating to <strong>AWS Console Home</strong> and then click over to the <strong>DynamoDB</strong> page and click <strong>“Create Table”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRv540l9LdDqrLFJESr6Jw.png" /><figcaption>Amazon DynamoDB</figcaption></figure><p>Enter a name for the table, I will use “Smartphone-table”, and then enter a <strong>Partition key.</strong> I will use “Smartphone Brand” and string value. Then enter a <strong>Sort key</strong>, I will use “Model” and string value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIpaQ5AHHHpnKaAaEaNTaw.png" /></figure><p>Scroll down to <strong>Table Settings,</strong> for this table we can use the <strong>default</strong> settings. Scroll down to the bottom of the page and click <strong>“create table”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2P4CT48hAdylSD0CFW7qw.png" /></figure><p>Once the table is created, select the table then click <strong>actions</strong>, and from the drop down menu click on <strong>explore items</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mq4cUcWMfOdjKj8Lq6NsRg.png" /></figure><p>Now we will begin entering our items into the table. Click <strong>create item</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZgnQ7-cF0gNYUEh7yFOfA.png" /></figure><p>Enter the data for each line and then click <strong>create item</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjTSPVf5wwR8bp2T1bXOOA.png" /></figure><p>We will repeat this process until we have atleast 10 items in the table. Once the table is completed, we will get an EC2 instance started so we can accomplish the rest of the objectives.</p><h3>IAM Roles with an EC2 instance</h3><p>Start by spinning up an EC2 instance, if you need help starting an instance, use this article as a reference: <a href="https://medium.com/@ryan.a.adcock/how-to-create-launch-an-amazon-ec2-instance-set-security-policies-access-the-instance-via-ssh-3c072988fe73">EC2 Instance</a></p><p>While the instance is launching, we will use an IAM role and the principle of least privilege, grant the EC2 instance <strong><em>read-only</em></strong> access to DynamoDB. For that, we will navigate over to the <strong>IAM</strong> page, then click <strong>“roles”</strong> on the left side of the page, and then <strong>“create role.</strong> Select <strong>AWS service</strong> and then for <strong>Use case</strong>, we will use <strong>EC2. </strong>Then click <em>next.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3VN3Ay7g06TWx33bQHznA.png" /></figure><p>We are looking to grant the EC2 instance the ability to read the DynamoDB table with no other permissions, so <em>read-only</em>. Enter <strong>“dynamodb”</strong> into the search bar, then select the <strong>AmazonDynamoDBReadOnlyAccess</strong> policy and click <em>next</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8yQyUrk6dQpcNmgFLfWpw.png" /></figure><p>Give the role a name and then scroll to the bottom of the page and click <strong>Create Role.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oeSWqvMo9g1rBRfn0Ck1cg.png" /></figure><p>Now we need to assign this new role to the EC2 instance we launched earlier. Go to <strong>EC2 &gt; instance </strong>select the instance, then click <strong>actions</strong>, from the drop down menu click <strong>security</strong>, then click <strong>modify IAM role.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hzom5q0_4MKeSTRM9ZbyNg.png" /></figure><p>Then select the role from the drop down menu and then click <strong>update IAM role</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hq6RTYm46RWszB_HL0Oag.png" /></figure><h3>CLI</h3><p>We will now use the CLI to SSH into the instance. If you need help, use this article as a reference: <a href="https://medium.com/@ryan.a.adcock/how-to-create-launch-an-amazon-ec2-instance-set-security-policies-access-the-instance-via-ssh-3c072988fe73">SSH into EC2</a>.</p><p>Once you are logged into the instance, we want to use the CLI to verify that the instance has the ability to read the items in the DynamoDB table we created. First, we must run a command to configre AWS on the instance. Run:</p><pre>$ aws configure<br>AWS Access Key ID [None]:<br>AWS Secret Access Key [None]:<br>Default region name [us-east-1]:<br>Default output format [None]:</pre><p>Make sure your region is the same as the instance, <strong>us-east-1</strong>. The rest of the settings can be blank by pressing <strong>“Enter”</strong> to skip them.</p><p>Now that we have configured AWS, let’s verify if the instance can read the DynamoDB table. In order to do this, we will run the following command:</p><pre>$ aws dynamodb scan --table-name Smartphone-table</pre><p>You should see the output of the table similar to below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3g_FvF2p-WHEAWb_asDHQ.png" /></figure><p>Success! The EC2 Instance has the ability to read the DynamoDB table. Now let’s verify that we can’t add an item to the table. To test this we will run a command in an attempt to add an item to the table. To do this, we will run the <strong>“put-item” </strong>command:</p><pre>$ aws dynamodb put-item --table-name Smartphone-table --item &#39;{&quot;Smartphone Brand&quot;: {&quot;S&quot;: &quot;Apple&quot;}, &quot;Model&quot;: {&quot;S&quot;: &quot;iPhone12&quot;}}&#39;</pre><p>Here is the output received:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEnQk-6ZtEXdultPBDrISg.png" /></figure><p>An error has occured, we were not able to add an item to the table. Success, that’s the result we expected to received showing our IAM role policy is working as intended! We have created an EC2 instance that has an IAM role that allows read-only access to our Amazon DynamoDB table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LqqALymhhTT7HMxrPVX-qA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c35f938794d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>