Wednesday, April 4, 2018

Provision EC2 instance in AWS using Terraform - Create Terraform files for provisioning resources on AWS

Terraform can provision resources on any cloud platform. We will see how you can use Terraform to provision EC2 instance.

1. Login to AWS console, click on username and go to My security credentials. 2. Continue on security credentials, click on access keys 3. Create a new access key if you don't have one. Make sure you download the keys.

4. create aws.tf file with below content. make sure you update with your Access key and secret keys.
replace red marked with keys you received from step # 3 above.
sudo vi aws.tf

provider "aws" {
access_key = "xx"
  secret_key = "
xx"
  region     = "us-east-2"
}



Now execute the below command:

terraform init



the above command should load the AWS plug-ins.


sudo vi create_ec2.tf
copy the below code in yellow color:



resource "aws_instance" "myFirstInstance" {
  ami           = "ami-916f59f4"


  key_name = "my_key"
  instance_type = "t2.micro"
  security_groups= [ "security_jenkins_grp"]
  tags= {
    Name = "jenkins_instance"
  }

}

resource "aws_security_group" "security_jenkins_grp" {
  name        = "security_jenkins_grp"
  description = "security group for jenkins"

  ingress {
    from_port   = 8080
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

 ingress {
    from_port   = 22

    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

 # outbound from jenkis server
  egress {
    from_port   = 0
    to_port     = 65535
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags= {
    Name = "security_jenkins_grp"
  }
}

terraform plan

the above command will show you what Terraform is going to do..

terraform apply
type yes

Now login to EC2 console to see newly provisioned EC2 instance.

No comments:

Post a Comment