Sunday, August 11, 2019

Terraform setting up simple web server !! Getting Started Part-2!!


In our last post "Getting started with terraform", we just learn how to launch a simple EC2 instance in AWS. In this article we will dig more and will try to create a simple web server and try to access that.

Architecture -





We are not installing proper web-server, its just a hack. Using busybody to launch http process.

#!/bin/bash
echo "Hello, World" > index.html
nohup busybox httpd -f -p 8080 &
resource "aws_instance" "example" {
  ami                    = "ami-0cfee17793b08a293"
  instance_type          = "t2.micro"

  user_data = << - EOF  // Together<-eof code="">
              #!/bin/bash
              echo "Hello, World" > index.html
              nohup busybox httpd -f -p 8080 &
              EOF

  tags = {
    Name = "terraform-example"
  }
}

The << - EOF (together)<-eof span=""><-eof span=""> and EOF are Terraform’s heredoc syntax, which allows us to create multiline strings without having to insert newline characters all over the place.

We need to do some more changes before making this to work. By default aws deny all incoming and outgoing traffic from any EC2 instance. So, to allow http traffic on the web server we need to add a rule which will allow traffic on port 8080.

For this we will create a security group as below :

resource "aws_security_group" "example-ec2-sg" { 
  name = "terraform-example-instance"    // Name of the security Group

  ingress {
    from_port   = 8080
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]. // Allow from everything
  }
}
Creating this new security group will not be enough, until we configure our EC2 instance to use this security group. To do that we should be aware of terraform expressions.

An expression in terraform is something which return values. Terraform support number of expressions, but here we will use the type of reference  which allow us to access the values from other code. Here we need  the ID of the security group in EC2 configuration. For this format will be something like below-

_..
e.g. aws_security_group.example-ec2-sg.id

 Now use this security group ID in "vpc_security_group_ids" argument of aws_instance. So the final terraform file will be as below -



Now, lets go ahead and apply these changes. This will replace existing server and create NSG and associate that with new EC2.

Output of $terraform apply

Lets check aws console, grab Public IP and try to access web server either via browser or cli(curl e.g)-



Thats all for this post. Later we will see how to use variables (Input and Output) to make it more generic and setup cluster on webservers.

2 comments:

Integrate Jenkins with Azure Key Vault

Jenkins has been one of the most used CI/CD tools. For every tool which we are using in our daily life, it becomes really challenges when ...