How to Get the IP address of the EC2 instance deployed using Terraform and connect it to the elastic IP.
In the Previous Blog, we discussed what is terraform and how to deploy an ec2 instance using Terraform.
In today’s blog, we will discuss how to get the IP address of the ec2 instance deployed using terraform and assigned it to the elastic IP. So you can connect to it any time you want.
First of all, we will create an ec2 instance (if you want to learn it in more detail check out my previous blog, mentioned above) and elastic IP using terraform. Then we will get their respected IP and allocation id and we will connect them both.
in the first block(provider block) we define the provider which is AWS in our case.
after that, in the second block(resource block) we define that we want to deploy an ec2 instance with the name “chirag_ec2" and we also define ami id which is amazon Linux in this case, and instance_type which is the “t2.micro” (free tier).
in the third block, we are defining that we want to create elastic IP with the name “eip”.
finally, in the fourth block, we define the AWS elastic IP association which needs the instance id of the ec2 instance we deployed and the allocation_id of the elastic IP.
now let’s understand how we are getting these two things.
we are getting these output values with the help of attributes like id to access these attributes we need to reference the resource. To get the reference to the resource we use: resource_name.name_we_gave.attribute
e.g. aws_instance.chirag_ec2.id and aws_eip.eip.id
That’s it after creating the file with the above code.
type (in the shell):
- terraform init if you haven’t initialized the terraform yet.
terraform init
2. terraform plan ( to get the plan)
terraform plan
3. terraform apply (to apply changes)
terraform apply
and don’t forget to destroy the resource after using terraform destroy (if you don’t need it.).
terraform destroy
I hope today’s blog helped in some way, give yourself a nice pat on the back you learned a new thing today, and enjoy a cup of coffee and remember to not add too much sugar to it. 😁️😁️
Don’t forget to visit again tomorrow for more exciting and informative content. We will discuss Statefiles how the terraform keep the information about changes to your infrastructure and how to use variables in the terrafrom.
Meanwhile, you can check out my other blogs which are awesome by the way.