Terraform Modules & Interview questions of Terraform
What is Terraform Modules ?
Modules serve as containers for organizing multiple resources that work collectively. Each module is comprised of a set of .tf and/or .tf.json files grouped within a directory.
The capability for a module to invoke other modules enables the seamless inclusion of the child module's resources into the configuration in a succinct manner.
Furthermore, modules have the flexibility to be invoked repeatedly, either within a single configuration or across distinct configurations. This facilitates the packaging and reuse of resource configurations.
Format on how to use modules:
Creating EC2 instance
Creating a AWS EC2 Instance resource "aws_instance" "server-instance" { # Define number of instance instance_count = var.number_of_instances # Instance Configuration ami = var.ami instance_type = var.instance_type subnet_id = var.subnet_id vpc_security_group_ids = var.security_group # Instance Tagsid tags = { Name = "${var.instance_name}" } }
Server Module Variables
# Server Module Variables
variable "number_of_instances" {
description = "Number of Instances to Create"
type = number
default = 1
}
variable "instance_name" {
description = "Instance Name"
}
variable "ami" {
description = "AMI ID"
default = "ami-xxxx"
}
variable "instance_type" {
description = "Instance Type"
}
variable "subnet_id" {
description = "Subnet ID"
}
variable "security_group" {
description = "Security Group"
type = list(any)
}
. Server module Output
# Output Section
output "server_id" {
description = "ID of the created server"
value = aws_instance.server-instance.id
}
Task-01
Explain the below in your own words and it shouldnt be copied from Internet ๐
Write about different modules Terraform.
- Terraform is this really cool tool that lots of people use to handle and set up cloud resources from different providers. What makes it stand out is how it's put together: you can break down your setup code into smaller chunks called modules. The awesome part? You can reuse these modules over and over again, especially handy when dealing with complex setups.
Let's break down the types of modules in Terraform:
Root Modules: These are like the big starting points for your Terraform setup. They hold the basics, like how to connect to your cloud provider and all the details to describe your resources.
Child Modules: Think of these as smaller modules living inside the main one. They're great for grouping related things together, making it much easier to handle.
Published Modules: These modules are shared with everyone on the Terraform Module Registry. This registry is like a public space where people share their modules so that others can use and improve them.
Each module has its own set of resources and settings that you can handle independently. This makes managing and testing your setup a breeze, and it encourages using your code in more than one place. You can either create your modules or use ones that others have shared on the Terraform Module Registry โ it's like this massive collection of useful tools created by the community.
Difference between Root Module and Child Module.
- The key difference between a root module and a child module in Terraform lies in their roles within the overall setup.
Root Module:
Picture the root module as the boss in a Terraform setup. It's the big shot, the starting point that holds crucial details like how to connect to your cloud provider and all the necessary info for your resources. Its responsibilities include kicking off Terraform, setting up providers, and specifying the required resources.
Child Module:
On the other hand, the child module is like the supporting actor. It's a smaller module tucked inside the main one, organized to bring related things together for easier management. A child module often wraps up a collection of resources with a specific purpose, acting like a reusable building block that can be utilized in different setups.
To add child modules within a root module, you use a module block. This block indicates where the module comes from and what input details it requires. The source could be a local file or something more distant, like a version control system or the Terraform Module Registry.
Important note: while root modules can discuss variables that everyone can see, including child modules, a child module can only discuss variables that are confined within its own module.
Is modules and Namespaces are same? Justify your answer for both Yes/No
- No, modules and namespaces aren't identical concepts, although they do share some similarities in certain situations.
Modules:
In Terraform, a module serves as a compact package of infrastructure code. It bundles together a set of related resources that can be repeatedly utilized in various setups. Modules streamline the process of using the same code in multiple locations, offering an orderly and reusable approach to managing complex setups.
Namespaces:
On the other hand, a namespace functions like a system for structuring names or labels to prevent confusion. It's a method of grouping items with similar names to avoid mix-ups. In programming, namespaces play a role in preventing naming clashes between different components of the code, such as modules, functions, or variables. They contribute to maintaining organization under a common label.
While both modules and namespaces contribute to organization and clarity, they fulfill slightly different roles. Modules in Terraform are primarily concerned with organizing and reusing infrastructure code, whereas namespaces are focused on maintaining name organization and preventing conflicts in programming.
Interview questions of Terraform
Q1. What is Terraform and how is it different from other IaaC tools?
- Terraform, created by HashiCorp, is a tool that lets you control your cloud infrastructure using code. Unlike other Infrastructure as Code (IaaC) tools, Terraform stands out because it can work with various cloud providers such as AWS, Azure, Google Cloud, and even on your own servers. It uses a consistent language and rules across all these providers. Terraform's unique "dry run" feature allows you to preview changes before applying them, reducing the risk of errors. It also keeps track of the current state of your infrastructure, aiding in managing complex setups.
Q2. How do you call a main.tf module?
- In Terraform, the main.tf file serves as the primary configuration file. It outlines the desired setup and is typically located in the main folder of a Terraform module. To use a module with a main.tf file, you include it in your Terraform code by creating a new configuration file. In this file, you add a "module" section, specifying the module's location (either a local file or an online repository) and assigning a special name to the module for reference in your Terraform code.
Q3. What exactly is Sentinel? Can you provide a few examples where we can use Sentinel policies?
- Sentinel acts like a set of rules for your infrastructure code, ensuring it follows guidelines and is secure, compliant, and cost-effective. Examples of Sentinel policies include checking compliance standards for virtual machine placement, ensuring storage accounts are encrypted securely, verifying resource group names follow specific conventions, limiting virtual machine creation in certain areas, and checking resources are labeled correctly for business reasons.
Q4. You have a Terraform configuration file that defines an infrastructure deployment with multiple instances of the same resource. How would you modify the configuration file to achieve this?
- In Terraform, to create multiple instances of the same resource, you can use either the count or for_each block in your configuration file. The count specifies how many copies you want, while for_each allows you to create one for each item in a list. This approach makes your configuration cleaner and more organized, avoiding repetitive code.
Q5. How do you enable debug messages in Terraform to find out from which paths providers are loading?
- To enable debug messages in Terraform and find out from which paths providers are loading, you set the environment variable TF_LOG=TRACE
. This global setting provides detailed debug logs, including information about provider loading paths during Terraform execution.
Q6. While using "terraform destroy" to remove everything, how would you save a specific resource from deletion?
- When using terraform destroy
to remove everything, you can save a specific resource from deletion by using the -target
option. For example, terraform destroy -target=aws_instance.example
would only remove the specified AWS instance while leaving other resources untouched.
Q7. Which module is used to store .tfstate file in S3?
- The Terraform module terraform/backend
is utilized for storing the .tfstate
file in an S3 bucket. This module facilitates setting up a remote backend in S3 and configuring Terraform to save its state in that location.
Q8. How do you manage sensitive data in Terraform, such as API keys or passwords?
- Sensitive data in Terraform, like API keys or passwords, can be managed using Terraform input variables, environment variables, external secret tools (e.g., Vault or AWS Secrets Manager), or encrypted state files. Input variables prompt users for sensitive information during the Terraform run, while environment variables keep private data separate from the main configuration.
Q9. To provision an S3 bucket and a user with read and write access, what resources would you use and how would you configure them?
- To provision an S3 bucket and a user with read and write access in Terraform, you would use resources such as aws_s3_bucket
, aws_iam_user
, aws_iam_access_key
, and aws_s3_bucket_policy
. The configuration file would define settings for the S3 bucket, IAM user, access keys, and permissions via a bucket policy, ensuring the user can read and write objects in the bucket.
Q10. Who maintains Terraform providers?
- Terraform providers are maintained by a collaboration between the open-source community and the companies that own the providers. The community contributes code, reports bugs, and suggests features through the GitHub repository. Meanwhile, provider-owning companies (e.g., AWS, Google Cloud, Microsoft Azure) ensure their providers work seamlessly with their services, updating them as needed. Providers are often updated independently of the main Terraform project, allowing for flexibility and expansion.
Q11. How can we export data from one module to another in Terraform?
- In Terraform, you can share data from one module to another using outputs. By defining an output in the outputs.tf
file of the source module, you expose values for use in other modules or external references. To access this data in the destination module, you use the syntax <module_name>.<output_name>
. This approach allows for effective communication and data sharing between different parts of your Terraform configuration.