Using Terraform to Create VM Instances and Connect via SSH
Introduction
In the previous article, I introduced some basic concepts about Terraform, as well as the advantages of using Terraform. If you're not familiar with it yet, take a look to get some basic knowledge before diving into the next topics.
In this article, I will guide you through writing Terraform files to deploy a Virtual Machine (VM) instance to the Google Cloud Provider.
Creating a Service Account
If you already have a Google Cloud account with the necessary permissions, you can log in to work with Terraform as I instructed in the previous article. However, if for some reason you can't log in, or if you need a better authentication method, you can create a Service Account to use.
In simple terms, a Google Cloud account is allowed to create Service Accounts. Each Service Account is assigned roles, and each role has corresponding permissions allowing the Service Account to perform specific tasks based on permissions.
To create a Service Account, use the following command:
Next, create a JSON-formatted key file:
After executing this command, a file named `service-account.json` will be created for us to use in the Terraform project.
Setting up roles for the Service Account
Here, to have management rights in Compute Engine, you need to set the role to `--role=roles/compute.admin`.
Creating a Terraform Project
First, create a file named `provider.tf` to define the cloud provider and information about credentials.
Here, use the `service-account.json` file created from the Service Account initialization step.
Next, create the `variables.tf` file.
Create the `terraform.tfvars` file to define default values. You can modify the values according to your needs.
Finally, create the `main.tf` file to initialize the compute instance as follows:
Execute the Terraform command
Then, execute the following commands one by one to apply the configuration to Google Cloud.
Once you see the result as follows, the VM instance has been successfully initialized:
SSH Connection
I will guide you through two simple ways to connect via SSH:
1. Using Cloud Shell:
On the Google Cloud web page UI, simply click on the SSH icon to connect.
2. Using the gcloud terminal:
Another way to directly connect via SSH from your local machine is by using the following gcloud command:
Comments
Post a Comment