Skip to content

Lesson 3 of 6

Create the virtual machine

Add an instance resource that uses the security group and runs a simple web server on first boot.

4 minInfrastructure

After this lesson, you will be able to add a cloud virtual machine to your Terraform configuration, connect it to the security group from the previous lesson, and run a simple web server on it automatically when it starts.

Add an instance resource

A virtual machine in AWS is called an EC2 instance. You define it with a resource block in your Terraform file. Open main.tf and add the following code below the security group resource.

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  vpc_security_group_ids = [aws_security_group.web.id]

  user_data = <<-EOF
    #!/bin/bash
    apt-get update
    apt-get install -y apache2
    echo "Hello from Terraform" > /var/www/html/index.html
    systemctl start apache2
    systemctl enable apache2
  EOF

  tags = {
    Name = "web-server"
  }
}

The ami argument is the Amazon Machine Image, which is the operating system image for the instance. The value shown is for Ubuntu Server 20.04 LTS in the us-east-1 region. AMI IDs are different for each region, so if you changed the region in your provider block, you need to find the correct AMI ID for that region. The instance_type is the size of the virtual machine; t2.micro is a small, inexpensive type that is free tier eligible.

The vpc_security_group_ids argument attaches the security group you created in the previous lesson. It uses the reference aws_security_group.web.id to get the ID of that security group. Terraform will create the security group before the instance because the instance depends on it.

The user_data argument is a script that runs when the instance first boots. It installs the Apache web server, creates a simple HTML page, and starts Apache. The script uses a heredoc syntax with <<-EOF so you can write multiple lines. The first line #!/bin/bash tells the operating system to run the script with the Bash shell.

The tags argument adds a name tag to the instance, which helps you identify it in the AWS console.

Understand user_data and cloud-init

The user_data script is passed to the instance at launch and executed by cloud-init, a service that runs on first boot. Because it runs only once, it is ideal for initial setup tasks like installing packages and starting services. If you need to change the script later, you must recreate the instance or run the commands manually. Terraform will show a change in the plan if user_data is modified, and applying that change will destroy and recreate the instance. This is because user_data is used only at launch and cannot be updated on a running instance.

The script uses apt-get update to refresh the package list, then apt-get install -y apache2 to install Apache without prompting for confirmation. The echo command writes a simple HTML file to the default web root. Finally, systemctl start apache2 starts the service immediately, and systemctl enable apache2 ensures it starts automatically on future boots.

Format and validate

Run terraform fmt to format the file consistently, then terraform validate to check for syntax errors.

terraform fmt
terraform validate

The validate command should output a success message. If there are errors, read them carefully and fix the configuration.

Plan the changes

Before creating the instance, run terraform plan to see what Terraform will do.

terraform plan

The plan output will show that Terraform will create a new aws_instance.web resource. It will also show that the security group already exists and will not be changed. The plan does not make any changes; it only shows what would happen if you applied it.

You do not need to apply the plan yet. In a later lesson, you will apply it and verify the web server. For now, the configuration is ready.

Key takeaways

  • An aws_instance resource defines a virtual machine with an AMI, instance type, and other settings.
  • Use vpc_security_group_ids to attach a security group to the instance.
  • The user_data script runs automatically on first boot and can install and start a web server.
  • Always run terraform fmt and terraform validate after editing configuration files.
  • terraform plan shows what changes Terraform will make without applying them.

Try it

Add a second instance resource named web2 to your configuration. Use the same AMI and instance type as the first instance, attach the same security group, and give it a different name tag, such as web-server-2. For user_data, use a script that installs Apache and creates a page that says Hello from second instance. Run terraform fmt, terraform validate, and terraform plan. Confirm that the plan shows two new instances to be created. Then remove the second instance resource and run terraform fmt and terraform validate again to return to the state from this lesson. A good result is that the plan clearly lists both instances when the second one is present, and the final configuration has only the original instance.

Official documentation

Ready to use this in a job?

Rolebound applies to matching roles for you.

Start now

Written with AI and checked automatically. Tools change, so a command may behave differently in the version you install. Spotted a mistake? Tell us.

    Cookies on Rolebound

    We use necessary cookies to sign you in and keep the site working — those cannot be turned off. We would also like to set analytics and advertising cookies so we can see which pages help people get interviews and which adverts brought them here. Nothing optional is set unless you say yes, and you can change your mind at any time from “Cookie settings” in the footer. Read our Privacy Policy.

    Create the virtual machine | Build a Cloud Web Server with Terraform | Rolebound