Skip to content

Instantly share code, notes, and snippets.

@ashokbalaraman
Created December 16, 2022 02:31
Show Gist options
  • Select an option

  • Save ashokbalaraman/f66a54c1605725bdccfdb6febb9c7431 to your computer and use it in GitHub Desktop.

Select an option

Save ashokbalaraman/f66a54c1605725bdccfdb6febb9c7431 to your computer and use it in GitHub Desktop.
Terraform Associate Certification - Notes
Best Practices: https://www.terraform-best-practices.com/code-structure
Naming Convention: https://www.terraform-best-practices.com/naming
1. AWS Hardening Guidelines (There is a 156 Page guideline)
2. Convert this hardening guidelines into Terraform code
3. Configuration Management (Chef, Puppet, Ansible,..) vs Infrastructure Orchestration (Terraform, CloudFormation,..)
4. Terraform can do both configuration management and infrastructure orchestration
5. Terraform Init downloads all the plugins associated with the "provider" (check this under the directory .terraform/providers/registry.terraform.io/hashicorp/aws/…..
6. Terraform.tfvars vs variables.tf
7. Use conditional expression to handle environment specific workflow
8. Use local values for tagging. You can differential common_tags and private tags
9. Terraform console
10. Use file function to specify ssh keys
11. Use lookup function to get the existing values. Try element function to retrieve elements of a list
12. Learn data block for specifying AMI
13. Do we need our own AMI, that is hardened as per standards?
14. Try --filters in Data Sources while choosing an AMI
15. Use environment variable TF_LOG for debugging. Log levels are TRACE, DEBUG, INFO, WARN or ERROR
16. To persist the log output set TF_LOG_PATH
17. Terraform format (terraform fmt)
18. Terraform validate
19. Use SET datatype (toset converts list to set)
20. Use For Each to avoid replication count challenge
21. Use dynamic block for ingress & egress
22. Use Terraform Taint to destroy and recreate. Taint doesn't modify
23. Use Splat function to get a list of sth based on a wildcard character(splat)
24. Save plan to file to avoid someone accidentally changing
25. Terraform output to check the values of the variables
26. Check Terraform Settings (terraform.required_version, terraform.required_providers.aws.source,..). Use this to specify > 0.12 as lots of format has changed
27. BP: Switch to smaller configuration where each can be applied independently (ec2.tf, rds.tf,….)
28. BP: Terraform plan refreshes state of each resource. You can use -target=resource and refresh=false to target a specific resource in a large file to avoid lots of API calls
29. Use zipmap for associating key value pairs in 2 different lists
30. Count is a Meta-Argument. If your resource are identical, it is appropriate (5 count of EC2 that are t3.micro). If distinctive values are needed use for_each Meta-Argument (5 ec2 of different instance types)
31. Use Terraform Provisioners to install once the infrastructure is created (Ex. Install Nginx after the EC2 is created)
32. Provisioners should only be used as a last resort, as for common situations there are better alternatives
33. Provisioners are inside the resource block
34. 2 Types of Provisioners (Local Exec (run sth where you are running terraform apply. Ex. Echo output) & Remote Exec (run sth which you created using tf. Ex. Install nginx on EC2 that you just created)
35. Checkout available provisioners
36. 2 Types of Provisioners (creation-time-provisioner & destroy-time-provisioner)
37. Use null_resource to test and conditionally create other resources. Ex. Curl url before creating an EIP
38. DRY = Don't Repeat Yourself is the principle of software development aimed at reducing repetition of software patterns
39. Use modules to define a software pattern. Ex. Module will have the EC2 instance resource, and the ec2.tf will refer the module using the key "source". Name the directory "modules". You can also create a folder for project
40. Module (D), projects (D), providers.tf, backend.tf,
41. In module do not hard code any attribute that will change between environments. Ex. Instance_type (small in dev, medium in uat and large in prod). Use a variable in the module to get around this issue
42. As variables can be over-ridden by an user, you can use locals to enforce declaring as a variable and prevent from the value being over-ridden
43. Check Terraform Registry for verified modules. Super helpful while compiling the code. Read the "Notes" section.
44. Standard Module Structure aka file and directory layout
45. Terraform Workspace. Master this. Create separate workspace for Sbx, uat & prod. (terraform workspace list, terraform workspace select prd, terraform workspace -h
46. Terraform allows us to have multiple workspaces, with each of the workspace, we can have a different set of environment variables
47. Workspaces allow multiple state files of a single configuration
48. Terraform Modules centralizes the terraform resources and can call out from TF files whenever required
49. Every Terraform configuration has atleast one module, called the root module, which consists of resources defined in the .tf files in the main working directory
50. A module can call other modules, which lets you include the child module's resources into the configuration in a concise way
51. A module that includes a module block like the following is the calling module of the child module
Module "servers" {
source = "./app-cluster"
servers = 5
}
52. The resources defined in the module are encapsulated, so the calling module cannot access their attributes directly. However, the child module can declare output values to selectively export certain values to be accessed by the calling module
53. Never git commit terraform.tfstate (as it might have passwords while using a file function)
54. You can use git based modules as well. i.e leave the code in git and do terraform init based on the git repo, including reference to a branch
55. Crash.log. Check github.com-> gitignore repository for recommended gitignores specific to terraform (https://github.com/github/gitignore/blob/main/Terraform.gitignore)
56. Terraform.tfstate SHOULD NOT BE backed in git. S3 or DynamoDB is an option.
57. BF: TF Files should go to Git repo and .tfstate should go to central backend (S3/DynamoDB/Kubernetes). Check available Terraform Backends
58. What about S3 versioning?
59. State locking is implemented through DynamoDB, as S3 doesn't support locking.
60. Use force-unlock command to unlock the state if the unlocking process has failed. Use cautiously
61. Use "time_sleep" resource to wait n seconds
62. Terraform state list, terraform state mv, terraform state pull, terraform state rm,
63. Create linux alias tf for terraform
64. Terraform_remote_state retrieves root module output values from some other terraform configuration, using the latest snapshot from the remove backend
65. Do Terraform Import to bring manual infrastructure as IaC. It cannot create configuration. You create the configuration and use it to bring it to current state = desired state
66. Use alias variable to use multiple regions from the same provider (aws->us-west-2, us-east-1,..). This is very common scenario in production. You can use profile key to handle multiple accounts as well. Try this.
67. In provider.tf, use STS to retrieve the token. Always use temporary credentials
68. Use sensitive=true in output to mask password. Remember this doesn't encrypt or redact in .tfstate
69. Check out Dynamic Secretes with AWS (Lease Duration)
70. There is a "vault" provider. Checkout for something similar for "secrets manager".
71. Sentinel is an embedded policy-as-code framework integrated with the HashiCorp Enterprise Products
72. Sentinel - Enables fine-grained, logic-based policy decisions and can be extended to use information from external resources. Sentinel policies are a paid feature. Check if AWS has similar functionality. Enable this for the team.
Ex. Block EC2 creation without tags, Disallow 0.0.0.0/0 for any inbound, Verify if the bucket encryption is enabled
73. Sentinel checks stand in between terraform plan and apply. If the rules pass, terraform apply runs. If the rules fail, the terraform apply is skipped
74. If you manage sensitive data with Terraform, treat the state itself as sensitive data. Terraform cloud always encrypts the state at rest and protects it with TLS in transit. Terraform cloud also knows the identity of the user requesting state and maintains a history of state changes
75. Terraform Graph command is used to generate a visual representation of either a configuration or execution plan. The output of the terraform graph is in the DOT format, which can easily be converted to an image.
76. Provider Configuration block is NOT mandatory for all the terraform configuration
77. Terraform output extracts the output values from the state file
78. Terraform Refresh doesn't modify the infrastructure, but modifies the state file
79. Slice is not a part of string function, whereas, join, split, chomp are a part of it
80. It is not mandatory to include the module version argument while pulling the code from terraform registry
81. Environment Variables can be used to set variables. The environment variables must be of the form TF_VAR_name
82. Emma is a Terraform expert, and she has automated all the things with Terraform. During a recent deployment, a virtual machine was deployed but a local script did not work correctly, and therefore needs to be destroyed and recreated. How can Emma easily have Terraform recreate this one resource without having to destroy everything that was created?
The terraform apply -replace command manually marks a Terraform-managed resource for replacement, forcing it to be destroyed and recreated on the apply execution.
You could also use terraform destroy -target <virtual machine> and destroy only the virtual machine and then run a terraform apply again.
IMPORTANT - PLEASE READ
This command replaces terraform taint, which was the command that would be used up until 0.15.x. You may still see terraform taint on the actual exam until it is updated.
83. There is no Terraform binary for AIX. Terraform is available for macOS, FreeBSD, OpenBSD, Linux, Solaris, and Windows.
84. The existence of a provider plugin found locally in the working directory does not itself create a provider dependency. The plugin can exist without any reference to it in the Terraform configuration.
85. True or False? Rather than use state, Terraform can inspect cloud resources on every run.
State is a necessary requirement for Terraform to function. And in the scenarios where Terraform may be able to get away without state, doing so would require shifting massive amounts of complexity from one place (state) to another place (the replacement concept).
86. Select the most accurate statement to describe the Terraform language from the following list.
Terraform is an immutable, declarative, IaC configuration management language based on HCL (Hashicorp Configuration Language) , or optionally JSON
87. When you add a new module to a configuration, Terraform must download the module before it can be used. What two commands can be used to download and update modules? (select two)
terraform init & terraform get
88. What are some of the problems of how infrastructure was traditionally managed before Infrastructure as Code? (select three)
Businesses are making a transition where traditionally-managed infrastructure can no longer meet the demands of today's businesses. IT organizations are quickly adopting the public cloud, which is predominantly API-driven.
To meet customer demands and save costs, application teams are architecting their applications to support a much higher level of elasticity, supporting technology like containers and public cloud resources. These resources may only live for a matter of hours; therefore the traditional method of raising a ticket to request resources is no longer a viable option
Pointing and clicking in a management console is NOT scale and increases the change of human error.
89. In the terraform block, which configuration would be used to identify the specific version of a provider required?
Required_providers
90. What is the purpose of using the local-exec provisioner? (select two)
To execute one or more commands on the machine running Terraform
To invoke a local executable
91. When configuring a remote backend in Terraform, it might be a good idea to purposely omit some of the required arguments to ensure secrets and other relevant data are not inadvertently shared with others. What are the ways the remaining configuration can be added to Terraform so it can initialize and communicate with the backend? (select three)
Interactively
File
Command Line KV pairs
92. In order to make a Terraform configuration file dynamic and/or reusable, static values should be converted to use what?
Input Variables
93. Variables and their default values are typically declared in a main.tf or variables.tf file. What type of file can be used to set explicit values for the current working directory that will override the default variable values?
.tfvars file
94. Which of the following commands can be used to detect configuration drift?
Terraform apply -refresh-only
95. Which of the following are the benefits of using modules in Terraform? (select three)
Enables Code Reuse
Supports modules stored locally or remotely
Supports versioning to maintain compatibility
96. You have a Terraform configuration file defining resources to deploy on VMware, yet there is no related state file. You have successfully run terraform init already. What happens when you run a terraform apply?
If there is no state file associated with a Terraform configuration file, a terraform apply will create the resources defined in the configuration file. This is a normal workflow during the first terraform apply that is executed against a configuration file. This, of course, assumes that the directory has been initialized using a terraform init
97. Given the following snippet of code, what does servers = 4 reference?
module "servers" {
source = "./modules/aws-servers"
servers = 4
}
Ans: The value of an input variable
98. Which of the following best describes a "data source"?
Enables terraform to fetch data for use elsewhere in the terraform configuration
Margaret is calling a child module to deploy infrastructure for her organization. Just as a good architect does (and suggested by HashiCorp), she specifies the module version she wants to use even though there are newer versions available. During a terrafom init, Terraform downloads v0.0.5 just as expected.
What would happen if Margaret removed the version parameter in the module block and ran a terraform init again?
Ans: Terraform would use the existing module already downloaded
99. Which of the following best describes the primary use of Infrastructure as Code (IaC)?
The ability to programmatically deploy and configure resources
100. Given the code snippet below, how would you refer to the value of ip for the dev environment if you are using a for_each argument?
variable "env" {
type = map(any)
default = {
prod = {
ip = "10.0.150.0/24"
az = "us-east-1a"
}
dev = {
ip = "10.0.250.0/24"
az = "us-east-1e"
}
}
}
Ans: each.value.ip
101. You are using modules to deploy various resources in your environment. You want to provide a "friendly name" for the DNS of a new web server so you can simply click the CLI output and access the new website. Which of the following code snippets would satisfy these requirements?
Output "website" {
description = "Some description"
value = "https://${module.web.public.dne}:8080/index.html"
}
102. You have declared a variable named db_connection_string inside of the app module. However, when you run a terraform apply, you get the following error message:
Since the variable was declared within the module, it cannot be referenced outside of the module
103. True or False? In both Terraform OSS and Terraform Cloud/Enterprise, workspaces provide similar functionality of using a separate state file for each workspace.
True
104. True or False? Official Terraform providers and modules are owned and maintained by HashiCorp.
True
105. What CLI commands will completely tear down and delete all resources that Terraform is currently managing? (select two)
Terraform destroy
Terraform apply -destroy
106. You want to use Terraform to deploy resources across your on-premises infrastructure and a public cloud provider. However, your internal security policies require that you have full control over both the operating system and deployment of Terraform binaries. What versions of Terraform can you use for this? (select two)
Terraform OSS/CLI
Terraform Enterprise
107. When initializing Terraform, you notice that Terraform's CLI output states it is downloading the modules referenced in your code. Where does Terraform cache these modules?
.terraform/modules
108. You want to use a Terraform provisioner to execute a script on the remote machine. What block type would use to declare the provisioner?
Resource block
109. Which of the following are advantages of using infrastructure as code (IaC) for your day-to-day operations? (select three)
Provides the ability to version control the infrastructure and the application architecture
Enables self-service for developers and operators alike
API-driven workflows
110. Which of the following Terraform versions offer the ability to use a private module registry? (select three)
Terraform Cloud for Business
Terraform Cloud (free)
Terraform Enterprise
111. True or False? When developing Terraform code, you must include a provider block for each unique provider so Terraform knows which ones you want to download and use.
False. Unlike many other objects in the Terraform language, a provider block may be omitted if its contents would otherwise be empty. Terraform assumes an empty default configuration for any provider that is not explicitly configured. In other words, if you don't have any specific configurations for your provider, you may indeed leave it out of your configuration.
112. Beyond storing state, what capability can an enhanced storage backend, such as the remote backend, provide your organization?
Execute your terraform on infrastructure either locally or in Terraform cloud
113. True or False? Under special circumstances, Terraform can be used without state.
False
114. You have a number of different variables in a parent module that calls multiple child modules. Can the child modules refer to any of the variables declared in the parent module?
No, it can only refer to the variables passed to the module
115. You have declared the variable as shown below. How should you reference this variable throughout your configuration?
variable "aws_region" {
type = string
description = "region used to deploy workloads"
default = "us-east-1"
validation {
condition = can(regex("^us-", var.aws_region))
error_message = "The aws_region value must be a valid region in the USA, starting with \"us-\"."
}
}
Ans: var.aws_region
https://developer.hashicorp.com/terraform/language/expressions/references#input-variables
116. True or False? In order to use the terraform console command, the CLI must be able to lock state to prevent changes.
True
117. How can you reference all of the subnets that are created by this resource block?
#Deploy the private subnets
resource "aws_subnet" "private_subnets" {
for_each = var.private_subnets
vpc_id = aws_vpc.vpc.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, each.value)
availability_zone = tolist(data.aws_availability_zones.available.names)[each.value]
tags = {
Name = each.key
Terraform = "true"
}
}
Ans: aws_subnet.private_subnets[*]
Areas to focus:
1. Modules
2. Terraform state mv and all those
3. Available functions
4. Types of blocks (terraform, resource, provider & data)
5. Understand the offering of Terraform Cloud Free vs Business vs Team
Handson:
https://github.com/aws-samples/terraform-eks-code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment