<?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 Jubril Adeyi on Medium]]></title>
        <description><![CDATA[Stories by Jubril Adeyi on Medium]]></description>
        <link>https://medium.com/@jubril___?source=rss-6b66476f74e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VEPE58_u_bQkw5MnZV2mKA.jpeg</url>
            <title>Stories by Jubril Adeyi on Medium</title>
            <link>https://medium.com/@jubril___?source=rss-6b66476f74e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:34:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jubril___/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[Automating Infrastructure Provisioning on AWS and System Configuration using Terraform and Ansible…]]></title>
            <link>https://awstip.com/automating-infrastructure-provisioning-on-aws-and-system-configuration-using-terraform-and-ansible-a44a833cd001?source=rss-6b66476f74e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a44a833cd001</guid>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Jubril Adeyi]]></dc:creator>
            <pubDate>Thu, 25 May 2023 14:42:42 GMT</pubDate>
            <atom:updated>2023-07-03T15:11:23.038Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating Infrastructure Provisioning on AWS and System Configuration using Terraform and Ansible: streamlining Infrastructure Deployment and Management.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*henTPXXNENyjpFImeSDG0g@2x.jpeg" /></figure><h3>Introduction</h3><p>Infrastructure as code (IaC) Is a pivotal aspect of modern DevOps practices, playing a major role in the efficiency of automated provisioning of cloud infrastructure. It provides an alternative to the tedious process of manually provisioning infrastructure from scratch, allowing streamlined modifications to cloud infrastructure.</p><p>This also aligns perfectly with the principles of cloud computing and DevOps, delivering accelerated provisioning, cost savings, and numerous other advantages.</p><p><strong>Key Advantages of IaC over Manual Provisioning</strong></p><ol><li>Scalability</li><li>Reproducibility</li><li>Version Control</li><li>Cost Savings</li><li>Collaboration and sharing</li><li>Error Reduction</li><li>Infrastructure As Documentation</li></ol><p>Just as the name implies, Infrastructure as Code (IaC) simplifies the provisioning of infrastructure using lines of code, eliminating the need for manual provisioning through the console or web-based user interfaces of cloud providers.</p><p>This shift towards code-based provisioning is a significant milestone in the history of cloud computing and DevOps practices, and there are a number of tools and technologies used for provisioning infrastructure as code, including Terraform, Ansible, Chef &amp; Puppet, and AWS CloudFormation.</p><h3>Overview</h3><p>In this article, we will explore the process of provisioning infrastructure on AWS using Terraform as our infrastructure-as-code tool. Our infrastructure setup will include a VPC network, multiple EC2 instances, a load balancer, and AWS Route53 for DNS management.</p><p>Additionally, we will use Ansible for system configuration to set up web servers on these instances, allowing us to test the functionality of the load balancer.</p><h3>Prerequisites</h3><ol><li>AWS Account</li><li>AWS IAM user</li><li>Terraform</li><li>Ansible</li></ol><h3>Provisioning Infrastructure Using Terraform</h3><p>In this section, we’ll be walking through the process of provisioning our Infrastructure on AWS using Terraform. We will walk through each step of the process; Initializing Terraform, Creating VPC network and Security groups, Launching EC2 Instances, Configuring Load Balancer, and Route53 for DNS management.</p><h4><strong>Initializing Terraform</strong></h4><p>We will start by setting up Terraform and initializing it with the necessary configurations. This includes defining the providers, Specifying the AWS IAM credentials, and configuring the backend for storing <a href="https://spacelift.io/blog/terraform-state">state Information </a>Using AWS S3 for state files and DynamoDB for state lock.</p><p><em>Storing the Terraform state information in a backend, such as AWS S3 and DynamoDB is done to enable collaboration and facilitate the management of infrastructure as code in a team setting. The backend is a central store of terraform state files.</em></p><p><strong>STEP 1: </strong>Create the terraform files for backend configuration, these files will be in a subdirectory (backend) in the main working directory.</p><ul><li>Create a subdirectory for backend terraform files.</li></ul><pre>mkdir backend<br>cd backend </pre><ul><li>Create ‘main.tf’ file.</li></ul><pre>provider &quot;aws&quot; {<br>  access_key = var.access_key<br>  secret_key = var.secret_key<br>  region     = var.region<br>}<br><br>resource &quot;aws_s3_bucket&quot; &quot;tf_backend_bucket&quot; {<br>  bucket = var.bucket_name<br>  acl    = &quot;private&quot;<br><br>  tags = {<br>    Name        = &quot;My bucket&quot;<br>    Environment = &quot;Dev&quot;<br>  }<br><br>  versioning {<br>    enabled = true<br>  }<br><br>  server_side_encryption_configuration {<br>    rule {<br>      apply_server_side_encryption_by_default {<br>        sse_algorithm = &quot;AES256&quot;<br>      }<br>    }<br>  }<br><br>  lifecycle {<br>    prevent_destroy = false<br>  }<br><br>}<br><br># DynamoDb for state file locking<br><br>resource &quot;aws_dynamodb_table&quot; &quot;terraform-state-lock&quot; {<br>  name         = var.dynamo-db-name<br>  hash_key     = &quot;LockID&quot;<br>  billing_mode = &quot;PAY_PER_REQUEST&quot;<br><br>  attribute {<br>    name = &quot;LockID&quot;<br>    type = &quot;S&quot;<br>  }<br>}</pre><ul><li>Create a variable.tf file for the backend; this will contain our AWS IAM credentials and names of the S3 bucket and DynamoDB, all assigned to terraform variables.</li></ul><pre><br>variable &quot;access_key&quot; {<br>  type    = string<br>  default = &quot;&quot;<br>}<br>variable &quot;secret_key&quot; {<br>  type    = string<br>  default = &quot;&quot;<br>}<br>variable &quot;region&quot; {<br>  type    = string<br>  default = &quot;us-east-1&quot;<br>}<br>variable &quot;bucket_name&quot; {<br>  type    = string<br>  default = &quot;terra-tfstate-2228&quot;<br>}<br>variable &quot;dynamo-db-name&quot; {<br>  type    = string<br>  default = &quot;terra-statelock-2228&quot;<br>}</pre><p><strong>STEP 2:</strong> Now execute the ‘terraform init’ command in the /backend directory to Initialize Terraform; This installs all plugins required for interacting with the AWS Infrastructure provider.</p><pre>terraform init</pre><p><strong>STEP 3: </strong>Execute the ‘terraform apply’ command in the /backend directory to create the S3 bucket and DynamoDB on AWS.</p><pre>terraform apply </pre><ul><li>The already configured backend can now be invoked for use while provisioning our infrastructure, lets name this file backend.tf and save it in our working directory.</li></ul><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;terra-tfstate-2228&quot;<br>    key            = &quot;global/infrastructure/terraform.tfstate&quot;<br>    region         = &quot;us-east-1&quot;<br>    dynamodb_table = &quot;terra-statelock-2228&quot;<br>    encrypt        = true<br>  }<br>}</pre><h4>Provisioning VPC network and security groups</h4><p>Before proceeding with the provisioning of servers and other resources, we will create and customize a VPC network and security group for the rest of our infrastructure. The VPC network serves as a foundation for the rest of our infrastructure and provides isolation and network connectivity for our resources, and the security group controls the traffic in and out of our EC2 instances.</p><p><strong>STEP 1</strong>: Create a variable.tf file in main working directory and set the required variables and values required for VPC configuration.</p><ul><li>Create variable.tf.</li></ul><pre>touch variable.tf </pre><ul><li>Open the ‘variables.tf’ file in text editor.</li><li>Add the following terraform scripts that defines the variables for VPC configuration and Security. Including AWS region, CIDR blocks, and subnets for VPC configuration and Inbound ports for the security group configuration:</li></ul><pre># // VPC variables  <br><br>variable &quot;aws_region&quot; {<br>  type        = string<br>  default     = &quot;us-east-1&quot;<br>  description = &quot;AWS region&quot;<br>}<br><br>variable &quot;cidr_blocks&quot; {<br>  type        = string<br>  default     = &quot;10.0.0.0/16&quot;<br>  description = &quot;vpc CIDR blocks&quot;<br>}<br>variable &quot;subnets&quot; {<br>  type = map(any)<br>  default = {<br>    subnet-a = {<br>      az   = &quot;use1-az1&quot;<br>      cidr = &quot;10.0.1.0/24&quot;<br>    }<br>    subnet-b = {<br>      az   = &quot;use1-az2&quot;<br>      cidr = &quot;10.0.2.0/24&quot;<br>    }<br>    subnet-c = {<br>      az   = &quot;use1-az3&quot;<br>      cidr = &quot;10.0.3.0/24&quot;<br>    }<br>  }<br><br>}<br><br># // security group variables <br><br>variable &quot;inbound_ports&quot; {<br>  type        = list(number)<br>  default     = [80, 22]<br>  description = &quot;ports for inbound rules&quot;<br>}</pre><p><strong>STEP 2</strong>: Create a vpc.tf file to define the Terraform script that creates and configures your VPC network, creates subnets, defines an Internet Gateway, and sets up route tables.</p><ul><li>Create vpc.tf file in main working directory.</li></ul><pre>touch vpc.tf </pre><ul><li>Open vpc.tf in text editor</li><li>Add the following terraform scripts to define our VPC configuration:</li></ul><pre>// CREATE VPC <br><br>resource &quot;aws_vpc&quot; &quot;server-vpc&quot; {<br>  cidr_block       = var.cidr_blocks<br>  instance_tenancy = &quot;default&quot;<br>  enable_dns_hostnames = true<br><br>  tags = {<br>    Name = &quot;server-vpc&quot;<br>  }<br>}</pre><pre>// DEFINE SUBNETS <br><br>resource &quot;aws_subnet&quot; &quot;server-subnets1&quot; {<br>  vpc_id               = aws_vpc.server-vpc.id<br>  cidr_block           = &quot;10.0.1.0/24&quot;<br>  availability_zone_id = &quot;use1-az1&quot;<br>}<br><br>resource &quot;aws_subnet&quot; &quot;server-subnets2&quot; {<br>  vpc_id               = aws_vpc.server-vpc.id<br>  cidr_block           = &quot;10.0.2.0/24&quot;<br>  availability_zone_id = &quot;use1-az2&quot;<br>}<br><br>resource &quot;aws_subnet&quot; &quot;server-subnets3&quot; {<br>  vpc_id               = aws_vpc.server-vpc.id<br>  cidr_block           = &quot;10.0.3.0/24&quot;<br>  availability_zone_id = &quot;use1-az3&quot;<br>}</pre><pre>// CREATE INTERNET GATEWAY <br><br>resource &quot;aws_internet_gateway&quot; &quot;gw&quot; {<br>  vpc_id = aws_vpc.server-vpc.id<br><br>  tags = {<br>    Name = &quot;server-gw&quot;<br>  }<br>}</pre><pre>// CREATE INTERNET GATEWAY<br> <br>resource &quot;aws_route_table&quot; &quot;server-rt&quot; {<br>  vpc_id = aws_vpc.server-vpc.id<br><br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.gw.id<br>  }<br><br>  tags = {<br>    Name = &quot;server-rt&quot;<br>  }<br>}<br><br>//  ROUTE TABLE ASSOCIATIONS<br><br>resource &quot;aws_route_table_association&quot; &quot;subnet1_rt&quot; {<br>  subnet_id = aws_subnet.server-subnets1.id<br>  route_table_id = aws_route_table.server-rt.id<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;subnet2_rt&quot; {<br>  subnet_id = aws_subnet.server-subnets2.id<br>  route_table_id = aws_route_table.server-rt.id<br>}<br>resource &quot;aws_route_table_association&quot; &quot;subnet3_rt&quot; {<br>  subnet_id = aws_subnet.server-subnets3.id<br>  route_table_id = aws_route_table.server-rt.id<br>}</pre><p><strong>STEP 3:</strong> Create a sg.tf file to define the terraform scripts that creates our security groups. We’ll be creating two security groups; a security group for our load balancer and one for our EC2 Instances.</p><ul><li>Create sg.tf file.</li></ul><pre>touch sg.tf </pre><ul><li>Open sg.tf file in text editor</li><li>Add the following terraform scripts to define our security groups:</li></ul><pre>// Load balancer security group <br><br>resource &quot;aws_security_group&quot; &quot;lb-sg&quot; {<br>  name        = &quot;lb-sg&quot;<br>  description = &quot;Allow TLS inbound traffic&quot;<br>  vpc_id      = aws_vpc.server-vpc.id<br><br><br>  ingress {<br>    description = &quot;inbound traffic for http&quot;<br>    from_port   = var.inbound_ports[0]<br>    to_port     = var.inbound_ports[0]<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<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>// Security group for EC2 Instances <br><br>resource &quot;aws_security_group&quot; &quot;servers-sg&quot; {<br>  name        = &quot;servers-sg&quot;<br>  description = &quot;Allow TLS inbound traffic&quot;<br>  vpc_id      = aws_vpc.server-vpc.id<br><br><br>  ingress {<br>    description = &quot;inbound traffic for SSH&quot;<br>    from_port   = var.inbound_ports[1]<br>    to_port     = var.inbound_ports[1]<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  ingress {<br>    description     = &quot;inbound traffic for HTTP&quot;<br>    from_port       = var.inbound_ports[0]<br>    to_port         = var.inbound_ports[0]<br>    protocol        = &quot;tcp&quot;<br>    security_groups = [aws_security_group.lb-sg.id]<br>  }<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>We can now Proceed to provisioning then rest our infrastructure, executing the ‘terraform apply’ command here provisions our VPC network and our security groups.</p><h4>Provisioning EC2 Instances</h4><p>For this task, we will provision three EC2 instances within our VPC network.</p><p><strong>STEP 1</strong>: Add variables and values for our EC2 instances to the variables.tf file, including the resource ID for an Amazon Machine Image (AMI) and the name of an SSH key pair.</p><p>You can create an AMI and EC2 SSH key pair on the AWS console, and these resources can be used in our Terraform scripts for provisioning EC2 instances.</p><p><em>Note: Make sure the SSH key pair (.pem) file is downloaded and saved in the working directory, it will be subsequently required for SSH access to our instances when using ansible.</em></p><ul><li>Open variables.tf file in text editor</li><li>Add the following terraform scripts to the variables.tf file to define variables for provisioning our EC2 Instances.</li></ul><pre>// EC2 varaibles<br><br>variable &quot;ec2_ami&quot; {<br>  type        = string<br>  default     = &quot;ami-09c583d8b568a9722&quot;<br>  description = &quot;machine image for instance&quot;<br>}<br>variable &quot;key_pem&quot; {<br>  type        = string<br>  default     = &quot;key&quot;<br>  description = &quot;SSH Key&quot;<br>}</pre><p><strong>STEP 2</strong>: Create an ec2.tf file to provision 3 EC2 instances. Instance type, SSH key, and other features will be defined in this Terraform script.</p><ul><li>Create ec2.tf file in main working directory.</li></ul><pre>touch ec2.tf </pre><ul><li>Add the following script to create and configure our EC2 Instances</li></ul><pre>resource &quot;aws_instance&quot; &quot;server&quot; {<br>  count = 3<br><br>  ami           = var.ec2_ami<br>  instance_type = &quot;t2.micro&quot;<br><br>  tags = {<br>    Name = &quot;server-${count.index}&quot;<br>  }<br>  vpc_security_group_ids      = aws_security_group.server-sg.id<br>  associate_public_ip_address = true<br>  subnet_id                   = aws_subnet.server-subnets1.id<br>  key_name                    = var.key_pem</pre><p>With the ec2.tf file now in place you can proceed to execute the terraform commands to provision the EC2 instance based on the defined script</p><h4>Provisioning Load Balancer</h4><p>Now that we have created our EC2 instances, we can proceed to provisioning our load balancer. We will provision an Application Load Balancer using the AWS Elastic Load Balancer service. The load balancer will be configured to distribute traffic across our 3 EC2 instances based on availability. Let’s dive in.</p><p><strong>STEP 1</strong>: Add variables and corresponding values for provisioning the load balancer to the variables.tf file in the main working directory. These variables will include the listener protocol, listener port, and other values required for configuring the load balancer.</p><ul><li>Open the variables.tf file in text editor.</li><li>Add the following Terraform code to define the variables.</li></ul><pre>// Load balancer Variables <br><br>variable &quot;port&quot; {<br>  type    = number<br>  default = 80<br>}<br>variable &quot;protocol&quot; {<br>  type    = string<br>  default = &quot;HTTP&quot;<br>}<br><br>variable &quot;health_check&quot; {<br>  type = map(string)<br>  default = {<br>    &quot;interval&quot;            = &quot;300&quot;<br>    &quot;path&quot;                = &quot;/&quot;<br>    &quot;timeout&quot;             = &quot;60&quot;<br>    &quot;matcher&quot;             = &quot;200&quot;<br>    &quot;healthy_threshold&quot;   = &quot;5&quot;<br>    &quot;unhealthy_threshold&quot; = &quot;5&quot;<br>  }<br>}<br>variable &quot;listener_port&quot; {<br>  type    = number<br>  default = 80<br>}<br>  <br>variable &quot;listener_protocol&quot; {<br>  type    = string<br>  default = &quot;HTTP&quot;<br> <br>}</pre><p>With the variables defined we can now proceed to provisioning our load balancer, using these variables.</p><p><strong>STEP 2</strong>: Create the lb.tf file to provision our load balancer. In this Terraform script, we will create a load balancer, a target group, and define listeners for our load balancer.</p><p>To create the lb.tf file and define the terraform scripts follow these steps:</p><ul><li>Create a file named lb.tf</li></ul><pre>touch lb.tf </pre><ul><li>Add the following script to lb.tf to provision the load balancer:</li></ul><pre>// create load balancer<br> <br>resource &quot;aws_lb&quot; &quot;server-lb&quot; {<br>  name                       = &quot;server-lb&quot;<br>  internal                   = false<br>  load_balancer_type         = &quot;application&quot;<br>  security_groups            = [aws_security_group.lb-sg.id]<br>  subnets                    = [aws_subnet.server-subnets2.id, aws_subnet.server-subnets1.id]<br>  enable_deletion_protection = false<br>}<br><br>// create target group <br><br>resource &quot;aws_lb_target_group&quot; &quot;server-tg&quot; {<br>  name        = &quot;server-tg&quot;<br>  target_type = &quot;instance&quot;<br>  port        = var.port<br>  protocol    = var.protocol<br>  vpc_id      = var.vpc_id<br><br>  health_check {<br>    enabled             = true<br>    interval            = var.health_check[&quot;interval&quot;]<br>    path                = var.health_check[&quot;path&quot;]<br>    timeout             = var.health_check[&quot;timeout&quot;]<br>    matcher             = var.health_check[&quot;matcher&quot;]<br>    healthy_threshold   = var.health_check[&quot;healthy_threshold&quot;]<br>    unhealthy_threshold = var.health_check[&quot;unhealthy_threshold&quot;]<br>  }<br>}<br><br><br><br>// Add a listener<br>resource &quot;aws_lb_listener&quot; &quot;lb-listener&quot; {<br>  load_balancer_arn = aws_lb.server-lb.arn<br>  port              = var.listener_port<br>  protocol          = var.listener_protocol<br><br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.server-tg.arn<br>  }<br>}</pre><p>With the lb.tf file in place we can now proceed to executing terraform commands to provision our load balancer based on the terraform script.</p><h4>Provisioning AWS Route53 service</h4><p>We will be provisioning the Route53 service to provide a custom DNS name to route traffic into the load balancer. This will include creating a hosted zone and adding a record to the hosted zone.</p><p><strong>STEP 1: </strong>Add the required variables for the Route53 service to the main variables.tf file.</p><ul><li>Add the following terraform script to the main variables.tf file:</li></ul><pre>// ROUTE53 variables <br><br>variable &quot;domain_name&quot; {<br>  type    = string<br>  default = &quot;&lt;YOUR DNS&gt;&quot;<br>}<br>variable &quot;sub_domain_name&quot; {<br>  type    = string<br>  default = &quot;terraform-infra&quot;<br><br>}</pre><ul><li>Create a route53.tf file.</li></ul><pre>touch route53.tf</pre><ul><li>Add the following terraform script to this file:</li></ul><pre>//hosted zone<br>resource &quot;aws_route53_zone&quot; &quot;hosted_zone&quot; {<br>  name = var.domain_name<br>}<br><br>//set record in the hosted zone <br>resource &quot;aws_route53_record&quot; &quot;record&quot; {<br>  zone_id = aws_route53_zone.hosted_zone.zone_id<br>  name    = var.sub_domain_name<br>  type    = &quot;A&quot;<br><br>  alias {<br>    name                   = aws_lb.server-lb.dns<br>    zone_id                = aws_lb.server-lb.zone_id<br>    evaluate_target_health = true<br>  }<br>}</pre><p>Now our load balancer can be accessed via our configured Route53 DNS</p><h4><strong>Attaching EC2 instances to Target group</strong></h4><p>Now we need to attach our EC2 instances to our already provisioned target group, this indirectly connects our Instances the load balancer.</p><p>To attach the instances to our load balancer, follow these steps.</p><ul><li>Create a tg-attach.tf file.</li></ul><pre>touch tg-attach.tf </pre><ul><li>Add the following terraform scripts to tg-attach.tf file:</li></ul><pre>resource &quot;aws_lb_target_group_attachment&quot; &quot;tg-attach1&quot; {<br>  target_group_arn = aws_lb_target_group.server-tg.arn<br>  target_id        = aws_instance.server[0].id<br>  port             = 80<br>}<br>resource &quot;aws_lb_target_group_attachment&quot; &quot;tg-attach2&quot; {<br>  target_group_arn = aws_lb_target_group.server-tg.arn<br>  target_id        = aws_instance.server[1].id<br>  port             = 80<br>}<br>resource &quot;aws_lb_target_group_attachment&quot; &quot;tg-attach3&quot; {<br>  target_group_arn = aws_lb_target_group.server-tg.arn<br>  target_id        = aws_instance.server[2].id<br>  port             = 80<br>}</pre><p>Executing our ‘’terraform apply’ command here finalizes the provisioning of all our Infrastructure.</p><p>We have now created our VPC network, EC2 Instances, Route53 service and set up our load balancer with our instances attached to it using terraform as Infrastructure-as-code tool.</p><p>We can now proceed to System configuration on our infrastructure using Ansible, but first we will be using terraform to export the Ip addresses of our EC2 Instances into a host-inventory file in the main working directory.</p><ul><li>Create a host-inventory.tf file.</li></ul><pre>touch host-inventory.tf </pre><ul><li>Add the following terraform script to host-inventory.tf:</li></ul><pre>// export the ip addresses of instances into host-inventory file <br><br>resource &quot;local_file&quot; &quot;host-inventory&quot; {<br>  filename = &quot;host-inventory&quot;<br>  content = &lt;&lt;EOT<br>  ${aws_instance.server[0].public_ip}<br>  ${aws_instance.server[1].public_ip}<br>  ${aws_instance.server[2].public_ip}<br>    EOT<br>}<br></pre><ul><li>Execute the ‘terraform apply’ command to create host-inventory file.</li></ul><p>We can now proceed to system configuration.</p><h3>System Configuration Using Ansible</h3><p>In this section We will use Ansible to do some system configuration on our all of our servers (EC2 Instances). These configuration tasks will include Setting our Time zone, Installing and configuring Apache web server to display the Hostnames of each server.</p><p>To perform this system configuration on our servers using ansible, make sure Ansible is installed on your local machine. Let&#39;s dive right in.</p><p><strong>Step 1</strong>: Create the Ansible configuration file, ‘ansible.cfg’. This file will include the host inventory, private SSH key and other necessary parameters such as privilege escalations.</p><ul><li>Create a file named ‘ansible.cfg’ in your main working directory.</li><li>Add the following code to the ‘ansible.cfg’ file.</li></ul><pre>[defaults]<br>inventory         = host-inventory<br>remote_user       = ubuntu<br>host_key_checking = false<br>private_key_file  = key.pem<br><br>[privilege_escalation]<br>become        = yes<br>become_method = sudo</pre><p>Step 2: Create the Ansible playbook to perform system configuration tasks.</p><p>To create the playbook.yaml file and define the necessary tasks for system configuration, follow these steps:</p><ul><li>Create a file named ‘playbook.yaml’ in your main working directory.</li><li>Open the playbook.yaml file in a text editor.</li><li>Add the following tasks to perform system configuration:</li></ul><pre>---<br><br>- name: Install Apache2 and set timezone to Africa/Lagos<br>  hosts: all<br>  become: yes<br>  tasks:<br><br>  - name: update cache<br>    apt:<br>      update_cache: yes<br><br>  - name: Install Apache2    <br>    apt:<br>      name: apache2<br>      state: present<br><br>  - name: Set timezone to Africa/Lagos<br>    timezone:<br>      name: Africa/Lagos<br><br>  - name: Display hostname and date<br>    shell: echo &quot;&lt;h1&gt; hello world This is $(hostname -f) &lt;/h1&gt;&quot; &gt; /var/www/html/index.html<br>    notify: restart_apache<br><br>  handlers:<br>  - name: restart_apache<br>    systemd:<br>      name: apache2<br>      state: restarted</pre><p>Now we can the execute the ansible-playbook command to run the system configuration tasks on all three servers:</p><pre>ansible-playbook -i host-inventory playbook.yaml</pre><p>We have successfully provisioned infrastructure on AWS using Terraform and also performed system configuration on our servers using ansible.</p><h4>Summary</h4><ol><li>We started the process of provisioning infrastructure by initializing Terraform. This involved defining our selected provider as AWS, specifying IAM user credentials, and configuring a Terraform backend to store state files using AWS S3 storage and DynamoDB for state lock files.</li><li>We invoked our backend and proceeded to create and configure a VPC network using Terraform. Additionally, we created security groups that would be used to control traffic in and out of the servers and the load balancer.</li><li>After creating the VPC network, we proceeded to create our EC2 instances and load balancer. We ensured that the load balancer directs traffic to the servers by attaching the servers to a target group associated with the load balancer.</li><li>We then created a Route53 service on AWS and attached it to the load balancer DNS, providing a custom domain name and routing traffic to the load balancer.</li><li>Once we had our infrastructure fully provisioned, we exported the IP addresses of the servers into a host inventory file. This file would later be used by Ansible for system configuration.</li><li>Using Ansible for system configuration, we performed tasks such as setting the time zone on our servers and installing/configuring the Apache web server. This configuration allowed the web server to display the IP addresses of each server when accessed through the load balancer.</li></ol><p>Using infrastructure-as-code (IaC) streamlines the process of provisioning and modifying infrastructure. With minor changes to the infrastructure code, executing the ‘terraform apply’ command updates the infrastructure accordingly, while ‘terraform destroy’ completely removes it.</p><p>In this article, Ansible was used for minor system configuration tasks. For a more comprehensive exploration of complex system configuration using Ansible, please refer to my <a href="https://medium.com/@jubril___/deploying-laravel-application-on-a-remote-server-using-ansible-for-configuration-management-6c26531ad3d5">previous article</a>.</p><h3><strong>Resources</strong></h3><ul><li><a href="https://developer.hashicorp.com/terraform">Terraform Documentation</a></li><li><a href="https://spacelift.io/blog/terraform-state">Terraform State</a></li><li><a href="https://developer.hashicorp.com/terraform/language/settings/backends/s3">Terraform S3 Backend</a></li><li><a href="https://www.bing.com/ck/a?!&amp;&amp;p=75e193542f08214aJmltdHM9MTY4NDk3MjgwMCZpZ3VpZD0xYzdiZjhiZi1jYzZjLTZhMzUtM2Y5MS1lYTRlY2Q3MTZiNjEmaW5zaWQ9NTQ3OA&amp;ptn=3&amp;hsh=3&amp;fclid=1c7bf8bf-cc6c-6a35-3f91-ea4ecd716b61&amp;psq=aws+elastic+load+balancer&amp;u=a1aHR0cHM6Ly9hd3MuYW1hem9uLmNvbS9lbGFzdGljbG9hZGJhbGFuY2luZy8&amp;ntb=1">AWS Elastic load balancer</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route53_record">AWS Route53</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a44a833cd001" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/automating-infrastructure-provisioning-on-aws-and-system-configuration-using-terraform-and-ansible-a44a833cd001">Automating Infrastructure Provisioning on AWS and System Configuration using Terraform and Ansible…</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[Deploying Laravel application on a remote server using ansible for configuration management]]></title>
            <link>https://medium.com/@jubril___/deploying-laravel-application-on-a-remote-server-using-ansible-for-configuration-management-6c26531ad3d5?source=rss-6b66476f74e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c26531ad3d5</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Jubril Adeyi]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 11:48:09 GMT</pubDate>
            <atom:updated>2023-05-25T20:34:54.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*XVkgPKvwpqv1CV6P4LxFaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HY1N-hY0g0hfrE7FIoZfuA.jpeg" /></figure><h4>Introduction</h4><p>Automation is a key aspect of cloud computing and DevOps, allowing cloud engineers to make necessary installations and configurations on servers without having to work on them directly. With the help of tools like Ansible, the entire process of installing dependencies and setting up applications can be done remotely, streamlining the configuration process and making it more efficient.</p><h4><strong>WHAT IS ANSIBLE?</strong></h4><p><a href="https://www.ansible.com/">Ansible </a>is a powerful automation tool that is widely used in cloud computing and DevOps. It is Developed in Python and can be used for a variety of purposes, including configuration management, application deployment, and infrastructure as code. In this article, we’ll be exploring Ansible’s use as a configuration management tool, which allows management and automation of configuration of servers and applications using YAML files.</p><p>Ansible also allows you to limit access to the target server by only granting the necessary privileges to perform specific tasks, such as installing dependencies or modifying configuration files. This is important as a security consideration, as it allows you to control who can access and modify the server, reducing the risk of unauthorized access and unwanted system changes.</p><p>You may be wondering how Ansible is able to perform all these configurations completely remotely. Well, for an Ansible configuration, the working server just needs to have established SSH access to the remote server, and this is the channel through which all the configurations are made.</p><h3>Overview</h3><p>In this article, we’ll explore how to use Ansible to configure a remote server for hosting<a href="https://laravel.com/"> Laravel</a>.</p><p><em>Laravel is a PHP web application framework with powerful features such as routing, ORM, and templating engine. It is widely used to build scalable and maintainable web applications.</em></p><p>We will be using Apache as the web server and MySQL as the database for this application.</p><p>For this setup, Linux Ubuntu instances on AWS EC2 will be used as master and slave nodes/servers.</p><h3>Prerequisites:</h3><ul><li>An AWS account.</li><li>Two EC2 instances:</li></ul><ol><li>A slave (target) instance where the Laravel application and packages will be deployed.</li><li>A master instance, which will have Ansible installed on it and be granted SSH access to the slave instance.</li></ol><ul><li>Ansible Installed on the master instance.</li></ul><h4>Setting up AWS EC2 Instances</h4><p><strong>Step 1</strong>: Create a Security Group for the instances.</p><ul><li>Locate the EC2 dashboard on the AWS Console and select “Security Groups” under the Network &amp; Security section.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*lsjLuiuLgdMM5Qoi5pk6oQ.png" /></figure><ul><li>Click on “Create Security Group”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*d0tOio01QZf7MT2CFjZfug.png" /></figure><ul><li>Proceed to adding name, description (optional) for the security group and select the VPC this security group will be located in.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*7CVHSUYVNY2X7T-X15-0zQ.png" /></figure><ul><li>Modify the Inbound rules to allow Ports 22, 80 and 443 which will allow SSH access, HTTP connection and HTTPS connections respectively.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*njNDraRmdeXulqeGJV-FkQ.png" /></figure><ul><li>Set outbound rules to allow all traffic on all ports and finally click on “Create security group” and the security group has been created.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*LwY4plmgo0dWe2kvqqGJdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*ExE5k_r82R25YK96uBcL8Q.png" /></figure><p><strong>Step 2:</strong> Create an AWS SSH key pair.</p><ul><li>Locate “Key Pairs” in the Network and Security section on the EC2 dashboard and click on “Create key pair.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*OHKRe3NkAJaAHpwaf7mz6A.png" /></figure><ul><li>Proceed to Naming the key pair, select key pair type to be RSA and .pem Private key file format. Finally, click on “Create key pair.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*nvueftBlyuogcmxA6OgUfg.png" /></figure><blockquote>Note: .pem key pair file can be downloaded and used to ssh into the instance they’re attached to from your pc</blockquote><p><strong>Step 3</strong>: Create The AWS EC2 Instances</p><ul><li>Locate “Instances” on the EC2 dashboard. and click on “Launch instances.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*4Pm27O6FUjArMwmM7VFISw.png" /></figure><ul><li>Select the number of Instances, two since we’re creating just master and slave nodes for the ansible set up.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*o810ihSPufHefRuP78eBzA.png" /></figure><ul><li>We will be using the t2.micro instance type with an Ubuntu Linux 22.04 server.</li><li>Select the key pair created in the previous step.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*2KP6Ipzgl-TsRpVLA3g6_w.png" /></figure><ul><li>Enable Auto-assign public IP and select the security group created in the previous steps as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*wAbK2uAd9tCAWddtcfWq8Q.png" /></figure><ul><li>Now click on “Launch Instance” to finalize the creation of the instances.</li></ul><blockquote>Note: Both instances will be created inside the same VPC, will share the same security group and SSH key pair</blockquote><h4>Configuring the Master Node for Ansible</h4><p><strong>Step 1</strong>: SSH into the master node, Update package list and Install Ansible with the following commands.</p><pre>sudo apt update <br><br>sudo apt install ansible </pre><p><strong>Step 2: </strong>Create a working directory. This directory will house the ansible playbook and other necessary files. Also all the configuration and deployment will be done in this directory.</p><pre>mkdir Ansible <br><br>cd Ansible </pre><p><strong>Step 3</strong>: Create Host-inventory file and add slave node(s) IP address(es) in this file.</p><pre>touch host-inventory</pre><pre>[slave-nodes]<br>&lt; slave-node-ip-address &gt;</pre><p><em>The [slave-nodes] header is used to define a group of multiple hosts. “&lt; slave-ip-address &gt;” should be replaced with the public ip address of the slave node.</em></p><p><strong>Step 3</strong>: Create ansible.cfg file and specify the defaults and privilege escalations. This file controls how ansible will function, setting parameters such as path of the inventory file, default user and privileges.</p><pre>mkdir ansible.cfg</pre><pre>[defaults]<br>inventory         = host-inventory<br>remote_user       = ubuntu<br>private_key_file  = key.pem <br><br>[privilege_escalation]<br>become        = yes<br>become_method = sudo</pre><h4>Preparing Ansible Environment for Laravel deployment</h4><p><strong>Step 1</strong>: Create a variable file that will be used during the deployment process. To do this, we will be using the <a href="https://www.educba.com/ansible-group_vars/">Group_vars</a> system.</p><p>In the Group_vars directory, subdirectories will be created to represent specific groups of hosts as defined in the host-inventory file. These variables will apply only to the ip-addresses/hosts in this group. Each subdirectory will contain a YAML file (main.yaml) that declares variables and their values.</p><pre>mkdir Group_vars/slave-nodes/<br><br>cd Group_vars/slave-nodes/<br><br>touch  main.yaml</pre><p>Contents of the variable YAML file will include all the variables that will be used during the course of this deployment.</p><pre>laravel_app: &lt; name-for-laravel-app &gt;<br>mysql_username: &lt; mysql-username &gt;<br>servername: &lt; server-name or ip-address &gt;<br>sever_email: &lt; email-address &gt;<br>mysql_database_name: &lt; mysql-database-name &gt;<br>sever_admin: &lt; server-admin-email &gt;<br>server_name: &lt; server-name or ip-address &gt;<br>server_alias: &lt; server-alias &gt;</pre><p><strong>Step 2</strong>: Create an Ansible Vault;</p><p>Ansible Vault is used to securely store sensitive information such as passwords, API keys, and other secrets, we’ll create an Ansible Vault directory. This directory will contain a YAML that contains variables defined by encrypted values that we can reference in our playbooks.</p><pre>mkdir vault </pre><p>After creating a directory, vault in the working directory, run the following command to create the encrypted YAML file for your passwords:</p><pre>ansible-vault create /vault/db.yaml</pre><p>A new file db.yaml will be created in the vault directory and you’ll prompted to type a new vault password. Once password has been set, variables and values can be added to the encrypted YAML file.</p><pre>db_password : “ your-db-password ”</pre><p>Now, these values can be referenced in our playbook and our sensitive information can be called without exposing it in plain text.</p><p>Encrypted variables can be edited using this command:</p><pre>ansible-vault edit db.yml </pre><p>To run your ansible playbook commands whilst using the values defined in the encrypted ansible-vault file, the “ — ask-vault-pass” flag can be added like this:</p><pre>ansible-playbook -i host-inventory playbook.yaml —ask-vault-pass</pre><p>You will prompted for the vault password to run this command.</p><h4>Deploying Laravel using Ansible Roles</h4><p>Ansible roles is a feature in Ansible that allows users to organize tasks in a playbook into reusable units. A directory is created for each role, which contains subdirectories for tasks, templates, files, and handlers specific to that role. The main task playbook for each role is located in the tasks directory. This makes it easier to modify and maintain the playbook, especially in larger and more complex deployments.</p><p>The roles can then be called in the main playbook YAML file which will be located in the root working directory.</p><p><strong>Step 1: </strong>Create a roles directory in the root working directory and create a directory for each ansible role within the roles directory.</p><pre>mkdir roles</pre><p>For this deployment, we will section the tasks into eleven ansible roles:</p><ol><li>Install-packages</li><li>Install-mysql</li><li>Configure-mysql</li><li>Configure-mysql-user-database</li><li>Configure-firewall</li><li>Install-php</li><li>Install-setup-composer</li><li>Clone-laravel-repo</li><li>Configure-apache</li><li>Migrate-database</li><li>Install-setup-SSL</li></ol><ul><li><strong>Install-packages: </strong>This role Updates system packages on the slave node and installs the necessary packages required for this deployment using the apt module.</li></ul><pre>/roles/install-packages/tasks/main.yaml<br><br><br><br>- name: update &quot;apt&quot; <br>  apt: <br>   update_cache: yes <br>   autoclean: yes<br>   autoremove: yes <br>- name: install (git, wget, apache, ufw, unzip, curl)<br>  apt:<br>   pkg:<br>   - git<br>   - wget<br>   - apache2<br>   - ufw<br>   - unzip<br>   - curl</pre><ul><li><strong>Install-mysql</strong>: This role fully installs the MySQL package and all its dependencies.</li></ul><pre>/roles/Install-mysql/tasks/main.yaml<br><br>---<br><br><br><br>- name: install mysql-server<br>  apt: <br>    name: mysql-server<br>    state: present<br>- name: install mysql-client<br>  apt: <br>    name: mysql-client<br>    state: present<br>- name: install python3-pymysql<br>  apt: <br>    name: python3-pymysql<br>    state: present<br>- name: install python3-mysqldb<br>  apt: <br>    name: python3-mysqldb<br>    state: present<br>- name: install libmysqlclient-dev<br>  apt: <br>    name: libmysqlclient-dev<br>    state: present<br><br></pre><ul><li><strong>Configure-mysql: </strong>This role starts and enables the MySQL package on the slave node, flushes privileges, sets the root password and removes all anonymous user accounts.</li></ul><pre>/roles/Configure-mysql/tasks/main.yaml<br><br><br>- name: start and enable mysql service<br>  service:<br>    name: mysql<br>    state: started<br>    enabled: yes<br>- name: Change the auhentication plugin of mysql root user to mysql_native_password<br>  shell: mysql -u root -e &#39;UPDATE mysql.user SET plugin=&quot;mysql_native_password&quot; WHERE user=&quot;root&quot; AND host=&quot;localhost&quot;&#39;<br>- name: Flush Privileges<br>  shell: mysql -u root -e &#39;FLUSH PRIVILEGES&#39;<br>- name: Sets the root password<br>  mysql_user:<br>   login_host: &#39;localhost&#39;<br>   login_user: &#39;root&#39;<br>   login_password: &#39;&#39;<br>   name: root<br>   password: &quot;{{ mysql_root_password }}&quot;<br>   state: present<br>- name: Removes all anonymous user accounts<br>  mysql_user:<br>    name: &#39;&#39;<br>    host_all: yes<br>    state: absent<br>    login_user: root<br>    login_password: &quot;{{ mysql_root_password }}&quot;<br></pre><ul><li><strong>Configure-mysql-user-database</strong>: This role is responsible for Creating a MySQL user, creating a database and granting user all access and privileges to the database. Variables defined using our Group_vars system created earlier are used here, also some of encrypted values stored in our Ansible-vault are used called in the playbook as variables.</li></ul><pre>/roles/Configure-mysql-user-database/tasks/main.yaml<br><br><br>- name: Creates new user<br>  mysql_user:<br>    login_host: &#39;localhost&#39;<br>    name: &quot;{{ mysql_username }}&quot;<br>    password: &quot;{{ mysql_user_password }}&quot;<br>    state: present<br>    login_user: root<br>    login_password: &quot;{{ mysql_root_password }}&quot;<br>- name: Creates new database<br>  mysql_db:<br>    name: &quot;{{ mysql_database_name }}&quot;<br>    login_host: &#39;localhost&#39;<br>    state: present<br>    login_user: root<br>    login_password: &quot;{{ mysql_root_password }}&quot;<br>- name: Grants user  ALL access/privileges to database<br>  mysql_user:<br>    name: &quot;{{ mysql_database_name }}&quot;<br>    login_host: &#39;localhost&#39;<br>    state: present<br>    login_user: root<br>    login_password: &quot;{{ mysql_root_password }}&quot;<br>    priv: &#39;{{ mysql_database_name }}.*:ALL,GRANT&#39;</pre><ul><li><strong>Configure-firewall</strong>: This role configures the UFW firewall on the slave node to allow the necessary network traffic in and out of the server. This is so that the Firewall rules allow HTTP, HTTPS and MySQL traffic on the server level. This role does this by Creating UFW rules to allow traffic on ports 443, 80 and 3306.</li></ul><pre>/roles/Configure-firewall/tasks/main.yaml<br><br>---<br><br>- name: UFW - Allow HTTP on port 80<br>  ufw:<br>    rule: allow<br>    port: &quot;80”<br>- name: UFW -  Allow HTTPS<br>  ufw:<br>    rule: allow<br>    port: &quot;443&quot;<br><br>- name: UFW -  Allow  Mysql<br>  ufw:<br>    rule: allow<br>    port: 3306</pre><ul><li><strong>Install-php</strong>: This role installs the PHP packages on the slave node.</li></ul><pre>/roles/Install-php/tasks/main.yaml<br><br>- name: Add php repository <br>  apt_repository:<br>   repo: &#39;ppa:ondrej/php&#39;<br>- name: Updating the repo<br>  apt: update_cache=yes <br>- name: Install PHP <br>  apt: name=php8.1 state=latest<br>- name: Install PHP MB<br>  apt: name=php8.1-mbstring state=latest  <br>- name: Install PHP XML<br>  apt: name=php8.1-xml state=latest   <br>- name: Install PHP ZIP<br>  apt: name=php8.1-zip state=latest<br>- name: Install PHP CURL<br>  apt: name=php8.1-curl state=latest <br>- name: Install libapache2-mod-php<br>  apt: name=libapache2-mod-php state=latest  <br>- name: PHP DEV<br>  apt: name=php8.1-dev state=latest<br>- name: PHP mysql<br>  apt: name=php8.1-mysql state=latest <br>- name: PHP  XMLRPC<br>  apt: name=php8.1-xmlrpc state=latest<br>- name: PHP  DEV<br>  apt: name=php8.1-dev state=latest<br>- name: PHP common<br>  apt: name=php8.1-common state=latest<br>- name: PHP gd<br>  apt: name=php8.1-gd state=latest<br>- name: PHP imagick<br>  apt: name=php8.1-imagick state=latest<br>- name: PHP CLI<br>  apt: name=php8.1-cli state=latest<br>- name: PHP imap<br>  apt: name=php8.1-imap state=latest<br>- name: PHP intl<br>  apt: name=php8.1-intl state=latest<br>- name: Install some required softwares for php functionality<br>  apt: <br>    name: <br>      - ca-certificates<br>      - apt-transport-https<br>      - software-properties-common<br>      - lsb-release <br>    state: latest<br>    update_cache: true<br></pre><ul><li><strong>Install-setup-composer</strong>: This role installs the Composer package. It does this by downloading the installer file, installing it and making it executable. Composer is a dependency manager for PHP that is required to install and manage Laravel dependencies.</li></ul><pre>/roles/install-setup-composer/tasks/main.yaml<br><br><br><br>- name: Dowload php-composer<br>  get_url: <br>   url: https://getcomposer.org/installer<br>   dest: /tmp/installer<br>- name: verify installatiion script is safe <br>  command: php -r &quot;if (hash_file(&#39;sha384&#39;, &#39;composer-setup.php&#39;) === &#39;55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae&#39;) { echo &#39;Installer verified&#39;; } else { echo &#39;Installer corrupt&#39;; unlink(&#39;composer-setup.php&#39;); } echo PHP_EOL;&quot;<br><br>- name: Install composer<br>  command: php /tmp/installer  --install-dir=/usr/local/bin/ --filename=composer<br>  args: <br>    creates: /usr/local/bin/composer <br><br>- name: rename composer.phar to composer<br>  shell: mv /usr/local/bin/composer.phar /usr/local/bin/composer<br>  args:<br>    creates: /usr/local/bin/composer<br><br>- name: Make composer executable <br>  file: <br>     path: /usr/local/bin/composer<br>     mode: a+x<br>     state: file<br></pre><ul><li><strong>Clone-laravel-repo: </strong>This<strong> </strong>role simply clones a github repository that contains the Laravel application onto the slave node.</li></ul><pre>/roles/Clone-laravel-repo/tasks/main.yaml<br><br>- name: Clone  github repository<br>  git:<br>    repo: https://github.com/f1amy/laravel-realworld-example-app.git<br>    dest: /var/www/{{ laravel_app }}<br>    clone: yes<br>    update: no</pre><ul><li><strong>Configure-apache</strong>: This role is responsible for Configuring Apache webserver on the slave node. This role consists of several directories which include files, handlers, templates and the task directory. The files directory contains all the necessary files for this role, the handlers directory contains defined handlers, and the templates directory contains templates referenced in the main task YAML. This role performs tasks that includes moving the Laravel app files into the /var/www/html directory for Apache, setting up virtual hosts, enabling necessary modules, and restarting Apache service.</li></ul><pre>roles/Configure-apache/files/.htaccess<br><br>&lt;IfModule mod_rewrite.c&gt;<br>  RewriteEngine On<br><br>  RewriteCond %{REQUEST_URI} !^/public/<br>  RewriteCond %{REQUEST_FILENAME} !-d<br>  RewriteCond %{REQUEST_FILENAME} !-f<br><br>  RewriteRule ^(.*)$ /public/$1<br>  RewriteRule ^(.*)?$ public/index.php [L]<br>&lt;/IfModule&gt;</pre><pre>roles/Configure-apache/templates/.web.php<br><br>&lt;?php<br><br>use Illuminate\Support\Facades\Route;<br><br>/*<br>|--------------------------------------------------------------------------<br>| Web Routes<br>|--------------------------------------------------------------------------<br>|<br>| Here is where you can register web routes for your application. These<br>| routes are loaded by the RouteServiceProvider within a group which<br>| contains the &quot;web&quot; middleware group. Now create something great!<br>|<br>*/<br><br>Route::get(&#39;/&#39;, function () {<br>    return view(&#39;welcome&#39;);<br>});<br><br></pre><pre>/roles/Configure-apache/templates/web.conf.j2<br><br>&lt;VirtualHost *:80&gt;<br>     ServerAdmin {{ sever_admin }}<br>     ServerName {{ server_name }}<br>     ServerAlias {{ server_alias }}<br><br>     DocumentRoot /var/www/html/{{ laravel_app }}/<br><br>     &lt;Directory /var/www/html/{{ laravel_app }}&gt;<br>         Options Indexes FollowSymLinks<br>         AllowOverride All<br>         Require all granted<br>     &lt;/Directory&gt;<br><br>     ErrorLog ${APACHE_LOG_DIR}/error.log<br>     CustomLog ${APACHE_LOG_DIR}/access.log combined<br> &lt;/VirtualHost&gt;<br></pre><pre>roles/Configure-apache/tasks/main.yaml<br><br>- name: Copy laravel project <br>  shell: sudo mv /var/www/{{ laravel_app }} /var/www/html<br><br>- name: Change permission<br>  shell: sudo chgrp -R www-data /var/www/html/{{ laravel_app }}<br><br>- name: Change permission<br>  shell: sudo chmod -R 775 /var/www/html/{{ laravel_app }}/storage<br><br>- name: Change permission<br>  shell: sudo chmod -R ug+rwx  /var/www/html/{{ laravel_app }}/bootstrap/cache<br><br>- name: Copy .env file<br>  copy:<br>    src: /var/www/html/{{ laravel_app }}/.env.example<br>    dest: /var/www/html/{{ laravel_app }}/.env<br>    remote_src: true<br><br>- name: Modify .env file<br>  template: src=.env  dest=&quot;/var/www/html/{{ laravel_app }}/.env&quot; owner=www-data mode=0644<br><br>- name: Modify /routes/web.php file (Add frontend to laravel route)<br>  template: src=.web.php dest=&quot;/var/www/html/{{ laravel_app }}/routes/web.php&quot; owner=www-data  mode=0644<br><br>- name: Copy .htacces file<br>  copy:<br>    src: .htaccess<br>    dest: /var/www/html/{{ laravel_app }}/.htaccess<br><br>- name: Remove default apache vhost config from sites-enabled<br>  file: name=/etc/apache2/sites-enabled/000-default.conf state=absent<br><br>- name: create apache vhosts for domain<br>  template: src=web.conf.j2 dest=&quot;/etc/apache2/sites-available/{{ laravel_app }}.conf&quot; owner=www-data mode=0644<br><br>- name: Update a2ensite<br>  command: a2ensite {{ laravel_app }}<br><br>- name: Update enable apache rewrite module<br>  shell:  a2enmod rewrite<br><br>  notify: <br>    - Restart apache<br></pre><ul><li><strong>Migrate-database: </strong>This role is responsible for automating the process of migrating the MySQL database for the Laravel application. It first makes sure that the Composer package is installed and updated. Then, it creates a new Laravel project on the slave node. Finally, it runs the “php artisan migrate” command to migrate the database, which applies any outstanding database migrations to the MySQL database on the slave node. The importance of this role is that it makes sure the Laravel app has the appropriate database schema.</li></ul><pre>roles/Configure-apache/tasks/main.yaml<br><br><br>- name: Composer update<br>  shell: composer update --no-interaction<br>  args:<br>    chdir: /var/www/html/{{ laravel_app }}<br><br>- name: Composer Install<br>  shell: composer update --no-interaction<br>  args:<br>    chdir: /var/www/html/{{ laravel_app }}<br><br>- name: Composer create-project<br>  shell: composer create-project  --no-interaction<br>  args:<br>    chdir: /var/www/html/{{ laravel_app }}<br><br>- name: Run the php -artisan migrate --force --seed command<br>  shell: php artisan migrate --force --seed<br>  args:<br>   chdir: /var/www/html/{{ laravel_app }}<br></pre><ul><li><strong>Install-SSL</strong>: This role installs and configures the Let’s Encrypt SSL certificate package and its dependencies on the slave node. The certificate helps to secure the Laravel application on the web, making it accessible via HTTPS. By setting up HTTPS, this role ensures that communication between a user’s web browser and the web server that houses the Laravel application is secured and encrypted.</li></ul><pre>roles/Install-setup-SSL/tasks/main.yaml<br><br>- name: Install Python Package<br>  apt: name=python3 update_cache=yes state=latest<br><br>- name: Install Let&#39;s Encrypt Package<br>  apt: name=python3-certbot-apache update_cache=yes state=latest<br><br>- name: Create and Install Cert Using apache Plugin<br>  command: &quot;certbot --apache -d  {{ servername }} -m {{ sever_email }} --agree-tos --noninteractive --redirect&quot;</pre><p>Now that the roles have been defined, an Ansible playbook YAML file needs to be created in the root working directory. In this YAML file, the roles will be referenced in the order in which we want the tasks to be executed. this file will be named “playbook.yaml”.</p><pre>- name: deploy laravel app on remote server<br>  hosts: slave-nodes<br>  vars_files:<br>    - group_vars/slave-nodes/main.yml<br>    - vault/db.yml<br>  become: yes<br>  roles: <br>    - Install-packages<br>    - Install-mysql<br>    - Configure-mysql<br>    - Configure-mysql-user-database<br>    - Configure-firewall<br>    - Install-php<br>    - Install-setup-composer<br>    - Clone-laravel-repo <br>    - apache-config<br>    - migrate-database<br>    - SSL-install-setup that the </pre><p>We can now proceed to running the ansible-playbook command to deploy the application into the slave node. To do this, navigate to the root working directory in your terminal and run the following command:</p><pre>ansible-playbook -i host-inventory playbook.yaml -ask-vault-pass</pre><blockquote>Note: You will be prompted to input your vault password because of the -ask-vault-pass flag. the deployment should run right after the correct password is inputted.</blockquote><p>We have now successfully Deployed the Laravel application on a remote server using ansible.</p><h4>Summary of the Process</h4><ol><li>To begin the deployment process, we first created two AWS EC2 instances which will be used as the master and slave nodes for our Ansible tasks. We made sure that both instances were created within the same VPC network, shared a security group that allows inbound traffic for HTTP, HTTPS, and SSH protocols. Additionally, we ensured that they shared an SSH key pair to facilitate SSH connection between both instances.</li><li>After creating the instances, we proceeded to install the Ansible package on the master node. We then created a working directory where we created and modified the host-inventory and ansible.cfg files to define the host nodes and set some configurations respectively.</li><li>We proceeded to create a group_vars directory within the working directory on the master node. Inside this directory, we created a subdirectory to house the variables used in this deployment. We also created an Ansible vault to keep sensitive information such as passwords and keys secure.</li><li>We created a roles directory in our working directory, and inside this directory, we created subdirectories for each task in this deployment. Each of these subdirectories contains additional subdirectories, such as files, templates, and tasks, that house the files, templates, and YAML files for each task respectively. This organizational structure made it easy to manage and modify the tasks in our playbook.</li><li>Finally, we summarized the process by creating an Ansible playbook YAML in the working directory. This YAML file contains each of our defined roles in the order in which we want the tasks to be executed. We then ran the ansible-playbook command in the working directory with the ask-vault-pass flag to commence with our deployment.</li></ol><p>Overall, this process allowed us to efficiently automate the deployment of our Laravel application on a remote server using Ansible. By breaking down the deployment tasks into separate roles and using Ansible’s automation capabilities, we were able to simplify the process and ensure that each step was executed correctly.</p><h3>Resources</h3><ul><li><a href="https://docs.ansible.com/ansible/latest/cli/ansible-playbook.html">Ansible Playbooks</a></li><li><a href="https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html">Ansible Roles</a></li><li><a href="https://docs.ansible.com/ansible/latest/cli/ansible-vault.html">Ansible Vaults</a></li><li><a href="https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html">Using Ansible Variables</a></li><li><a href="https://medium.com/@ehisjude420/ansible-fundamentals-6a0377eaaec5">Ansible Fundamentals.</a> by <a href="https://medium.com/u/de4b9b517c7e">Iribhogbe Ehis</a></li><li><a href="https://github.com/jubril-adeyi/deploy-laravelapp-using-ansible">GitHub repository for this deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c26531ad3d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Privately Host a static website on Amazon S3 using AWS Cloudfront]]></title>
            <link>https://medium.com/@jubril___/how-to-host-a-static-website-on-amazon-s3-using-aws-cloudfront-without-enabling-public-access-2fc7d5bd105?source=rss-6b66476f74e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fc7d5bd105</guid>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[static-websites]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jubril Adeyi]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 16:01:57 GMT</pubDate>
            <atom:updated>2023-05-22T19:10:29.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*dzcyCDWq6tyferxgHqOd3A.png" /></figure><p>Static websites are web pages that deliver web contents; HTML, Javascript, images, Videos, and other files to visitors exactly as they are stored, and are usually made up of fixed code.</p><p>Static Websites require very little IT administration to manage, are low-cost, and can easily handle high levels of traffic without a team of software developers.</p><p>These kinds of websites, therefore, are highly suitable for Blogs, marketing and sales websites, or for a web app that’s still under development.</p><p>In this tutorial, you’ll learn how Amazon S3 coupled with AWS Cloudfront can be used to host static websites.</p><h3><strong>Prerequisites</strong></h3><ul><li>Basic Frontend Design knowledge</li><li>An Index.html file</li><li>AWS Account</li></ul><h4><strong>WHAT IS AMAZON S3?</strong></h4><p><strong>Amazon S3 </strong>(simple storage service) is a scalable, highly secure, reliable, and highly available object storage service provided by AWS Cloud.</p><p>Within the Amazon S3 service are S3 buckets in which files are stored as objects. These objects can be further organized in folders within the S3 bucket.</p><p>Amazon S3 stores Objects using a Unique key-value and each object can be up to 5TB in size. Each object consists of a Key, Version ID, Value, Metadata, and Access control information.</p><h4><strong>WHAT IS AMAZON CLOUDFRONT?</strong></h4><p><strong>AWS Cloudfront </strong>is a low-latency content delivery network (CDN) that’s designed to securely deliver content via websites around the globe. It is peculiarly characterized by its high speed and availability.</p><h3><strong>SETTING UP AMAZON S3</strong></h3><h4><strong>Step 1: Create an Amazon S3 Bucket</strong></h4><ul><li>Locate Amazon s3 On the AWS management console and click on “Create bucket”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0K19z2aDlZgwE1MxmYJhg.png" /></figure><ul><li>In General configuration, while setting the bucket name, note that the bucket name must be unique and must follow the <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html">bucket naming rules</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*ksfI3J6sImoeW3CSaEluTQ.png" /></figure><ul><li>On the next step, choose the AWS region where you want your bucket deployed, note that S3 is a global service, so it’s best to choose the geographically closest region to minimize latency.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*LVv0ILhhT-Y3qXqbeKuj6A.png" /></figure><ul><li>Set All public access to remain blocked, this is usually the default state. Enabling public access would mean that our static website can be accessed by anyone via the Public DNS assigned to the bucket.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*NfSnqPp6pVxQvn9alDi-aw.png" /></figure><ul><li>Now click on “Create bucket” and finally, your S3 bucket has been created</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*is4zCa-h5JKsuiOsX3UCxg.jpeg" /></figure><h4><strong>Step 2: Upload the Frontend files for the static website</strong></h4><ul><li>After Selecting the S3 bucket, click on the “upload” button</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*ahomgDVPZDObKdnxBXPwMQ.jpeg" /></figure><ul><li>On the next page click on “add files”, select index.html files for your website from your local disk, and click on the “Upload” button to upload the files into the s3 bucket.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*tBS-8_RxHUXwXgXncR_yBA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*dmpMg2bPwM1E0Kfv9_6qzw.jpeg" /></figure><p>Now your files have been successfully uploaded.</p><h4><strong>Step 3: Enable static website hosting on the S3 bucket</strong></h4><p>Static website hosting is a feature of the Amazon S3 service that lets a bucket host websites, it also provides a website endpoint that can be used to access the website.</p><ul><li>Select your bucket and locate Static Website Hosting on the properties tab, click on the Edit button</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgrlhYqW6zv7Dn2a6u2KQA.jpeg" /></figure><ul><li>Enable static website hosting and choose “Host static Website” for the hosting type</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*sFmYz_LSXx-J9YiKaV3_iA.png" /></figure><ul><li>Input the name of the file that is the home/default page of your website which is the index.html file. The error.html file is optional, it should be a file that you want returned when an error occurs while trying to reach the website.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*jlMzRtump2sQWgE06VRRAA.png" /></figure><ul><li>You can now save these changes.</li></ul><p>Now that the S3 bucket has been successfully created with frontend files uploaded and static website hosting enabled, we can now proceed to set up our Cloudfront to access the Website hosted in the S3 bucket.</p><h3><strong>SETTING UP AWS CloudFront</strong></h3><h4>Step 4: Create a CloudFront Distribution</h4><ul><li>Locate CloudFront on the AWS management console and Click on “Create Distribution”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiJANgeLG8ARlUnaNceBww.png" /></figure><ul><li>Select the origin domain, the origin domain is the domain name for the S3 bucket that was previously created.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*BCJlIHK-f61kM4oYCkZ9YA.png" /></figure><ul><li>Create origin access control, this restricts Bucket access to only the Cloudfront service.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*Zayrh51t7UUtcIfNkyCWpg.png" /></figure><ul><li>Input the object file (index.html) as the default root object to be returned when the root URL is requested.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*Y4TwBJdKSXe7BBne48daUw.png" /></figure><ul><li>Now the CloudFront distribution has been created, it usually takes a while to deploy while it indicates ‘deploying’</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCjEyP6J1gVrEd9SBLo92A.png" /></figure><ul><li>An AWS policy is created once the distribution configuration is finalized, this policy should be copied and used in the s3 bucket to allow access from CloudFront.</li></ul><h4><strong>Step 5: Update the S3 bucket policy to Allow access via CloudFront.</strong></h4><ul><li>On<strong> </strong>the S3 bucket Permissions tabs, locate Bucket policy, click on edit policy and paste the copied policy that was created while creating the CloudFront distribution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqKfjVMXUuzh2vJLF04ZVg.png" /></figure><ul><li>You can now save your changes</li></ul><p>Your static website will now be accessible via the CloudFront Distribution domain name. You can link this domain name to any personal domain name of your choice using <a href="https://aws.amazon.com/route53/">Amazon Route 53</a>.</p><h3><strong>Conclusion</strong></h3><p>I hope you were able to learn how to host a static website effectively using Amazon s3 and CloudFront services in this tutorial.</p><p>This tutorial covers the Use of S3 buckets and CloudFront for static websites but there is so much more that these services can be used to do. You might find the Documentation for <a href="https://aws.amazon.com/documhttps://aws.amazon.com/documentation-overview/s3/entation-overview/s3/">Amazon s3</a> and <a href="https://aws.amazon.com/documentation-overview/cloudfront/">Cloudfront </a>very useful.</p><p>If you have any questions, you can leave them in the comment section below.</p><h4>Resources for further reading</h4><ul><li><a href="https://www.sanity.io/static-websites">Static websites</a>, <a href="https://www.sanity.io/exchange/community/joeholmes">Joe Holmes</a></li><li><a href="https://aws.amazon.com/documentation-overview/s3/">Amazon S3 </a>Documentation, AWS Cloud</li><li><a href="https://aws.amazon.com/documentation-overview/cloudfront/">AWS Cloudfront</a> Documentation, AWS Cloud</li><li><a href="https://aws.amazon.com/documentation-overview/route53/">Amazon Route 53</a> Documentation, AWS Cloud</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fc7d5bd105" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>