Exam Prep Flashcards
What does terraform init do?
The terraform init command initializes a working directory.
Initialization includes installing provider plugins, backend initialization, copy source modules, etc.
This is the first command that should be run after writing a new terraform config, its safe to run multiple times.
Terraform init -upgrade
The terraform init -upgrade installs the latest module and provider versions allowed within the configured constraints.
If you have the latest provider plugin already installed and define a new version constraint that matches different version you will need to run terraform init -upgrade.
Terraform plan
It allows you to create an execution plan.
The infrastructure is not modified as part of this plan.
The state file is not modified even when it detects drift in real-world and current infrastructure.
How to save the plan to a file?
-out=FILE option to save the generated plan to a file on disk, which can later execute by passing the file to terraform apply as an extra argument (terraform apply ec2.plan, for ex).
Terraform apply
Used to apply the changes required to reach the desired state of the config.
The state file gets modified in this command
Name of state file = terraform.tfstate.
Terraform apply can change, destroy, and provision resources but cannot import any resources.
Terraform destroy
Used to destroy the terraform-managed infrastructure
terraform destroy command is not the only command through which infrastructure can be destroyed.
* You can also either comment out the code in the code or delete the code entirely.
Terraform fmt
Used to rewrite terraform config files to a canonical format/style. It will directly perform “write” operation and not “read” as in it will not ask for confirmation and just format.
Two flags:
1. -check | Checks if input is formatted, files not modified.
2. -recursive, also process files in subdirectories, by default only the given directory (or current directory) is processed.
Terraform validate
It validates the config files in a directory.
It requires an initialized working directory with any referenced plugins/modules installed, i.e n
Terraform plan uses implied validation check (even if you don’t perform a terraform validate)
Whats a resource block?
A resource block declares a resource of a given type (“aws_instance) with a given local name (“web”)
Resource type and name together serve as an identifier for a given resource and so must be unique.
Address of the resource is resource type.localname
Ex: aws_instance.web
The statements inside the resource is made up of the argument name and argument value.
Ex: ami = “ami-123”
Terraform refresh? whats it do again?
The terraform refresh command reads the current settings from all managed remote objects and updates the terraform state to match.
This wont modify your real remote objects, but it will modify the terraform state.
This command is DEPRACATED, because its default behavior is unsafe.
Are arrays possible in Terraform?
No
Why is the terraform state command used?
Its used for advanced state management
Terraform import
You can use import blocks to import more than one resource at a time
Local values
Locals are used whne you want to avoid repeating the same expression multiple times
Local values are created by a locals block (plural), but you reference them as attributes on an object named local (singular)
Local values can reference values from other variables, locals, etc.
Terraform Modules
Terraform modules allow us to centralize the resource config, and it makes it easier for multiple projects to re-use the terraform code.
Instead of writing code from scratch, we can re-use.
Modules source code can be present in a wide variety of locations.
Github, local pths, terraform reg, s3 buckets.
To reference a module, you need to make use of module block and source.
Terraform uses this during the module installation step of terraform init to download the source code to a directory on local disk so that other terraform commands cna use it.
Module local paths
A local path must begin with either ./ or ../ to indicate a local path.
Module sourced from local paths do NOT support versions
Git repository module
Arbitrary Git repositories can be used by prefixing the address with the special git:: prefix.
Root vs child modules
Root modules reside in the main working directory of terraform config. This is the entry point of infrastructure definition.
A module that has been called by another module is referred to as the child module.
Module outputs
A child module can use outputs to expose a subset of its resource attributes to a parent module.
Format: <MODULE>.<OUTPUT></OUTPUT></MODULE>
Module versioning
When using modules installed from a module registry, Hashicorp recommends explicitly constraining the acceptable version #’s to avoid unexpected or unwanted changes.
It is not mandatory to specify a version argument
Terraform registry
Hosts a broad collection of public terraform modules
Each terraform module has an associated address
A module address has the syntax hostname/namespace/name/system.
The hostname/ portion of a module is optional, and if omitted defaults to the namespace and beyond.
Ex: registry.terraform.io would drop off if not included and reduce to
source = “terraform-aws-modules/ec2-instance/aws”
Functions in terraform
the terraform language includes a # of built-in functions that you can use to transform and combine values.
NO SUPPORT for user-defined functions
Function categories
Numeric = abs, ceil, floor, max min
String = concat, replace, split, join, tolower, toupper
Collection - element, keys, length, merge, sort, slice
Fiesystem - file, filebase64, dirname
Lookup function
Lookup retrieves the value of a single element from a map, given its key. If the given key does not exist, the given default value is returned instead.
Zipmap function
zipmap constructs a map from a list of keys and a cooresponding list of values
Index function
Index find the element index for a given value in a list.
Element function
retrieves a single element from a list.
Toset function
Converts the list of values to SET.
Timestamp function
returns a UTC time stamp in RFC 3339 format
File function
can reduce the overall TF code size by loading contents from external sources during TF operations.
Meta arguments
Meta arguments are added within resource block, which allows some details of this standard resource behavior to be customized on a per-resource basis.
Meta-arugments
depends on, count, for_each, lifecycle, provider
Sentinal
Sentinal is an embedded policy-as-code framework integrated with hashicorp enterprise products.
It’s a proactive service, can be used for various use-cases like:
Verify if EC2 instance has tags, verify if S3 bucket has encryption enabled.
Sentinal runs after terraform plan but before terraform apply.
Terraform graph
Refers to a visual representation of the dependency relationship b/w resources defined in TF config
The output of TF graph is in the DOT format, which can be easily be converted to an image.
Input variables
Terraform.tfvars can be used to define values to all variables.
This approach leads to easier setup for multi-project deployments
How to select specific .tfvars
-var-file=”fname.tfvars”
Declaring Variable Values.
- Variable defaults in a .tf file
- Variable Definition (*.tfvars)
- Env variables
- Setting variables as part of command line (-var=” argname=argvalue”)
Setting variable values through ENV variables?
Terraform searches the ENV of its own process for ENV variables named TF_VAR_ followed by the name of a declared variable.
echo %TF_VAR_instance_type%
Variable definition precedence
Later sources taking precedence over earlier ones.
- ENV variables
- .tfvars file, if present
- .tfvars.json file, if present.
- Any *.auto.tfvars or *.auto.tfvars.json
file, processed in lexical order of filename
5.Any -var and -var-file options on CMD line.
Variables with undefined values
If you have variables with undefined values, it will NOT directly result in an error, you’ll get prompted to enter a value.
Are there certain words you can not use as a variable name?
Yes, we cannot use all words within variable names.
Ex: count, depends_on
for_each
lifecycle
providers
source
Regarding input variables and state files
TF state files generally store details about the resource it manages.
Various aspects like “input variables” are not stored.
Output vales will be stored in state file but not the description.
Whats the order of logging from most verbose to least verbose?
Terraform (Trace)
Does (Debug)
Improve (Info)
With (Warnings)
Excellence (Error)
By default, how many resources will Terraform provision concurrently during a terraform apply? with reference to TF reducing time it takes to provision resources through the concept of parallelism?
By default, Terraform Enterprise allocates 512 MB of memory to each Terraform run, with a default concurrency of 10 parallel runs.
What command replaced the depracated terraform refresh?
Terraform plan -refresh-only
What does terraform plan -refresh-only do?
This command is used to create a plan whos goal is only to update the TF state to match any changes made toe remote objects outside of TF. It does NOT apply those changes to the state.
When using variables in HCP Terraform, what level of scope can the variable be applied to?
- Run-specific
- Workspace-specific
- Workspace-scoped variable set (apply to multiple workspaces w/in same org)
- Project-scoped variable set (auto apply to all current/future workspaces w/in project
- Global variable set (auto applied to all current/future workspaces w/in an org.
What are the core Terraform workflow steps to use infrastructure as code?
Write, plan, apply.
What Terraform command can be used to inspect the current state file?
Terraform show - The ‘terraform show’ command is used to inspect the current state file in Terraform. It displays the current state as Terraform sees it, including resource attributes and dependencies.
In the terraform block, which configuration would be used to identify the specific version of a provider required?
required_providers.
The correct configuration to identify the specific version of a provider required is the “required_providers” block in the terraform configuration. This block allows you to specify the provider name and version constraints, ensuring that the correct version of the provider is used for the Terraform configuration.
Which Terraform features supports the versioning of a module?
- Terraform registry
- Private registry
What does not support
3. modules stored in GitLab - it can store modules but doesnt support versioning.
Infrastructure as code makes infrastructure changes that are
- indempotent (the outcome of applying the same config multiple times will always result in the same desired state)
- predictable
- Consistent
- repeatable
The environment variables must be in the format of …
TF_VAR_VARNAME=VALUE
Ex: TF_VAR_region=us-west-1
What are some of the benefits of using IaC code in an org?
- IaC code can be used to manage infra on multiple cloud platforms.
- IaC allows you to commit configs to version control to safely collab on infra
- IaC uses a human-readable config language to help you write infra code quickly, enabling self-service for dev’s/operators alike.
- API-driven workflows are a key advantage, allows for automation/programmability of infra provision/mgmt
What are the supported VCS providers for HCP Terraform?
- Azure Devops (Server/Services)
- Bitbucket (Cloud/Data Center)
- Gitlab (.com/EE/CE)
- Github (Enterprise/Oath/TFE.com)
What tasks can the terraform state command be used for?
Modifying the current state, such as removing items (Ex: listing resources, removing resources from the state file, adjusting the provider, etc.)
- Inspecting the state - Terraform state show
- Updating the state - State MV and State RM
- Pulling/pushing state - State Pull, State Push
- Importing resources into TF - TF state import
Whats the use of terraform apply -replace=name.web?
Using this command allows a specific resource to be marked for replacement without affecting the other resources that were created. This command is useful for quickly recreating a single resource.
What backend options are supported by TF?
- Local
- remote - stores state in remote location, such as s3. bucket, Consul server, or TF enterprise instance.
- consul -backend stores TF state in a Consul cluster.
- S3 backend, stores TF state in an S3 bucket, making it highly available and durable storage solution.
What command can be ran to validate the changes to infrastructure without impacting existing workloads?
Terraform plan is the best answer.
Terraform validate isn’t correct as it will check syntax and config of TF files, but it does not provide a preview of the changes.
When you migrate a TF config from say a local setup (Terraform community) to HCP Terraform (and create a new workspace), what TF. version would the new workspace be configured to use after the migration?
HCP TF would configure the workspace to use the same version as the TF binary you used when migrating.
When you add a new module to a configuration, Terraform must download it before it can be used. What two commands can be used to download and update modules?
Terraform init
Terraform get - download/update modules declared in the root module. Modules are downloaded into a .terraform subdirectory.
Whats the command to create a new workspace in TF
terraform workspace new <workspacename></workspacename>
What CLI commands will completely tear down and delete all resources that Terraform is currently managing?
- Terraform destroy (This command is just a convenience alias for terraform apply -destroy)
- terrform apply -destroy
What are some of the benefits that Terraform providers offers to users?
- Abstracts the target platform’s API from the end-user
- enables a plugin architecture that allows TF to be extensible w/o having to update Terraform core.
- Enables the deployment of resources to multiple platforms, such as public cloud, private cloud, or other Saas, Pass, IaaS services.
Whats true regarding Terraform variables?
- the default value will be found in the state file if no other value was set for the variable.
- Variables names themselves arent stored in the state file.
When using TF, where can you install providers from?
- official hashicorp release site
- Terraform registry
- Terraform plugin cache.
- plugins directory
Are official terraform providers and modules owned AND maintained by Hashicorp?
Yes, these providers/modules are developed and supported directly by Hashicorp to ensure compatibility, reliability, and security for TF users.
How do you properly configure a Terraform backend?
Backends are configured with a nested backend block within the top-level terraform block.
* A config can only provide one backend block
*A backend block cannot refer to named values (like input varaibles, locals, or data source attributes), it REQUIRES constant values.
How do you reference a value of a variable when using a for_each argument in a resource block?
A for _each argument will iterate over a map/set of strings and create a similar instance/resource for each item in the map/set.
each.value.variable
What are examples of collection/structural types that can be used when declaring a variable in order to group values together?
- Object - allows you to create a complex data structure w/multiple attributes, useful for grouping related data together in a hierarchical manner.
- Map
- List.
- Tuple - allows you to create an ordered collection of elements of different types.