-
Once terraform is in setup then create one folder and go inside them to write a terraform script.
-
You can provide the name of terraform script file as per your choice but always end with .tf
-
Some imp commands used in terraform
"If you are not a root user use sudo before every command"
a. terraform init: Once you write script for resources then run this command in the same directory where you write the script, This initialises terraform with script and download requirement mentioned in code. Without ‘terraform init’ your working directory does not initialise for terraform.
b. terraform fmt: Make proper format of script which we write.
c. terraform validate: validate our script for any type of error or missing element.
d. terraform plan: This command shows the output of the script without applying any changes, we get just an overview of resources created after “terraform apply”.
e. terraform apply: This command applies all changes in infra that we mentioned in script.
"We can also use '--auto-approve' flag after terraform apply and destroy command to direct action without asking to confirmation"
f. terraform destroy: This command destroys all created resources from terraform apply.
g. terraform workspace list: To list all workspaces
h. terraform workspace new any_name: Create a new workspace and switches to them
i. terraform workspace show: Show current workspace
j. terraform workspace select dev: Selet the workspace of name dev
k. terraform workspace delete dev: delete workspace of name name dev
Before creating resources create one service account and download the key for provide credential of your account.
In the script file named 'terroform-project-a745e034dbf9.json' is the secret key downloaded from service account you will put your key file
Go to IAM console with navigation pan and click on service account.
Now click on upper side for create new service account.
once the account is created then on right side of service account name click on three dot's for manage key
And inside the manage key create a new key and download the same for provide in main.tf for your account access by terraform.
Once our script is done then run first command
terraform init #Initiate present working dir with terraform
see below is the output of the command
After terraform initialize run
terraform fmt #This command make proper formate
After that run
terraform validate #This is validate the the script for any type of error and missing element.
Now run the the command
terraform plan #This command shows the plan of action after terraform apply
Now finaly we can apply the script with command
terraform apply #Now we get the all mentioned resources in script to GCP
Network VPC is created with subnet
Firewall for port 80 and 22 is created with script
Compute engine is created and access successfully.