how to create ec2 instance in aws using terraform

We will cover few basic elements like what is Infrastructure as code, What is Terraform etc and setup AWS API authentication and start creating Terraform configuration files for AWS provisioning, Infrastructure as Code often referred to as IaC, is where the developer or system admins write code to achieve the end state of the infrastructure or server they desire. Subscribe to our channel Also, we have specified key_name to specify the name of the key pair to attach to the instance. Create a file called variables.tf This will contain the name, description, type and default values of all your input variables. You need to save it right so that you can use it in terraform. As well be working with AWS, here is our provider declaration section and authentication section-. , In this step, we will create our Terraform configuration files: main.tf, providers.tf, variables.tf, and outputs.tf. Create a new Key Pair and name it ditwl_kp_infradmin. Linux (Ubuntu) 6. In this guide, we going to launch an EC2 Instance (Ubuntu Server 20.04 LTS) on AWS with Terraform. On the Add permissions page, select the policies that grants your instances access to the resources that they need. if(typeof ez_ad_units!='undefined'){ez_ad_units.push([[300,250],'howtoforge_com-box-3','ezslot_3',106,'0','0'])};__ez_fad_position('div-gpt-ad-howtoforge_com-box-3-0'); Create a dedicated directory where you can create terraform configuration files. We are going to be creating a public and a private route table. AWS EC2 Instance Lab Technologies Planning to Use : 1. Hope this article helps you understand, How Terraform AWS or Terraform EC2 instance creation works in real-time. It is not recommended. Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox. Count, For_Each, and Ternary operators Steven Laszloffy in Level Up Coding Deploying a Two-Tier Structure with Terraform Cloud CI/CD Help Status Writers Blog Careers Privacy Terms About Text to speech Additionally, you tell terraform how you will be authenticating with the said cloud provider. You can also subscribe to our newsletter below to not miss any updates from us. Create a folder for your Terraform Project and export the Terraform environment variables. Now you try login to the EC2 using the session manager as below:- Click on the Connect button in EC2 console 2. We will be using MySQL RDS for the database. Click on "Security Credentials" tab Click on "Create access key" button to generate a new access key. When you execute the above command, you can see that1 new resource hasbeen added and 0has been destroyed in the output. Change). Next initialize the Terraform using terraform init command followed by terraform plan and finally terraform apply to deploy the changes. Here is what the final configuration file looks like. When it is finished, you should see a success message. I hope you learned something special today. Simply runterraform destroyand it will delete all that you created usingmain.tf. Terraform is a popular DevOps IaC tool that allows you to build, manage, and automate on-premise and cloud resources declaratively with a configuration file. document.getElementById( "ak_js_1" ).setAttribute( "value", ( new Date() ).getTime() ); The Most Trending, Quality DevOps Cloud articles, Automation guides, series, News, Podcasts, and videos. You can use an editor of your choice and copy-paste the following configurations to create variables.tf, terraform.tfvars, and main.tf Create 'main.tf', which is responsible for creating VPC on to AWS with the dependent resources. Create a folder called terraform-example where the HCL files will live, then change directories to that folder. Terraform providers will need to be defined and installed to use certain types of resources. And you should be good to go. Before you can create an EC2 instance with key pair, you will need a key pair. Create 'variables.tf' which contains the declaration and definitionof the variables. Enter the following command: It will take a few minutes to destroy everything. Copy the Access key ID and Secret access key Store these credentials somewhere safely as you will need to access them later, 8. We and our partners use cookies to Store and/or access information on a device. The one mentioned over here is a dummy one. Using an existing key pair looks as simple as-, If you are creating this Key Pair for learning purposes, you can go ahead and delete your key pair. Lets execute terraform destroy to tear down our infrastructure with one command. Easy and happy Learning! AWS Provider:The Amazon Web Services provider is used to interact with the many resources supported by AWS. Here is what you can do to flag kcdchennai: kcdchennai consistently posts content that violates DEV Community's This button displays the currently selected search type. Make sure to generate your own SSH key and replace the value of the public key with your own. terraform apply. Assuming you are still logged into the Ubuntu machine using your favorite SSH client. Alright, ONE more thing before we finish up here. Your email address will not be published. Log in to the Ubuntu machine using your favorite SSH client. `resource "aws_instance" "terraform_Demo_EC2_Instance" { ami = "$ {var.ami_id}" count = "$ {var.number_of_instances}" instance_type = "$ {var . terraform apply command will create the resources on the AWS mentioned in the main.tf file. . Create and assign a Security Group to the Jenkins Server that allows traffic on port 22 from your Public IP and allows traffic from port 8080. . Lets dive in. Create a main.tf, providers.tf, variables.tf, and outputs.tf to manage your Terraform deployment. 10. Since this is a test instance, I want to destroy the resources I have created and I can do it by executing terraform destroycommand. The following keys need to be changed with the keys of your IAM user. terraform state list can list all the resources managed in our state file. Use the following command to create a directory and change our present working directory to it. Delete the createdEC2 instanceusing Terraform. Now, I know what you are probably thinking. Also, we have specified the region in which we would like terraform to create my resources. By following this article, you will be able to create your first EC2 Instance creation using Terraform. Scenario: Your team has been working on a web application that uses a database. Made with love and Ruby on Rails. To facilitate the team's use of Jenkins as their preferred CI/CD tool for DevOps projects, it is necessary to create a Jenkins server using Terraform. EC2 Dashboard Step 11: You will see the Connect option on top. I have used Visual Studio Code as an editor to write in files, we can use an editor of our choice and copy paste the following configurations to create variables.tf, terraform.tfvars and main.tf. Step 2 Create a Key-pair for the server. Once we have saved the File in the newly created directory, we need to initializeterraform, If you have used Gitthis is similar to git init where we set up some local repository and initialize. When we created our EC2 instance we did not specify a Security Group so our instance will use the default Security Group for the region. The instructions are at the Amazon EC2 key pairs and Linux instances official documentation. Enter a Name for your key, select pem for openSSH or ppk for Putty and then click on Create key pair. So it refers to the profile: defaultfor the authentication. Search for AWS IAM 3. For Windows instances, the private key allows us to obtain the administrator password and then log in the EC2 Instance using RDP. IF you plan on deploying resources to a region besides us-east-1, you can modify the region value in the aws_region variable block. See complete example for details. Terraform is a great open-source tool that provides the easiest code and configuration files to work with. I am using "vim" as an editor to write in files, you can use an editor of your choice and copy paste the following configurations to create variables.tf, terraform.tfvars and main.tf. Create a file called provider.tf This is where you will specify terraform providers: 11. Copyright 2020 CloudKatha - All Rights Reserved, Click to share on Twitter (Opens in new window), Click to share on Facebook (Opens in new window), Click to share on LinkedIn (Opens in new window), Click to share on Telegram (Opens in new window), Click to share on WhatsApp (Opens in new window). Some of them are listed below. Lets check whether its created or not. We partner with you and bring together talented team of designers, front end developers, back end developers, Software architect, Cloud engineers to make your vision a reality and business a success. But it is important to manually verify all the four AWS instances launched in AWS. Create 'main.tf' which is responsible to create an EC2 on to AWS. The first command to be used is 'terraform init'. How to change key automatically in Azure Key Vault . Use the following command to create a directory and change your present working directory to it. Updated on Jun 7, 2022. As we can see from our returned output, Terraform will create 13 resources in AWS. In the commands above, an AWS instance is created with unlimited CPU usage. This section talks about how to create EC2 key pair using terraform. I have given some explanation before each block on the configuration to explain the purpose of the block. Enter yes. Copy and paste into your Terraform configuration, insert the variables, and run terraform init : module " ec2-instance " { source = " terraform-aws-modules/ec2-instance/aws " version = " 4.3.0 " } Readme Inputs ( 63 ) Outputs ( 22 ) Dependency ( 1 ) Resources ( 5 ) AWS EC2 Instance Terraform module We can go to the AWS EC2 console to verify if the EC2 instance is created or not. Choose Instances , Select Launch Instance , Here you will find the lists of Operating systems. Now that the VPC resource has been created, its time to create the Internet Gateway and attach it to the VPC. Now that the data object has been created, we can create the EC2 instance. Let's see if our database was created. Whenever we want this IP, we can come to this directory and execute terraform outputto get it. Before deploying your infrastructure, we must run terraform init to initialize the working directory where the Terraform configuration files are located. When you execute the above command, you can see that. Step 1) Open up your AWS console or directly visit ' console.aws.amazon.com '. For more practical videos and tutorials. Write for Us Cloud Computing | AWS | Cyber Security | DevOps | IoT, Ways in Which You can Create and Manage AWS Resources, How to Setup AWS Free Tier Account in Right Way, Getting Started With Terraform on AWS In Right Way, How to Create Key Pair in AWS using Terraform in Right Way, Send SNS Notification from AWS Lambda using Python Boto3, Subscribe an SQS Queue to an SNS Topic using CloudFormation, How to Create IAM Role in AWS using Terraform, We saw how to create an EC2 key pair using terraform, Created an EC2 instance using the created key pair, We also saw how to use an existing key pair while creating an EC2 instance. AWS account with Administrator Access permissions, AWS CLI installed and configured with your programmatic access credentials. Node.js doesnt stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc. Thanks to IaC.!! Static stuff can be provided by adding an access_key and secret_key in-line in the AWS provider block. . As soon as you click, a variety of options for connecting the EC2 instance will appear. The resource name and VPC are set to variables created in the next step. This terraform-for_each-demo folder will contain all the configuration files that Terraform needs. Docker 2. It also guarantees that what we see in the planning phase would be applied when we go for committing it. Now its time to begin setting up our AWS environment. After the DB subnet group has been created, we can now create the database. . A better way is using Terraform to . Click anywhere on the image to buy it on amazon. Now you have learnt how to create EC2 instance with Terraform and with user_data as well. It takes hours of productivity and creates a huge delay for the server setup or provisioning. Fill out the vars.tfvars with your desired key_pair_name. Set the user permissionsUnder Set permissions < Attach an existing policy < Select AdministratorAccess. This article is going to all about Terraform AWS Example and how to Create EC2 instance with Terraform. Now lets use the output returned for ec2_remote_access and ssh into our EC2 instance. Using ChatGPT to Create AWS Cloudformation & Terraform Templates Flavius Dinu Terraform from 0 to hero 7. Now its time to clean up our resources. You can remove the profile line alone and that should be it. In such cases, we can use EC2 user_data feature and define a set of commands or scripts that needs to be executed during the server initialization. In the AWS console we need to remember where and what to click so we risk missing step(s). When you are working with Terraform in production or with other engineers you will store this state file in a remote storage account, allowing you to keep track of all your resources in a shared share file. In our case, we will use Ubuntu. While AWS or Amazon web services being a leader in the cloud industry with a market share 70 percentage. If those are your exact thoughts, dont worry. If you are using VS Code, install the terraform extension. In this tutorial, you will learn how to Launch multiple AWS EC2 instances on AWS using Terraform count and Terraform for_each. Create an outputs.tf file This will output values after the creation of your resources. The input file for terraform is known as Terraform Configuration. For example, Lets suppose You want to create an infrastructure of LAMP (Linux Apache MySql PHP) along with some other Linux tools like nc, curl, Openssletc, The traditional approach is to build the Virtual machine and install these tools one after another. NOTE: I am using the WSL terminal in this demonstration, but you can follow along using any terminal supporting the abovementioned prerequisites. Now that we have defined both the variables and secrets, lets start creating our config file. Now that you have Terraform installed. If You need a quick and efficient way to automate infrastructure in AWS, you can use Terraform.. With AWS EC2, you dont need to worry about the hardware and time to develop and deploy applications on the machines. You can get the AMI Id from the console. So let us go and do some farming in the AWS planet. We will verify S3 access and the Jenkins installation with the upcoming steps. The list of users per distribution can be found here: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connection-prereqs.html, (ii) Connect to your EC2 Instance using the private key file, the username and the public_dns name from the output above, 23. Fill out the vars.tfvars with your instance_type, (i) Login to the AWS Console < Search for EC2 < Select Launch instance < Scroll down to Instance type < Select Compare instance types, (ii) Search for the instance type you want < select and copy its name, (iv) Update your vars.tfvars with the value of the instance type, 15. In the preceding output. Otherwise, there are other ways to connect your system and its absolutely okay for you to skip adding a key pair to your instance. This was the db_password you created in your secrets file. We need something powerful to help us create instances/Infra in a single click. Terraform configurations must declare which providers they require so that Terraform can install and use them. Lets learn how to use Terraform count meta argument. We can create the AWS Key Pair using the AWS Console, AWS CLI, or PowerShell. This will install the latest module and provider versions. This is the first command that should be run after writing a new Terraform configuration. We will explore it by following this piece of code step by step. Install AWS CLIon your machine and configure it with the IAM user credentials. 16. ssh -i "tutorial_kp.pem" ubuntu@$(terraform output -raw web_public_dns), ssh -o 'IdentitiesOnly yes' -i "tutorial_kp.pem" ubuntu@$(terraform output -raw web_public_dns), sudo apt-get update -y && sudo apt install mysql-client -y, mysql -h -P -u -p, terraform destroy -var-file="secrets.tfvars", https://github.com/dispact/terraform-custom-vpc, EC2 instances should be accessible anywhere on the internet via HTTP, Only you should be able to access the EC2 instances via SSH, RDS should be on a private subnet and inaccessible via the internet, Only the EC2 instances should be able to communicate with RDS, Create an Internet Gateway and attach it to the VPC, Create 3 subnets: 1 public for EC2 and 2 private for RDS, Create 2 route tables: 1 public and 1 private, Create 2 security groups: 1 for EC2 and 1 for RDS, Verify that everything is set up correctly, Lets create a directory for our terraform project and cd into it, Create a file in the project directory called, Create a file in the same directory called. Benefit of that project: You save time by automating the creation of your infrastructure using Terraform You can reuse that code in different cloud providers such as GCP, AWS, Azure, Oracle, etc.. and create an infrastructure . If you want to learn to create an EC2 instance from the AWS console then click here. Terraform outruns them for the right reasons. The best practice is to keep changing the API Access Key and recreating it. To create the EC2 Instance, run the command terraform apply.. Congratulations! Now that the subnets have been created, we can go ahead and create the route tables. Create a file called ec2.tf This is where you will describe the EC2 instance you want to create, Note: we are referencing the key pair created from the ssh.tf file, 13. Select your EC2 instance and click on it to go to the instance details screen. Once unsuspended, kcdchennai will be able to comment and publish posts again. In order to do this, The Simplest way is to download and setup AWS CLI, You can refer to this document how to setup AWS CLI. Input command cat. Here is the sample Terraform Configuration file saved with *.tf extension. To destroy the resource use below command and Type " Yes ". However, its far from the ideal scenario. After successfully installing the terraform, we will create an EC2 instance using Terraform, and we will use the VS code editor to write the script. You'll need to write out each argument you want to set with an expression which tells Terraform how you'd like to set it. Setup Programmatic Access Login to AWS Console, In the services, go to IAM and perform the following steps Step1: Add new user and key in the UserName Click to view the image Step2: Attach Existing Policies and Select Admin Click to view the image Here is the Terraform configuration file or manifest to create EC2 instance. DEV Community A constructive and inclusive social network for software developers. Terraform configuration is written in a specific language namedHashicorp Configuration Languageand it can optionally be written in JSONas well. For example, You want to launch Ubuntu 18.04, You can find the AMI ID of Operating system, You should use this AMI ID in your terraform file to launch an EC2 Instance with Ubuntu 18.04 Launching an EC2 instance using Custom AMI: How to use Terraform to create a Virtual Private Cloud (VPC) and an EC2 instance in AWS First, create a new Terraform configuration file and specify the AWS provider: provider Terraform has to successfully authenticate. Now your files and code are ready for execution. On the Select trusted entity page, choose AWS service, and then select the EC2 use case. We can view a lot of information about our deployment from this command. We empower and invest in diverse technology talent to increase representation for all people, and to create higher performing enterprise organizations. This will create your EC2 instance in AWS and create a private key file on your local machine. Share Improve this answer Follow edited Feb 9 at 23:19 As you can see, well be working with the AWS provider. We are giving full permissions here but the best practice is to follow the Principle of Least Privilege (POLP) and give our user only the permissions needed to create an EC2 instance. Follow DevopsJunction onFacebook orTwitter We must change ami_key_pair_name, ami_id and subnet_id as these are specific to the environment. Next, enter the value returned from the instance_public_ip in your browser with :8080 appended to the end. Run the following command in the MySQL terminal. If you had any issues throughout this tutorial, you can compare your code to the final code here: https://github.com/dispact/terraform-custom-vpc. This main.tf will read values of variables from variables.tf and terraform.tfvars. You can find the instructions hereInstalling Terraform CLI. Now you deployed an AWS EC2 Instance in your AWS account using Terraform. DEV Community 2016 - 2023. Connect to your instance using your private SSH key, (i) Each Instance gets a default user added to it, depending on its distribution. In this step, we will finally deploy our AWS resources using Terraform. please do take a look by following this link, If you would like to give a chance to Terraform and want to learn all the bits and pieces of it. (ii) Open the command line and export the Terraform environment variables. Now that the variables have been declared, let's go ahead and set up our secrets file. Change the value of "region" if you want to create the instance in some other region than what I have specified. In this article, we saw the steps to create an EC2 instance in the region of our choice. What I love most about Terraform is that we only have to worry about defining WHAT we want to deploy and not HOW it should be deployed. This will allow the team to utilize the tool in multiple environments and better track any changes made to the environment. For any Consultation or to hire us [emailprotected], Signup for Exclusive "Subscriber-only" Content, Infrastructure as Code is getting all attention it deserves and everyone is trying to find their way to the `Completely automated Infrastructure Provisioning & Management` While there are a lot of tools available now in the market starting from Terraform, AWS CloudFormation, Chef, Puppet, Salt Stack There are some differences, In this article, we are going to see a quick packer aws example setup and provide the steps to create an AWS Image (AMI) using Packer and we are also going to Create Amazon EC2 Instance ( Elastic Bean Stack - EBS) from the same AMI Image we have created,, AWS CLI is a very great help when it comes to efficiently managing your AWS Cloud Infrastructure and your EC2 instances. Terraform is a great automation choice of tool to create Iaac (Infraestructure as a service) for AWS. Such as-. This Series: https://medium.com/@roadtocloude/list/create-ec2-instances-with-infrastructure-as-code-iac-c4ca1b5067fe, Git Repository: https://github.com/RukayaOK/aws-ec2-creation-iac/tree/main/terraform, 4. This tutorial is a shorthand to show how to start using this tool. Terraform configuration files for creating an AWS EC2 Instance Create a dedicated directory where we can create terraform configuration files. In this article, we will see how to create an EC2 Instance using Terraform. It is primarily used to build and test the integration of new code in your project by executing a set of instructions found in the Jenkinsfile. This main.tf will read values of variables from variables.tf and terraform.tfvars. Step 5: Validate EIP Association. While the world is moving towards containers and desired state and auto-scale. Hope this article is helpful, If you have any feedback or issues please let me know on the comments section. For your satisfaction, stop and start your Ec2 instance. You will notice that the apply command shows your plan output and asks you to Do you want to perform these actions?.Write yes and hit Enter to deploy the EC2 Instance. We and our partners use data for Personalised ads and content, ad and content measurement, audience insights and product development. While everything has its pros and cons. To create one, go to your AWS console, select EC2 from Services drop-down, click on Key pairs, then click on Create key pair button. Write Terraform configuration filesto create an EC2 Instance, Create an EC2 Instanceusing the Terraform configuration files, Develop Network Applications for ESP8266 using Mongoose in Linux, How to Setup IKEv2 IPSec VPN Using strongSwan and Let's Encrypt on Rocky Linux 9, Generating Web Site Statistics With AWStats & JAWStats On Debian Lenny, ISPConfig Perfect Multiserver setup on Ubuntu 20.04 and Debian 10, How to Install Jitsi Video Conference Platform on Debian 11, How to Install LAMP Server Stack on Ubuntu 22.04, How to Install and Configure Ansible on Ubuntu 20.04, How to Install CryptPad Collaborative Office Suite on Ubuntu 22.04, How to use grep to search for strings in files on the Linux shell, How to Install Jellyfin Media Server on Debian 11. For creating the EC2 instance, we need ami and instance type. The syntax for creating a resource in Terraform is: Resource: The most important element in the Terraform language is the resource. You should have successfully reached the Jenkins Getting Started page that is displayed on every new Jenkins installation. Otherwise, you wont be able to connect to your instance from your local system. We are going to be working in the main.tf file for the majority of this tutorial. (LogOut/ When prompted, enter the password of the DB user. In this project write-up, I will cover deploying an EC2 into a new VPC with Jenkins installed using Terraform. Allow Necessary Cookies & Continue The instructions are at the "Amazon EC2 key pairs and Windows instances" official documentation. Another more simple command is terraform state list. I will sum it up for reference here. The requisites of this . In our case, we are going to need 1 public subnet and 2 private subnets. Connect to your instance with Session Manager 3. The second command to be used is 'terraform plan'. Once complete, all of your resources should be removed. Execute the terraform plancommand and it would present some detailed info on what changes are going to be made into your AWS infra. Dont worry!. , In the bucket_name variable block, you must change the default name value since S3 bucket names must be unique across AWS. To avoid any unnecessary charges in AWS, lets use terraform to destroy everything that we have created. you can use any editor). We are using the -t option to specify the algorithm that we want it to use. Install and configure AWS CLI Tool: How to Install and Use AWS CLI on Linux Don't forget to configure AWS Access Key ID and Secret Access Key as shown on the installation guide. When you create an EC2 instance and you know you will be doing SSH into your instance using an SSH client. Developers can create an Amazon EC2 instance to test software in a development or staging environment, or to deploy software to production.