Terraform-Associate Flashcards

1
Q

How would you describe a Terraform workflow?

A

Write > Plan > Apply

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does terraform init command do?

A

It initializes and sets up the working directory containing your Terraform code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
variable "replicas" {
  type = number
  default = 5
}
What will be passed into the code for the variable replicas when given the following command?

terraform apply -var replicas=1

A

1

While the default number of replicas in the Terraform source code is 5, the code being passed is explicitly providing a replicas variable value of 1 at execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can Terraform input variables be defined?

A

They can be predetermined in a file.

They can be pulled down from Terraform Cloud and referenced in your code.

They can be included in the command-line options.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which of the following best describes Terraform providers?

A

A plugin that enables Terraform to interface with the API layer of various cloud platforms and environments.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the default name of the file where Terraform state is stored when working locally?

A

terraform.tfstate

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What format is the Terraform state file stored in?

A

JSON

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Which are the uses of the Terraform output variables?

A

A root “module” can use outputs to print certain values in the CLI output after running terraform apply.

A child “module” can use outputs to expose a subset of its resource attributes to a parent module.

When using a remote state, “root module” outputs can be accessed by other configurations via a “terraform_remote_state” data source.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can Terraform Providers be sourced in Terraform?

A

You can reference providers from an internal registry in your Terraform code.

You can reference providers locally in your Terraform configuration.

By default, Terraform looks for providers in the Terraform provider registry.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

True or False? Terraform provisioners help bootstrap custom commands onto the resources being deployed via Terraform.

A

Terraform provisioners can help execute custom scripts and commands on resources. The best practice is to avoid using them if a built-in mechanism is provided by the resource API itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Where in Terraform code can you configure where the state file is stored?

A

In the terraform block, using the backend attribute.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Which command would you use to see all the resources that have been created and are being tracked by the Terraform state file?

A

terraform state list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What benefits does storing Terraform state remotely offer?

A

It provides granular:

  • access
  • integrity
  • security
  • availability
  • collaboration.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does the terraform state mechanism do?

A

It maps real-world resources to Terraform configuration/code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How does Terraform handle dependencies in your infrastructure when deploying or destroying resources?

A

It handles them via the Terraform state file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

In what file is your Terraform state stored locally?

A

terraform.tfstate

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How can Terraform module code return outputs to be used by the main Terraform code invoking it?

A

By using output block resources in the Terraform module code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Where can Terraform find and download modules referenced in code?

A
  • Local system

- Terraform Registry

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Given the following snippet of Terraform code:

module "my-test-module" {
  source = "./testm"
  version = "0.0.5"
  region = var.datacenter
}
Which of the attributes in the above snippet is an input being provided to the module?
A

region

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is one of the main purposes of Terraform modules?

A

To make code reusable elsewhere and avoid reinventing the wheel.=

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the command used in Terraform to format the code?

A

terraform fmt

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the flag that can be used to bypass approval entry?

A

–auto-approve

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Which of the following data types represent a primitive type value in Terraform?

A

Number, String, Boolean

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

The dynamic blocks feature in Terraform cannot be used with which of the following types of resources?

A

lifecycle blocks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

True or False? Collection variable types allow multiple values of one primitive type variable to be grouped together.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

True or False? In Terraform, you can create your own user-defined functions.

A

False Terraform comes pre-packaged with a number of built-in functions. Users cannot create their own functions like in a programming language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Given the following snippet of Terraform code:

variable "training" {
  type = object({
    name = string
    age = number
  })
  default = {
    name = "Ryan"
    age = 36
  }
}
Which of the following type constraints can the variable configured in the code be classified as?
A

Structural

A structural variable type allows multiple values of various primitive types to be grouped together as a single value. In this case, the variable training has 2 separate types of values within it, namely a string and a number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Which environment variable can you set to show the most verbose debug logs possible when running Terraform commands?

A

TF_LOG=TRACE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Which of the following commands will allow you to change your current workspace to an already existing workspace named “production”?

A

terraform workspace select production

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What does the terraform fmt command do?

A

It formats your Terraform code for readability and consistency.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

True or False? When working locally, Terraform always starts off with a single workspace called default that cannot be deleted.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What effect will the following command have on the terraform resource aws_instance.my-vm?

terraform taint aws_instance.my-vm

A
  • It will mark the resource as tainted in the state file
  • It will be deleted
  • Re-created upon the next terraform apply.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is the purpose of the terraform import command?

A

It brings external, unmanaged resources into your Terraform configuration to be tracked and managed by it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is the purpose of Terraform Cloud?

A

It helps teams use Terraform together.

Easy access to shared state and secret data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Which of the following statements is NOT accurate about the difference between open-source Terraform workspaces and Terraform Cloud workspaces?

A

Open-source Terraform workspaces can automatically back up your configuration to Terraform Cloud.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What is the Terraform public registry?

A

A repository of publicly available Terraform providers and modules.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What are the benefits of using HashiCorp Sentinel with your Terraform deployments?

A
  • makes deployments more secure

- act as protection against accidental deployments.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

How can HashiCorp Vault help secure your Terraform deployments?

A
  • It can store your long-lived credentials in a secure way

- “dynamically inject short-lived”, “temporary keys” to Terraform at deployment.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is HashiCorp Sentinel?

A

A policy-as-code framework that enforces adherence to policies within your Terraform code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What does the Terraform Vault provider offer Terraform users?

A

A secure place to manage access to the secrets for your Terraform configurations, in addition to integrating with other popular cloud vendors.

Provides short-lived, temporary credentials for users with only the permissions needed for infrastructure creation.

Allows you to store sensitive data securely that can be used for your Terraform configurations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Which one of the following answers is NOT a key benefit of Terraform Cloud?

A

A built-in version control similar to GitHub

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Why is it a good idea to declare the required version of a provider in a Terraform configuration file?

A

providers are released on a separate schedule from Terraform itself; therefore a newer version could introduce breaking changes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

After executing a terraform plan, you notice that a resource has a tilde (~) next to it. What does this infer?

  • Terraform can’t determine how to proceed due to a problem with the state file
  • the resource will be destroyed and recreated
  • the resource will be updated in place
  • the resource will be created
A

the resource will be updated in place

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Which of the following best describes a Terraform provider?

A

a plugin that Terraform uses to translate the API interactions with the service or provider

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Which flag would be used within a Terraform configuration block to identify the specific version of a provider required?

A

required_providers

For production use, you should constrain the acceptable provider versions via configuration file to ensure that new versions with breaking changes will not be automatically installed by Terraform init in the future. When terraform init is run without provider version constraints, it prints a suggested version constraint string for each provider

For example:

 terraform {
  required_providers {
    aws = ">= 3.1.0"
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

You want to use terraform import to start managing infrastructure that was not originally provisioned through infrastructure as code. Before you can import the resource’s current state, what must you do in order to prepare to manage these resources using Terraform?

  • run terraform refresh to ensure that the state file has the latest information for existing resources.
  • shut down or stop using the resources being imported so no changes are inadvertently missed
  • update the configuration file to include the new resources
  • modify the Terraform state file to add the new resources
A

update the configuration file to include the new resources

Explanation
The current implementation of Terraform import can only import resources into the state. It does not generate a configuration. Because of this, and prior to running terraform import, it is necessary to manually write a resource configuration block for the resource to which the imported object will be mapped.

First, add the resources to the configuration file:

resource "aws_instance" "example" {
  # ...instance configuration...
}
Then run the following command:

$ terraform import aws_instance.example i-abcd1234

https://www.terraform.io/docs/commands/import.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What does the command terraform fmt do?

A

rewrite Terraform configuration files to a canonical format and style

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

HashiCorp offers multiple versions of Terraform, including Terraform open-source, Terraform Cloud, and Terraform Enterprise. Which of the following Terraform features are exclusive to the Enterprise edition? (select one)

A
  • Clustering
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

By default, where does Terraform store its state file?

A

current working directory

By default, the state file is stored in a local file named “terraform.tfstate”, but it can also be stored remotely, which works better in a team environment.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

Which of the following best describes the default local backend?

A

The local backend:

“stores state on the local filesystem”
“locks the state using system APIs”
“performs operations locally”

Information on the default local backend can be found at this link.

Example:

terraform {
  backend "local" {
    path = "relative/path/to/terraform.tfstate"
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

True or False? You can migrate the Terraform backend but only if there are no resources currently being managed.

A

False

If you are already using Terraform to manage infrastructure, you probably want to transfer to another backend, such as Terraform Cloud, so you can continue managing it. By migrating your Terraform state, you can hand off infrastructure without de-provisioning anything.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

Which of the following connection types are supported by the remote-exec provisioner? (select two)

  • smb
  • ssh
  • rdp
  • winrm
A
  • ssh
  • winrm

The remote-exec provisioner invokes a script on a remote resource after it is created. The remote-exec provisioner supports both ssh and winrm type connections.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

Which of the following is
s considered a Terraform plugin?

  • Terraform provider
  • Terraform language
  • Terraform logic
  • Terraform tooling
A

Terraform provider

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

Which of the following Terraform files should be ignored by Git when committing code to a repo? (select two)

  • terraform.tfvars
  • terraform.tfstate
  • variables.tf
  • output.tf
A
  • terraform.tfstate

- terraform.tfvars

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

You have been given requirements to create a security group for a new application. Since your organization standardizes on Terraform, you want to add this new security group with the fewest lines of code. What feature could you use to iterate over a list of required TCP ports to add to the new security group?

A

dynamic block

A dynamic block acts much like a for expression but produces nested blocks instead of a complex typed value. It iterates over a given complex value and generates a nested block for each element of that complex value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

In regards to Terraform state file, select all the statements below which are correct: (select four)

  • storing state remotely can provide better security
  • Terraform Cloud always encrypts state at rest
  • when using local state, the state file is stored in plain-text
  • the Terraform state can contain sensitive data, therefore the state file should be protected from unauthorized access
A
  • When using local state, the state file is stored in plain-text
  • The Terraform state can contain sensitive data, therefore the state file should be protected from unauthorized access
  • Terraform Cloud always encrypts state at rest
  • Storing state remotely can provide better security

Terraform state can contain sensitive data, depending on the resources in use and your definition of “sensitive.” The state contains resource IDs and all resource attributes. For resources such as databases, this may contain initial passwords.

When using the local state, the state is stored in plain-text JSON files.

If you manage any sensitive data with Terraform (like database passwords, user passwords, or private keys), treat the state itself as sensitive data.

Storing Terraform state remotely can provide better security. As of Terraform 0.9, Terraform does not persist state to the local disk when the remote state is in use, and some backends can be configured to encrypt the state data at rest.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Terry is using a module to deploy some EC2 instances on AWS for a new project. He is viewing the code that is calling the module for deployment, which is shown below. Where is the value of the security group originating?

module “ec2_instances” {
source = “terraform-aws-modules/ec2-instance/aws”
version = “2.12.0”

name = “my-ec2-cluster”
instance_count = 2

ami = “ami-0c5204531f799e0c6”
instance_type = “t2.micro”
vpc_security_group_ids = [module.vpc.default_security_group_id]
subnet_id = module.vpc.public_subnets[0]

tags = {
Terraform = “true”
Environment = “dev”
}

A

the output of another module

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

What are some of the features of Terraform state?

  • determining the correct order to destroy resources
  • inspection of cloud resources
  • mapping configuration to real-world resources
  • increased performance
A
  • increased performance
  • determining the correct order to destroy resources
  • mapping configuration to real-world resources
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Which of the following allows Terraform users to apply policy as code to enforce standardized configurations for resources being deployed via infrastructure as code?

  • sentinel
  • functions
  • workspaces
  • module registry
A

sentinel

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

Frank has a file named main.tf which is shown below. Which of the following statements are true about this code? (select two)

module “servers” {
source = “./app-cluster”

servers = 5
}

A
  • main.tf is the calling module

- app-cluster is the child module

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

Stephen is writing brand new code and needs to ensure it is syntactically valid and internally consistent. Stephen doesn’t want to wait for Terraform to access any remote services while making sure his code is valid. What command can he use to accomplish this?

  • terraform show
  • terraform fmt
  • terraform refresh
  • terraform validate
A

terraform validate

The terraform validate command validates the configuration files in a directory, referring only to the configuration and not accessing any remote services such as remote state, provider APIs, etc.

Validate runs checks that verify whether a configuration is syntactically valid and internally consistent, regardless of any provided variables or existing state. It is thus primarily useful for general verification of reusable modules, including the correctness of attribute names and value types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

Published modules via the Terraform Registry provide which of the following benefits? (select four)

A
  • show examples and READMEs
  • automatically generated documentation
  • allow browsing version histories
  • support versioning
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

Terraform-specific settings and behaviors are declared in which configuration block type?

A

terraform

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

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)

A
  • command-line key/value pairs
  • interactively on the command line
  • use the -backend-config=PATH to specify a separate config file
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

True or False? Provisioners should only be used as a last resort.

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

What Terraform command can be used to inspect the current state file?

  • terraform inspect
  • terraform read
  • terraform state
  • terraform show
A

terraform show

The terraform show command is used to provide human-readable output from a state or plan file. This can be used to inspect a plan to ensure that the planned operations are expected, or to inspect the current state as Terraform sees it.

Machine-readable output can be generated by adding the -json command-line flag.

Note: When using the -json command-line flag, any sensitive values in Terraform state will be displayed in plain text.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

What is the purpose of using the local-exec provisioner? (select two)

  • ensures that the resource is only executed in the local infrastructure where Terraform is deployed
  • executes a command on the resource to invoke an update to the Terraform state
  • to execute one or more commands on the machine running Terraform
  • to invoke a local executable
A
  • to execute one or more commands on the machine running Terraform
  • to invoke a local execution
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

In Terraform Enterprise, a workspace can be mapped to how many VCS repos?

A

1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

What are the benefits of using Infrastructure as Code? (select five)

  • Infrastructure as Code is relatively simple to learn and write, regardless of a user’s prior experience with developing code
  • Infrastructure as Code gives the user the ability to recreate an application’s infrastructure for disaster recovery scenarios
  • Infrastructure as Code is easily repeatable, allowing the user to reuse code to deploy similar, yet different resources
  • Infrastructure as Code provides configuration consistency and standardization among deployments
  • Infrastructure as Code easily replaces development languages such as Go and .Net for application development
  • Infrastructure as Code allows a user to turn a manual task into a simple, automated deployment
A
  • Infrastructure as Code gives the user the ability to recreate an application’s infrastructure for
    (1) “disaster recovery scenarios”
  • Infrastructure as Code easily
    (2)”repeatable”
    allowing the user to reuse code to deploy similar, yet different resources
  • Infrastructure as Code allows a user to turn a manual task into a simple, (3)”automated deployment”
  • Infrastructure as Code provides (4)”configuration consistency and standardization among deployments”
  • Infrastructure as Code is relatively (5)”simple to learn and write”, regardless of a user’s prior experience with developing code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

In the example below, where is the value of the DNS record’s IP address originating from?

resource “aws_route53_record” “www” {
zone_id = aws_route53_zone.primary.zone_id
name = “www.helloworld.com”
type = “A”
ttl = “300”
records = [module.web_server.instance_ip_addr]
}

A

the output of a module named web_server

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

Which of the following actions are performed during a terraform init? (select three)

A
  • download the declared providers which are supported by HashiCorp
  • initializes downloaded and/or installed providers
  • initializes the backend configuration
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

Kristen is using modules to provision an Azure environment for a new application. She is using the following code and specifying a version of her virtual machine module to ensure she’s calling the correct module. Which of the following provides support for versioning of a module? (select two)

module “compute” {
source = “Azure/compute/azurerm”
version = “3.8.0”
}

A
  • public module registry

- private module registry

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

In order to make a Terraform configuration file dynamic and/or reusable, static values should be converted to use what?

A
  • input variables
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

What is a downside to using a Terraform provider, such as the Vault provider, to interact with sensitive data, such as reading secrets from Vault?

  • Terraform and Vault must be running on the same physical host
  • secrets are persisted to the state file and plans
  • Terraform and Vault must be running on the same version
  • Terraform requires a unique auth method to work with Vault
A

secrets are persisted to the state file and plans

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

Select two answers to complete the following sentence:

Before a new provider can be used, it must be ______ and _______. (select two)

A
  • declared/used in a configuration file

- initialized

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

Which of the following represents a feature of Terraform Cloud that is NOT free to customers?

  • private module registry
  • workspace management
  • VCS integration
  • team management and governance
A

team management and governance

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

True or False? Starting in Terraform v0.12, the Terraform language now has built-in syntax for creating lists using the [ and ] delimiters, replacing and deprecating the list () function.

A

True

The list function is deprecated. From Terraform v0.12, the Terraform language has built-in syntax for creating lists using the [ and ] delimiters. Use the built-in syntax instead. The list function will be removed in a future version of Terraform.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

Select the answer below that completes the following statement:

Terraform Cloud can be managed from the CLI but requires __________?

  • authentication using MFA
  • a username and password
  • an API token
  • a TOTP token
A

an API token

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

In order to reduce the time it takes to provision resources, Terraform uses parallelism. By default, how many resources will Terraform provision concurrently during a terraform apply?

A

10

Terraform can limit the number of concurrent operations as Terraform walks the graph using the -parallelism=n argument. The default value for this setting is 10. This setting might be helpful if you’re running into API rate limits.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

In Terraform, most resource dependencies are handled automatically. Which of the following statements describes best how Terraform resource dependencies are handled?

A

Terraform analyzes any expressions within a resource block to find references to other objects and treats those references as implicit ordering requirements when creating, updating, or destroying resources.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

Henry has been working hard on automating his infrastructure for a new application using Terraform. His organization has standardized on Azure for application workloads. Currently, he has his application running successfully, but he has added a new resource to create a DNS record using the Infoblox provider. He has added the new resource but gets an error when he runs a terraform plan. What should Henry do first before running a plan and apply?

  • you can’t mix resources from different providers within the same configuration file, so Henry should create a module for the DNS resource and reference it from the main configuration
  • Henry should run a terraform plan -refresh=true to update the state for the new DNS resource
  • since he has introduced a new provider, a terraform init needs to be run to download the Infoblox plugin
  • the Azure plugin doesn’t support Infoblox directly, so Henry needs to put the DNS resource in another configuration file
A

since he has introduced a new provider, a terraform init needs to be run to download the Infoblox plugin

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

Provider dependencies are created in several different ways. Select the valid provider dependencies from the following list: (select three)

  • use of any resource belonging to a particular provider in a resource or data block in the configuration
  • Existence of any resource instance belonging to a particular provider in the current state.
  • Explicit use of a provider block in configuration, optionally including a version constraint.
  • Existence of any provider plugins found locally in the working directory
A
  • use of any resource belonging to a particular provider in a resource or data block in the configuration
  • Existence of any resource instance belonging to a particular provider in the current state.
  • Explicit use of a provider block in configuration, optionally including a version constraint.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

Sara has her entire application automated using Terraform, but she now needs to start including more infrastructure pieces, such as creating a new subnet, DNS record, and load balancer. Like the Terraform pro she is, Sara requires that these new resources be created within modules so she can easily reuse the code later. However, Sara is having problems getting the subnet_id from the subnet module to pass to the load balancer module. What could fix this problem?

A

add an “output that references the subnet module” and retrieve the value using

“module.subnet.subnet_id”

in the load balancer module

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

What is the result of the following terraform function call?

> zipmap([“a”, “b”], [1, 2])

A

{
“a” = 1
“b” = 2
}

zipmap constructs a map from a list of keys and a corresponding list of values. A map is denoted by { } whereas a list is denoted by [ ].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
85
Q

Select the most accurate statement to describe the Terraform language from the following list.

  • Terraform is an immutable, declarative, Infrastructure as Code provisioning language based on Hashicorp Configuration Language, or optionally JSON
  • Terraform is a mutable, declarative, Infrastructure as Code Configuration management language based on HashiCorp Configuration language, or optionally JSON.
  • Terraform is an immutable, procedural, Infrastructure as Code configuration management language based on Hashicorp Configuration Language, or optionally JSON.
  • Terraform is a mutable, procedural, Infrastructure as Code provisioning language based on Hashicorp Language, or optionally YAML.
A

Terraform is an immutable, declarative, Infrastructure as Code provisioning language based on Hashicorp Configuration Language, or optionally JSON.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
86
Q

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?

A
  • use terraform taint to mark the virtual machine as tainted

The terraform taint command manually marks a Terraform-managed resource as tainted, forcing it to be destroyed and recreated on the next apply. This command will not modify infrastructure but does modify the state file in order to mark a resource as tainted. Once a resource is marked as tainted, the next plan will show that the resource will be destroyed and recreated and the next apply will implement this change.

You could also use terraform destroy -target and destroy only the virtual machine and then run a terraform apply again.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
87
Q

Whenever you add a new module to a configuration, Terraform must install the module before it can be used. What two commands can be used to install and update modules? (select two)

  • terraform get
  • terraform plan
  • terraform init
  • terraform refresh
A

terraform init
terraform get

Both the terraform get and terraform init commands will install and update-modules. The terraform init command will also initialize backends and install plugins.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

Which of the following terraform subcommands could be used to remove the lock on the state for the current configuration?

A

force-unlock

terraform force-unlock removes the lock on the state for the current configuration. Be very careful forcing an unlock, as it could cause data corruption and problems with your state file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

Terraform is distributed as a single binary and is available for many different platforms. Select all Operating Systems that Terraform is available for. (select five)

  • Unix
  • macOS
  • Solaris
  • FreeBSD
  • Linux
  • Windows
A
  • macOS
  • Solaris
  • FreeBSD
  • Linux
  • Windows
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q

What is the result of the following terraform function call?

> index([“a”, “b”, “c”], “c”)

A

2

index finds the element index for a given value in a list starting with index 0. Therefore, “a” is at index 0, “b” is at index 1, and “c” is at index 2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

True or False? When using the Terraform provider for Vault, the tight integration between these HashiCorp tools provides the ability to mask secrets in the terraform plan and state files.

A

False

Currently, Terraform has no mechanism to redact or protect secrets that are returned via data sources, so secrets read via this provider will be persisted into the Terraform state, into any plan files, and in some cases in the console output produced while planning and applying. These artifacts must, therefore, all be protected accordingly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
92
Q

Which of the following is not a valid Terraform string function?

A

tostring

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

Which Terraform command will check and report errors within modules, attribute names, and value types to make sure they are syntactically valid and internally consistent?

A

terraform validate

The terraform validate command validates the configuration files in a directory, referring only to the configuration and not accessing any remote services such as remote state, provider APIs, etc.

Validate runs checks that verify whether a configuration is syntactically valid and internally consistent, regardless of any provided variables or existing state. It is thus primarily useful for general verification of reusable modules, including the correctness of attribute names and value types.

https://www.terraform.io/docs/commands/validate.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
94
Q

True of False? Rather than use state, Terraform can inspect cloud resources on every run.

A

False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
95
Q

When writing Terraform code, HashiCorp recommends that you use how many spaces between each nesting level?

A

2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
96
Q

In the following code snippet, the block type is identified by which string?

resource “aws_instance” “db” {
ami = “ami-123456”
instance_type = “t2.micro”
}

A

resource

The format of resource block configurations is as follows:

”” “”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
97
Q

A user creates three workspaces from the command line - prod, dev, and test. Which of the following commands will the user run to switch to the dev workspace?

A

terraform workspace select dev

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
98
Q

During a terraform apply, a resource is successfully created but eventually fails during provisioning. What happens to the resource?

  • the terraform plan is rolled back and all provisioned resources are removed
  • it is automatically deleted
  • the resource is marked as tainted
  • Terraform attempts to provision the resource up three times before exiting with an error
A

the resource is marked as tainted

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
99
Q

True or False? By default, Terraform destroy will prompt for confirmation before proceeding.

A

True

Terraform destroy will always prompt for confirmation before executing unless passed the -auto-approve flag.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
100
Q

Select all features which are exclusive to Terraform Enterprise and Terraform Cloud for Business (select three).

  • SAML/SSO
  • Audit Logging
  • Self-Service Infrastructure
A
  • SAML/SSO
  • Audit Logging
  • Self-Service Infrastructure

Self-Service Infrastructure, Audit Logging, and SAML/SSO are only available in Terraform Cloud for Business or Terraform Enterprise.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
101
Q

Which of the following variable declarations is going to result in an error?

A

variable “example” {
description = “This is a variable description”
type = list(string)
default = {}
}

Lists are defined with [ ], maps are defined with { }.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
102
Q

Larissa is interested in using a module to create an AWS VPC. She finds this code but isn’t sure what all the declarations are beyond the source and version (such as “name, cidr, azs, etc). What are these declarations used for?

module “vpc” {
source = “terraform-aws-modules/vpc/aws”
version = “2.21.0”

name = var.vpc_name
cidr = var.vpc_cidr

azs = var.vpc_azs
private_subnets = var.vpc_private_subnets
public_subnets = var.vpc_public_subnets

enable_nat_gateway = var.vpc_enable_nat_gateway

tags = var.vpc_tags
}

  • this is where the variable declarations are so Terraform is aware of these variables within the calling module
  • these are the outputs that the child module will return
  • these are variables that are passed into the child module likely used for resource creation
  • the value of these variables will be obtained from values created in the child module
A

these variables that are passed into the child module are likely used for resource creation

These are the input variables that are being set for the child module, in which the child module will likely use to create resources. These variables are declared elsewhere, likely in a variables.tf file, and the values are pulled from either the default value, a .tfvars file, environment variable, or from another resource.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
103
Q

Freddy and his co-worker Jason are deploying resources in GCP using Terraform for their team. After resources have been deployed, they need to destroy the cloud-based resources to save on costs. However, two other team members, Michael and Chucky, are using a Cloud SQL instance for testing and are asking to keep it running.

How can Freddy and Jason easily destroy all other resources without negatively impacting the database?

A

run a “terraform state rm” command to remove the Cloud SQL instance from Terraform management before running the terraform destroy command

Ex:
In this case, the easiest way to accomplish this is to remove the database from the terraform state file, removing that resource from Terraform management. Afterward, the team can use the terraform destroy command which will delete all other resources.

All other options would be too time-consuming or would cause an outage to the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
104
Q

Why might a user opt to include the following snippet in their configuration file?

terraform {
required_version = “>= 0.12”
}

A

Terraform 0.12 introduced substantial changes to the syntax used to write a Terraform configuration.

Explanation
You can use required_version to ensure that a user deploying infrastructure is using Terraform 0.12 or greater, due to the vast number of changes that were introduced. As a result, many previously written configurations had to be converted or rewritten.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
105
Q

Where does Terraform OSS store the local state for workspaces?

  • a file called terraform.tfstate.backup
  • directory called terraform.workspaces.tfstate
  • directory called terraform.tfstate.d
  • a file called terraform.tfstate
A

directory called terraform.tfstate.d

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
106
Q

Which are some of the benefits of using Infrastructure as Code in general? (select three)

  • it can be versioned
  • it can be shared
  • it can be reused
  • it is always platform agnostic
A
  • it can be versioned
  • it can be shared
  • it can be reused

Explanation
Infrastructure as Code has many benefits, including being able to create a blueprint of your data center which can be versioned, shared, and reused. However, in a general sense, not all IaC tools are platform agnostic like Terraform.

https://www.terraform.io/intro/index.html#infrastructure-as-code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
107
Q

True or False? The terraform refresh command is used to reconcile the state Terraform knows about (via its state file) with the real-world infrastructure. If drift is detected between the real-world infrastructure and the last known-state, it will modify the infrastructure to correct the drift.

A

False

Explanation
The terraform refresh command is used to reconcile the state Terraform knows about (via its state file) with the real-world infrastructure. This can be used to detect any drift from the last-known state, and to update the state file.

This does not modify infrastructure but does modify the state file. If the state is changed, this may cause changes to occur during the next plan or apply.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
108
Q

The terraform state command and related attributes can be used to

A

modify the current state, such as removing items

Explanation
The terraform state command is used for advanced state management. Rather than modify the state directly, the terraform state commands can be used in many cases instead.

To refresh Terraform state, use the command terraform refresh.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
109
Q

Terraform has detailed logs which can be enabled by setting the _________ environmental variable.

A

TF_LOG

Explanation
Terraform has detailed logs that can be enabled by setting the TF_LOG environment variable to any value. This will cause detailed logs to appear on stderr.

You can set TF_LOG to one of the log levels TRACE, DEBUG, INFO, WARN or ERROR to change the verbosity of the logs. TRACE is the most verbose and it is the default if TF_LOG is set to something other than a log level name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
110
Q

Terraform Cloud is more powerful when you integrate it with your version control system (VCS) provider. Select all the supported VCS providers from the answers below. (select four)

  • Azure DevOps Server
  • GitHub
  • CVS Version Control
  • GitHub Enterprise
  • Bitbucket Cloud
A
  • Azure DevOps Server
  • GitHub
  • GitHub Enterprise
  • Bitbucket Cloud
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
111
Q

A user runs terraform init on their RHEL based server and per the output, two provider plugins are downloaded:

$ terraform init

Initializing the backend…

Initializing provider plugins…

  • Checking for available provider plugins…
  • Downloading plugin for provider “aws” (hashicorp/aws) 2.44.0…
  • Downloading plugin for provider “random” (hashicorp/random) 2.2.1…

Terraform has been successfully initialized!
Where are these plugins downloaded to?

  • The .terraform.d directory in the directory terraform init was executed in.
  • The .terraform/plugins directory in the directory terraform init was executed in.
  • /etc/terraform/plugins
  • The .terraform.plugins directory in the directory terraform init was executed in.
A

The .terraform/plugins directory in the directory terraform init was executed in.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
112
Q

What feature of Terraform Cloud and/or Terraform Enterprise can you publish and maintain a set of custom modules which can be used within your organization?

  • Terraform Registry
  • customer VCS integration
  • remote runs
  • private module registry
A

private module registry

Explanation
You can use modules from a private registry, like the one provided by Terraform Cloud. Private registry modules have source strings of the form ///. This is the same format as the public registry, but with an added hostname prefix.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
113
Q

While Terraform is generally written using the HashiCorp Configuration Language (HCL). What other syntax can Terraform be expressed in?

A

JSON

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
114
Q

True or False? Each Terraform workspace uses its own state file to manage the infrastructure associated with that particular workspace.

A

True

Explanation
The persistent data stored in the backend belongs to a workspace. Initially, the backend has only one workspace, called “default”, and thus there is only one Terraform state associated with that configuration.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
115
Q

A “backend” in Terraform determines how state is loaded and how an operation such as apply is executed. Which of the following is not a supported backend type?

  • consul
  • s3
  • artifactory
  • github
  • terraform enterprise
A

github

Explanation
GitHub is not a supported backend type. Check out the supported backends using the link below. Remember there is the “local” backend and then there are remote backends that store state elsewhere. Remote backends (and locking) are needed when more than one person is interacting with the same state file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
116
Q

When Terraform needs to be installed in a location where it does not have internet access to download the installer and upgrades, the installation is generally known as to be __________.

  • air-gapped
  • a private install
  • disconnected
  • non-traditional
A

air-gapped

Explanation
A Terraform Enterprise install that is provisioned on a network that does not have Internet access is generally known as an air-gapped install. These types of installs require you to pull updates, providers, etc. from external sources vs. being able to download them directly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
117
Q

Terraform Enterprise (also referred to as pTFE) requires what type of backend database for a clustered deployment?

  • Cassandra
  • MySQL
  • MSSQL
  • PostgreSQL
A

PostgreSQL

Explanation
External Services mode stores the majority of the stateful data used by the instance in an external PostgreSQL database and an external S3-compatible endpoint or Azure blob storage. There is still critical data stored on the instance that must be managed with snapshots. Be sure to check the PostgreSQL Requirements for information that needs to be present for Terraform Enterprise to work. This option is best for users with expertise managing PostgreSQL or users that have access to managed PostgreSQL offerings like AWS RDS.

Check out the Pre-requisite document for more information - https://www.terraform.io/docs/enterprise/before-installing/index.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
118
Q

When multiple arguments with single-line values appear on consecutive lines at the same nesting level, HashiCorp recommends that you:

A

align their equals signs
ami = “abc123”
instance_type = “t2.micro”

Explanation
HashiCorp style conventions suggest you that align the equals sign for consecutive arguments for easing readability for configurations

ami           = "abc123"
instance_type = "t2.micro"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
119
Q

When using providers that require the retrieval of data, such as the HashiCorp Vault provider, in what phase does Terraform actually retrieve the data required, assuming you are following the standard workflow of write, plan, and apply?

  • terraform apply
  • terraform init
  • terraform plan
  • terraform destroy
A

terraform plan

Explanation
It is important to consider that “Terraform reads from data sources during the plan phase and writes the result into the plan.”

For something like a Vault token which has an explicit TTL, the apply must be run before the data, or token, in this case, expires, otherwise, Terraform will fail during the apply phase.

Another example of this is AWS credentials:

The token is generated from the moment the configuration retrieves the temporary AWS credentials (on terraform plan or terraform apply). If the apply run is confirmed after the 120 seconds, the run will fail because the credentials used to initialize the Terraform AWS provider has expired. For these instances or large multi-resource configurations, you may need to adjust the default_lease_ttl_seconds.

Check out the blue box under this section for more information: https://learn.hashicorp.com/tutorials/terraform/secrets-vault#provision-compute-instance

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
120
Q

Which of the following statements best describes the Terraform list(…) type?

  • a sequence of values identified by consecutive whole numbers starting with zero.
  • a collection of named attributes that each have their own type.
  • a collection of unique values that do not have any secondary identifiers or ordering.
  • a collection of values where each is identified by a string label
A

a sequence of values identified by consecutive whole numbers starting with zero.

Explanation
A terraform list is a sequence of values identified by consecutive whole numbers starting with zero.

https://www.terraform.io/docs/configuration/types.html#structural-types

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
121
Q

From the code below, identify the implicit dependency:

resource “aws_eip” “public_ip” {
vpc = true
instance = aws_instance.web_server.id
}

resource "aws_instance" "web_server" {
  ami           = "ami-2757f631"
  instance_type = "t2.micro"
  depends_on = [aws_s3_bucket.company_data]
}
  • The EC2 instance labeled web_server
  • The S3 bucket labeled company_data
  • The EIP with an id of ami2757f631
  • The AMI used for the EC2 instance
A

The EC2 instance labeled web_server

Explanation
The EC2 instance labeled web_server is the implicit dependency as the aws_eip cannot be created until the aws_instance labeled web_server has been provisioned and the id is available.

Note that aws_s3_bucket.example is an explicit dependency.

https://learn.hashicorp.com/tutorials/terraform/dependencies

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
122
Q

What is the result of the following terraform function call?

> lookup({a=”hello”, b=”goodbye”}, “c”, “what?”)

A

what

Explanation
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. In this case, the function call is searching for the key “c”. Because there is no key “c”, the default value of “what?” is returned.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
123
Q

Choose the correct answer which fixes the syntax of the following Terraform code:

resource “aws_security_group” “vault_elb” {
name = “${var.name_prefix}-vault-elb”
description = Vault ELB
vpc_id = var.vpc_id
}

A

resource “aws_security_group” “vault_elb” {
name = “${var.name_prefix}-vault-elb”
description = “Vault ELB”
vpc_id = var.vpc_id
}

Explanation
When assigning a value to an argument, it must be enclosed in quotes (“…”) unless it is being generated programmatically.

https://www.terraform.io/docs/configuration/syntax.html#arguments-and-blocks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
124
Q

Elijah has created a module called “my_test_module” and committed it to GitHub. Over time, several commits have been made with updates to the module, each tagged in GitHub with an incremental version number. Which of the following lines would be required in a module configuration block in terraform to select tagged version v1.0.4?

A

source=”git::https://example.com/my_test_module.git?ref=v1.0.4”

Explanation
By default, Terraform will clone and use the default branch (referenced by HEAD) in the selected repository. You can override this using the ref argument:

module “vpc” {
source = “git::https://example.com/vpc.git?ref=v1.2.0”
}
The value of the ref argument can be any reference that would be accepted by the git checkout command, including branch and tag names.

https://www.terraform.io/docs/modules/sources.html#selecting-a-revision

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
125
Q

Which of the following commands will launch the Interactive console for Terraform interpolations?

A

terraform console

Explanation
The terraform console command provides an interactive console for evaluating expressions.

https://www.terraform.io/docs/commands/console.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
126
Q

When using constraint expressions to signify a version of a provider, which of the following are valid provider versions that satisfy the expression found in the following code snippet: (select two)

terraform {
  required_providers {
    aws = "~> 1.2.0"
  }
}
A
  1. 2.3
  2. 2.9

Explanation
~> 1.2.0 will match any non-beta version of the provider between >= 1.2.0 and < 1.3.0. For example, 1.2.X

https://www.terraform.io/docs/configuration/modules.html#gt-1-2-0-1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
127
Q

The following is a snippet from a Terraform configuration file:

provider “aws” {
region = “us-east-1”
}

provider “aws” {
region = “us-west-1”
}
which, when validated, results in the following error:-

Error: Duplicate provider configuration

on main.tf line 5:
5: provider “aws” {

A default provider configuration for “aws” was already given at
main.tf:1,1-15. If multiple configurations are required, set the “______”
argument for alternative configurations.
Fill in the blank in the error message with the correct string from the list below.

A

alias

Explanation
An alias meta-argument is used when using the same provider with different configurations for different resources.

https://www.terraform.io/docs/configuration/providers.html#alias-multiple-provider-instances

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
128
Q

In the example below, the depends_on argument creates what type of dependency?

resource "aws_instance" "example" {
  ami           = "ami-2757f631"
  instance_type = "t2.micro"
  depends_on = [aws_s3_bucket.company_data]
}
A

explicit dependency

Explanation
Sometimes there are dependencies between resources that are not visible to Terraform. The depends_on argument is accepted by any resource and accepts a list of resources to create explicit dependencies for.

https://learn.hashicorp.com/tutorials/terraform/dependencies

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
129
Q

Harry has deployed resources on Azure for his organization using Terraform. However, he has discovered that his co-workers Ron and Ginny have manually created a few resources using the Azure console. Since it’s company policy to manage production workloads using IaC, how can Harry start managing these resources in Terraform without negatively impacting the availability of the deployed resources?

A

use terraform import to import the existing resources under Terraform management

Explanation
The terraform import command is used to import existing resources into Terraform. This allows you to take resources that you’ve created by some other means and bring them under Terraform management.

Note that terraform import DOES NOT generate configuration, it only modifies state. You’ll still need to write a configuration block for the resource for which it will be mapped using the terraform import command.

https://www.terraform.io/docs/commands/import.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
130
Q

A user has created three workspaces using the command line - prod, dev, and test. The user wants to create a fourth workspace named stage. Which command will the user execute to accomplish this?

A

terraform workspace new stage

Explanation
The terraform workspace new command is used to create a new workspace.

https://www.terraform.io/docs/commands/workspace/new.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
131
Q

Oscar is modifying his Terraform configuration file but isn’t 100% sure it’s correct. He is afraid that changes made could negatively affect production workloads. How can Oscar validate the changes that will be made without impacting existing workloads?

A

run a terraform plan and validate the changes that will be made

Explanation
The terraform plan command is used to create an execution plan. Terraform performs a refresh, unless explicitly disabled, and then determines what actions are necessary to achieve the desired state specified in the configuration files. This command is a convenient way to check whether the execution plan for a set of changes matches your expectations without making any changes to real resources or to the state.

https://www.terraform.io/docs/commands/plan.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
132
Q

Anyone can publish and share modules on the Terraform Public Module Registry, and meeting the requirements for publishing a module is extremely easy. Select from the following list all valid requirements. (select three)

  • The registry uses tags to identify module versions. Release tag names must be for the format x.y.z, and can optionally be prefixed with a v
  • Module repositories must use this three-part name format, terraform
  • The module must be PCI/HIPPA compliant
  • The module must be on GitHub and must be a public repo
A

The registry uses tags to identify module versions. Release tag names must be for the format x.y.z, and can optionally be prefixed with a v

Module repositories must use this three-part name format, terraform–

The module must be on GitHub and must be a public repo

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
133
Q

Which of the following is an invalid variable name?

A

count

Explanation
count is a reserved word. The count parameter on resources can simplify configurations and let you scale resources by simply incrementing a number.

https://www.terraform.io/intro/examples/count.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
134
Q

Environment variables can be used to set variables. The environment variables must be in the format “____“_. Select the correct prefix string from the following list.

  • TF_ENV
  • TF_ENV_VAR
  • TF_VAR_NAME
  • TF_VAR
A

TF_VAR

Explanation
Environment variables can be used to set variables. The environment variables must be in the format TF_VAR_name and this will be checked last for a value. For example:

export TF_VAR_region=us-west-1
export TF_VAR_ami=ami-049d8641
export TF_VAR_alist=’[1,2,3]’
export TF_VAR_amap=’{ foo = “bar”, baz = “qux” }’
https://www.terraform.io/docs/commands/environment-variables.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
135
Q

True or False? Using the latest versions of Terraform (0.13 - 0.15) terraform init cannot automatically download community providers.

A

False

Explanation
With Terraform 0.13, terraform init can now automatically download community providers.

https://www.hashicorp.com/blog/automatic-installation-of-third-party-providers-with-terraform-0-13

In June at HashiConf digital we announced the beta version of HashiCorp Terraform 0.13. Many of the improvements in Terraform 0.13 focus on the diverse, rapidly-growing collection of official, partner, and community providers. With Terraform 0.13, terraform init will automatically download and install partner and community providers in the HashiCorp Terraform Registry, following the same clear workflow as HashiCorp-supported official providers. These improvements to the ecosystem will benefit Terraform users and provider developers alike.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
136
Q

You are an Infrastructure Engineer at Strategies, Inc, which is a new organization that provides marketing services to startups. All of your infrastructure is provisioned and managed by Terraform. Despite your pleas to not make changes outside of Terraform, sometimes the other engineers log into the cloud platform and make minor changes to resolve problems.

What Terraform command can you use to reconcile the state with the real-world infrastructure in order to detect any drift from the last-known state?

A

terraform refresh

Explanation
The terraform refresh command is used to reconcile the state Terraform knows about (via its state file) with the real-world infrastructure. This can be used to detect any drift from the last-known state, and to update the state file.

https://www.terraform.io/docs/commands/refresh.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
137
Q

Infrastructure as Code (Iac) provides many benefits to help organizations deploy application infrastructure much faster than clicking around in the console. What are the additional benefits to IaC? (select three)

  • code can easily be shared and reused
  • eliminates parallelism
  • allows infrastructure to be versioned
  • can always be used to deploy the latest features and services
  • creates a blueprint of your data center
A
  • code can easily be shared and reused
  • allows infrastructure to be versioned
  • creates a blueprint of your data center

Explanation
Infrastructure is described using a high-level configuration syntax. This allows a blueprint of your datacenter to be versioned and treated as you would any other code. Additionally, infrastructure can be shared and re-used.

Infrastructure as Code almost always uses parallelism to deploy resources faster. And depending on the solution being used, it doesn’t always have access to the latest features and services available on cloud platforms or other solutions.

https://www.terraform.io/intro/index.html#infrastructure-as-code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
138
Q

Based on the following code, which of the resources will be created first?

resource “aws_instance” “data_processing” {
ami = data.aws_ami.amazon_linux.id
instance_type = “t2.micro”

depends_on = [aws_s3_bucket.customer_data]
}

module “example_sqs_queue” {
source = “terraform-aws-modules/sqs/aws”
version = “2.1.0”

depends_on = [aws_s3_bucket.customer_data, aws_instance.data_processing]
}

resource “aws_s3_bucket” “customer_data” {
acl = “private”
}

resource “aws_eip” “ip” {
vpc = true
instance = aws_instance.data_processing.id
}

A

aws_s3_bucket.customer_data

Explanation
In this example, the only resource that does not have an implicit or an explicit dependency is the aws_s3_bucket.customer_data. Every other resource defined in this configuration has a dependency on another resource.

https://learn.hashicorp.com/tutorials/terraform/dependencies

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
139
Q

Based on the Terraform code below, what block type is used to define the VPC?

vpc_id = aws_vpc.main.id

  • provider block
  • locals block
  • data block
  • resource block
A

If it were in a data block, it would be referred to as data.aws_vpc.i.main.id

  • resource block

Explanation
Based on the Terraform code provided in the question, the VPC is defined in a resource block, meaning that there is a VPC resource being defined, such as:

resource “aws_vpc” “main” {
cidr_block = var.base_cidr_block
}
If it were locals, the resource would be referred to as local.aws_vpc

https://www.terraform.io/docs/configuration/resources.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
140
Q

Which feature of Terraform Enterprise can be used to enforce fine-grained policies to enforce standardization and cost controls before resources are provisioned with Terraform?

A

sentinel

Explanation
Sentinel is an embedded policy-as-code framework integrated with the HashiCorp Enterprise products. It enables fine-grained, logic-based policy decisions, and can be extended to use information from external sources.

https://www.terraform.io/docs/cloud/sentinel/index.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
141
Q

When running a terraform plan, how can you save the plan so it can be applied at a later time?

A

use the -out parameter

-out=FILE

Explanation
The optional -out argument can be used to save the generated plan to a file for later execution with terraform apply, which can be useful when running Terraform in automation.

https://www.terraform.io/docs/commands/plan.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
142
Q

Which type of configuration block assigns a name to an expression that can be used multiple times within a module without having to repeat it?

  • backend
  • resources
  • local
  • provider
A

local

Explanation
A local value assigns a name to an expression, so you can use it multiple times within a module without repeating it.

https://www.terraform.io/docs/configuration/locals.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
143
Q

Which of the following best describes a “data source”?

  • enables Terraform to fetch data for use elsewhere in the Terraform configuration
  • a file that contains the current working version of Terraform
  • provides required data for declared variables used within the Terraform configuration
  • maintains a list of strings to store the values of declared outputs in Terraform
A

enables Terraform to fetch data for use elsewhere in the Terraform configuration

Explanation
Data sources allow data to be fetched or computed for use elsewhere in Terraform configuration. Use of data sources allows a Terraform configuration to make use of information defined outside of Terraform, or defined by another separate Terraform configuration.

https://www.terraform.io/docs/configuration/data-sources.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
144
Q

Michael has deployed many resources in AWS using Terraform and can easily update or destroy resources when required by the application team. A new employee, Dwight, is working with the application team and deployed a new EC2 instance through the AWS console. When Michael finds out, he decided he wants to manage the new EC2 instance using Terraform moving forward. He opens his terminal and types:

A. Terraform cannot manage resources that were provisioned manually

B. Configure the appropriate tags on the Amazon EC? resource so Terraform knows that it
should manage the resource moving forward

C. import the configuration of the EC2 instance called web_app_42 from AWS first

D. create a configuration for the new resource in the Terraform configuration file, such as:
resource “aws_inctance’ “web_ap942" {
 # (resource arguments)
}
A

create a configuration for the new resource in the Terraform configuration file, such as:

resource "aws_instance" "web_app_42" {
    # (resource arguments)
}

Explanation
The terraform import command is used to import existing resources into Terraform. However, Terraform will not create a configuration for the imported resource. The Terraform operator must create/add a configuration for the resource that will be imported first. Once the configuration is added to the configuration file, the terraform import command can be executed to manage the resource using Terraform.

https://www.terraform.io/docs/commands/import.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
145
Q

Given a Terraform config that includes the following code, how would you reference the last instance that will be created?

resource "aws_instance" "web" {
  # ...
  for_each = {
    "terraform": "value1",
    "resource":  "value2",
    "indexing":  "value3",
    "example":   "value4",
  }
}
  • aws_instance.web[4]
  • aws_instance.example
  • aws_instance.web[3]
  • aws_instance.web[“example”]
A

aws_instance.web[“example”]

Explanation
The following specifications apply to index values on modules and resources with multiple instances:

[N] where N is a 0-based numerical index into a resource with multiple instances specified by the count meta-argument. Omitting an index when addressing a resource where count > 1 means that the address references all instances.

[“INDEX”] where INDEX is an alphanumerical key index into a resource with multiple instances specified by the for_each meta-argument.

https://www.terraform.io/docs/internals/resource-addressing.html

count Example
Given a Terraform config that includes:

resource "aws_instance" "web" {
  # ...
  count = 4
}
An address like this:

aws_instance.web[3]
Refers to only the last instance in the config, and an address like this:

aws_instance.web
Refers to all four "web" instances.
----------------------------------------------------------------------------------
»for_each Example
Given a Terraform config that includes:
resource "aws_instance" "web" {
  # ...
  for_each = {
    "terraform": "value1",
    "resource":  "value2",
    "indexing":  "value3",
    "example":   "value4",
  }
}
An address like this:

aws_instance.web[“example”]
Refers to only the “example” instance in the config.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
146
Q

Which of the following Terraform features is NOT available in the open-source version?

A

sentinel policies

Explanation
All of the options are available to open-source users except for Sentinel, which is only available in Terraform Enterprise and Terraform Cloud paid tiers.

https://www.hashicorp.com/products/terraform/pricing

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
147
Q

Given the following snippet of code, what does servers = 4 reference?

module “servers” {
source = “./modules/aws-servers”

servers = 4
}

  • the output variable of the module
  • the value of an input variable
  • the number of times the module will be executed
  • servers is not a valid configuration for a module
A

the value of an input variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
148
Q

When using a Terraform provider, it’s common that Terraform needs credentials to access the API for the underlying platform, such as VMware, AWS, or Google Cloud. While there are many ways to accomplish this, what are three options that you can provide these credentials? (select three)

  • using a remote-exec
  • integrated services, such as AWS IAM or Azure Managed Service Identity
  • use environment variables
  • directory in the provider block by hardcoding or using a variable
A
  • integrated services, such as AWS IAM or Azure Managed Service Identity
  • directly in the provider block by hardcoding or using a variable
  • use environment variables
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
149
Q

Philip works at a payment processing company and manages the organization’s VMware environment. He recently provisioned a new cluster for a production environment. To ensure everything is working as expected, Philip has been using Terraform and the VMware vSphere client to create and destroy new virtual machines. Currently, there are three virtual machines running on the new cluster, so Philip runs terraform destroy to remove the remaining virtual machines from the cluster. However, Terraform only removes two of the virtual machines, leaving one virtual machine still running.

Why would Terraform only remove two of the three virtual machines?

A

the remaining virtual machine was not created by Terraform, therefore Terraform is not aware of the virtual machine and cannot destroy it

Explanation
The terraform destroy command terminates resources defined in your Terraform configuration. This command is the reverse of terraform apply in that it terminates all the resources specified by the configuration. It does not destroy resources running elsewhere that are not described in the current configuration.

https://learn.hashicorp.com/tutorials/terraform/aws-destroy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
150
Q

A provider alias is used for what purpose in a Terraform configuration file?

  • to use as shorthand for resources to be deployed with the referenced provider
  • using the same provider with different configurations for different resources
  • to signify what cloud-based region to deploy resources
  • alias isn’t used with providers, they are used with provisioners
A

using the same provider with different configurations for different resources

Explanation
The primary reason for this is to support multiple regions for a cloud platform; other examples include targeting multiple Docker hosts, multiple Consul hosts, etc.

To create multiple configurations for a given provider, include multiple provider blocks with the same provider name. For each additional non-default configuration, use the alias meta-argument to provide an extra name segment.

https://www.terraform.io/docs/configuration/providers.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
151
Q

When a terraform apply is executed, where is the AWS provider retrieving credentials to create cloud resources in the code snippet below?

provider “aws” {
region = us-east-1
access_key = data.vault_aws_access_credentials.creds.access_key
secret_key = data.vault_aws_access_credentials.creds.secret_key
}

  • From a data source that is retrieving credentials from HashiCorp Vault is dynamically generating the credentials on Terraform’s behalf
  • from a script that is executing commands against Vault
  • From a variable called vault_aws_access_credentials
  • from the .tfvars file called vault
A

From a data source that is retrieving credentials from HashiCorp Vault. Vault is dynamically generating the credentials on Terraform’s behalf.

Explanation
In this case, Terraform is using a data source to gather credentials from Vault. The data block would look something like this:

data “vault_aws_access_credentials” “creds” {
backend = vault_aws_secret_backend.aws.path
role = vault_aws_secret_backend_role.role.name
}
https://www.terraform.io/docs/configuration/data-sources.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
152
Q

Terraform Cloud Agents are a feature that allows Terraform Cloud to communicate with private infrastructure, such as VMware hosts running on-premises. Which version of Terraform Cloud supports this feature?

  • Terraform Cloud for Business
  • Terraform Team and Governance
  • Terraform Cloud Free
A

Terraform Cloud for Business

Explanation
This newer feature is only available on Terraform Cloud for Business

https://www.hashicorp.com/products/terraform/pricing

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
153
Q

Jeff is a DevOps Engineer for a large company and is currently managing the infrastructure for many different applications using Terraform. Recently, Jeff received a request to remove a specific VMware virtual machine from Terraform as it is no longer needed by the application team. Jeff opens his terminal and issues the command:

$ terraform state rm vsphere_virtual_machine.app1

Removed vsphere_virtual_machine.app1
Successfully removed 1 resource instance(s).
The next time that Jeff runs a terraform apply, the resource is not marked to be deleted. In fact, Terraform is stating that it is creating another identical resource.

…..
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create

Terraform will perform the following actions:

  # vsphere_virtual_machine.app1 will be created
What would explain this behavior?
  • Jeff removed the resource from the state file, “but not the configuration file”. Therefore, Terraform is no longer aware of the virtual machine and assumes Jeff wants to create a new one since the virtual machine is still in the Terraform configuration file
  • the state file was not saved before the terraform apply was executed, therefore Terraform sees that the resource is still in the state file
  • the resource was manually deleted within the VMware infrastructure and needs to be recreated
  • after running the terraform rm command, Jeff needs to run a Terraform plan first to tell Terraform of the updated configuration. A plan will instruct Terraform that the resource should be deleted upon the next terraform apply
A

Jeff removed the resource from the state file, “but not the configuration file”. Therefore, Terraform is no longer aware of the virtual machine and assumes Jeff wants to create a new one since the virtual machine is still in the Terraform configuration file

Explanation:
Because Jeff manually deleted the resource from the state file, Terraform was no longer aware of the virtual machine. When Jeff ran a terraform apply, it refreshed the state file and discovered that the configuration file declared a virtual machine but it was not in state, therefore Terraform needed to create a virtual machine so the provisioned infrastructure matched the desired configuration, which is the Terraform configuration file.

Hopefully, this isn’t a tricky one but I thought it was good to test on, especially since terraform state commands are listed in Objective 4 of the exam. In this case, Jeff should NOT have removed the resource from the state file, but rather remove it from the configuration file and run a terraform plan/apply. In this scenario, Terraform would recognize that the virtual machine was no longer needed and would have destroyed it.

https://www.terraform.io/docs/commands/state/list.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
154
Q

Given the following snippet of code, what will the value of the “Name” tag equal after a terraform apply?

variable “name” {
description = “The username assigned to the infrastructure”
default = “data_processing”
}

variable “team” {
description = “The team responsible for the infrastructure”
default = “IS Team”
}

locals {
  name  = (var.name != "" ? var.name : random_id.id.hex)
  owner = var.team
  common_tags = {
    Owner = local.owner
    Name  = local.name
  }
}
A

data processing

Explanation
The syntax of a conditional expression first names the condition. In this example, if var.name is not (!=) empty, assign the var.name value; else, assign the new random_id resource as the name value. Since var.name equals data_processing, then the value of Name will equal data_processing.

https://www.terraform.io/docs/configuration/expressions/conditionals.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
155
Q

Which of the following commands can be used to detect configuration drift?

A

terraform refresh

Explanation
If the state has drifted from the last time Terraform ran, refresh allows that drift to be detected.

https://www.hashicorp.com/blog/detecting-and-managing-drift-with-terraform

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
156
Q

Variables and their default values are typically declared in a main.tf or terraform.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?

  • .sh file
  • .txt file
  • .tfvars file
  • .tfstate file
A

.tfvars file

Explanation
To set lots of variables, it is more convenient to specify their values in a variable definitions file (with a filename ending in either .tfvars or .tfvars.json)

https://www.terraform.io/docs/configuration/variables.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
157
Q

What happens when you apply a Terraform configuration using terraform apply? (select two)

A. Terraform makes infrastructure changes defined in your configuration.
B. Terraform recreates all the infrastructure defined in the configuration file
C. Terraform formats your configuration to the standard canonical format and style
D. Terraform downloads any required plugins
E. Terraform updates the state file with configuration changes made during the execution.

A

A. Terraform makes infrastructure changes defined in your configuration.
E. Terraform updates the state file with configuration changes made during the execution.

Explanation
The terraform apply command is used to apply the changes required to reach the desired state of the configuration, or the pre-determined set of actions generated by a terraform plan execution plan.

https://www.terraform.io/docs/commands/apply.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
158
Q

Terraform Cloud provides organizations with many features not available to those running Terraform open-source to deploy infrastructure. Select the ADDITIONAL features that organizations can take advantage of by moving to Terraform Cloud. (select three)

  • providers
  • VCS connection
  • remote runs
  • public module registry
  • private module registry
A
  • remote runs
  • VCS connection
  • private module registry

Explanation
Terraform Cloud offers many features, even in the free version, that organizations can quickly take advantage of. This is the best table that compares the features available in Terraform OSS vs. Terraform Cloud and Terraform Enterprise.

https://www.datocms-assets.com/2885/1602500234-terraform-full-feature-pricing-tablev2-1.pdf

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
159
Q

There are an endless number of benefits of using Terraform within your organization. Which of the following are true statements regarding Terraform. (select three)

A

Terraform can simplify both management and orchestration of deploying large-scale, multi-cloud infrastructure

A single Terraform configuration file can be used to manage multiple providers

Terraform is cloud-agnostic but requires a specific provider for the cloud platform

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
160
Q

Aaron is new to Terraform and has a single configuration file that is ready to be deployed. Which of the following can be true about this configuration file? (select three)

  • the state file can be stored in Azure but provision applications in AWS
  • Aaron’s configuration file can deploy applications in both AWS and GCP
  • the state can be disabled when deploying to multiple clouds to prevent sensitive data from being shared across cloud platforms
  • the configuration file can deploy both QA and Staging infrastructure for applications
A
  • Aaron’s configuration file can deploy applications in both AWS and GCP
  • the configuration file can deploy both QA and Staging infrastructure for applications
  • the state file can be stored in Azure but provision applications in AWS

Explanation
There are a ton of benefits of deploying with Terraform and the solution is very capable of managing deployments across multiple clouds. However, state is still required and cannot be disabled.

https://www.terraform.io/intro/use-cases.html#multi-cloud-deployment

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
161
Q

You have created a brand new workspace for a new project, and have added all of your Terraform configuration files in the new directory. Before you execute a terraform plan, you want to validate the configuration using the terraform validate command. However, Terraform returns the error:

$ terraform validate
Error: Could not load plugin
What would cause this error when trying to validate the configuration?

A

the directory was not initialized

Explanation
terraform validate requires an initialized working directory with any referenced plugins and modules installed. If you don’t initiate the directory, you will get an error stating you need to run a terraform init

https://www.terraform.io/docs/commands/validate.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
162
Q

Which of the following are the benefits of using modules in Terraform? (select three)

  • allows modules to be stored anywhere accessible by Terraform
  • enables code reuse
  • supports versioning to maintain compatibility
  • supports modules stored locally or remotely
A
  • supports versioning to maintain compatibility
  • supports modules stored locally or remotely
  • enables code reuse

Explanation
All of these are examples of the benefits of using Terraform modules “except where they can be stored”. Modules can only be supported in certain sources found at the following link:

https://www.terraform.io/docs/modules/sources.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
163
Q

Using the Terraform code below, where will the resource be provisioned?

provider “aws” {
region = “us-east-1”
}

provider “aws” {
alias = “west”
region = “us-west-2”
}

provider “aws” {
alias = “eu”
region = “eu-west-2”
}

resource “aws_instance” “vault” {
ami = data.aws_ami.amzlinux2.id
instance_type = “t3.micro”
key_name = “ec2_key”
vpc_security_group_ids = var.vault_sg
subnet_id = var.vault_subnet
user_data = file(“vault.sh”)

tags = {
Name = “vault”
}
}

A

us-east-1

Explanation
The resource above will be created in the default region of us-east-1, since the resource does signify an alternative provider configuration. If the resource needs to be created in one of the other declared regions, it should have looked like this, where “aws” signifies the provider name and “west” signifies the alias name as such .:

resource “aws_instance” “vault” {
provider = aws.west
ami = data.aws_ami.amzlinux2.id
instance_type = “t3.micro”
key_name = “ec2_key”
vpc_security_group_ids = var.vault_sg
subnet_id = var.vault_subnet
user_data = file(“vault.sh”)

  tags = {
    Name = "vault"
  }
}
https://www.terraform.io/docs/configuration/providers.html#selecting-alternate-provider-configurations
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
164
Q

What function does the terraform init -upgrade command perform?

  • upgrades the backend to the latest supported version
  • upgrades the Terraform configuration files(s) to use the referenced Terraform version
  • update all previously installed plugins to the newest version that complies with the configuration’s version constraints
  • upgrades all of the referenced modules and providers to the latest version of Terraform
A

update all previously installed plugins to the newest version that complies with the configuration’s version constraints

Explanation
The -upgrade will upgrade all previously-selected plugins to the newest version that complies with the configuration’s version constraints. This will cause Terraform to ignore any selections recorded in the dependency lock file, and to take the newest available version matching the configured version constraints.

https://www.terraform.io/docs/commands/init.html#upgrade-1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
165
Q

Teddy is using Terraform to deploy infrastructure using modules. Where is the module below stored?

module “monitoring_tools” {
source = “././modules/monitoring_tools”

cluster_hostname = module.k8s_cluster.hostname
}

  • in a private GitLab repository
  • on the Terraform public module registry
  • locally on the instance running Terraform
  • a private module registry in Terraform Cloud (free)
A

locally on the instance running Terraform

Explanation
A local path must begin with either ./ or ../ to indicate that a local path is intended, to distinguish from a module registry address.

https://www.terraform.io/docs/modules/sources.html#terraform-registry

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
166
Q

There are multiple ways to authenticate when using a Terraform provider. However, several methods will result in sensitive information being written to the state file, which is not desirable. Which method below will not result in sensitive information being written to the state file.

  • retrieving the credentials from a data source, such as HashiCorp Vault
  • using a declared variable
  • using environment variables
  • using a tfvars file
A

using environment variables

Explanation
The only method list above that will not result in the username/password being written to the state file is environment variables. All of the other options will result in the provider’s credentials in the state file.

Terraform runs will receive the full text of sensitive variables, and might print the value in logs and state files if the configuration pipes the value through to an output or a resource parameter. Additionally, Sentinel mocks downloaded from runs will contain the sensitive values of Terraform (but not environment) variables. Take care when writing your configurations to avoid unnecessary credential disclosure. Whenever possible, use environment variables since these cannot end up in state files or in Sentinel mocks. (Environment variables can end up in log files if TF_LOG is set to TRACE.)

https: //www.terraform.io/docs/cloud/workspaces/variables.html#sensitive-values
https: //learn.hashicorp.com/tutorials/terraform/sensitive-variables

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
167
Q

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?

module “consul” {
source = “hashicorp/consul/aws”
version = “0.0.5”

servers = 3
}

  • Terraform would return an error, as the version parameter is required
  • Terraform would use the existing module already downloaded
  • Terraform would download the latest version of the module
  • Terraform would skip the module
A

Terraform would use the existing module already downloaded

Explanation
When using modules installed from a module registry, HashiCorp recommends explicitly constraining the acceptable version numbers to avoid unexpected or unwanted changes. The version argument accepts a version constraint string. Terraform will use the newest installed version of the module that meets the constraint; if no acceptable versions are installed, it will download the newest version that meets the constraint.

A version number that meets every applicable constraint is considered acceptable.

Terraform consults version constraints to determine whether it has acceptable versions of itself, any required provider plugins, and any required modules. For plugins and modules, it will use the newest installed version that meets the applicable constraints.

To test this, I ran a terraform init with the code as shown in the file:

$ terraform init
Initializing modules…
Downloading hashicorp/consul/aws 0.0.5 for consul…
- consul in .terraform\modules\consul
- consul.consul_clients in .terraform\modules\consul\modules\consul-cluster
- consul.consul_clients.iam_policies in .terraform\modules\consul\modules\consul-iam-policies
- consul.consul_clients.security_group_rules in .terraform\modules\consul\modules\consul-security-group-rules
- consul.consul_servers in .terraform\modules\consul\modules\consul-cluster
- consul.consul_servers.iam_policies in .terraform\modules\consul\modules\consul-iam-policies
- consul.consul_servers.security_group_rules in .terraform\modules\consul\modules\consul-security-group-rules
Then I removed the constraint from the configuration file and ran a terraform init again:

$ terraform init
Initializing modules…

Initializing the backend…

Initializing provider plugins…
- Reusing previous version of hashicorp/aws from the dependency lock file
- Reusing previous version of hashicorp/template from the dependency lock file
Terraform did not download a newer version of the module. It reused the existing one.

https: //www.terraform.io/docs/configuration/blocks/modules/syntax.html#version
https: //www.terraform.io/docs/language/expressions/version-constraints.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
168
Q

True or False? Performing a terraform plan can modify the existing Terraform state file.

A

False

Explanation
The ultimate goal of a terraform plan is to compare the configuration file against the current state file and read any outputs related to the current figuration. While a terraform plan does perform a terraform refresh by default, the terraform plan does not actually result in changes to the state file.

For additional information, check out this Q&A discussion that I had with another student.

https://www.terraform.io/docs/commands/plan.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
169
Q

Based on the code provided, how many subnets will be created in the AWS account?

variables.tf

variable "private_subnet_names" {
  type    = list(string)
  default = ["private_subnet_a", "private_subnet_b", "private_subnet_c"]
}
variable "vpc_cidr" {
  type    = string
  default = "10.0.0.0/16"
}
variable "public_subnet_names" {
  type    = list(string)
  default = ["public_subnet_1", "public_subnet_2"]
}
main.tf

resource “aws_subnet” “private_subnet” {
count = length(var.private_subnet_names)
vpc_id = aws_vpc.vpc.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index)
availability_zone = data.aws_availability_zones.available.names[count.index]

  tags = {
    Name      = var.private_subnet_names[count.index]
    Terraform = "true"
  }
}
  • 1
  • 0
  • 2
  • 3
A

3

Explanation
The code above will create three subnets. The value of count is determined by the number of strings included in the private_subnet_names variable.

https://www.terraform.io/docs/configuration/functions/length.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
170
Q

What feature of Terraform provides an abstraction above the upstream API and is responsible for understanding API interactions and exposing resources?

  • Terraform configuration file
  • Terraform provisioner
  • Terraform backend
  • Terraform provider
A

Terraform provider

Explanation
Terraform relies on plugins called “providers” to interact with remote systems.

Terraform configurations must declare which providers they require so that Terraform can install and use them. Additionally, some providers require configuration (like endpoint URLs or cloud regions) before they can be used.

https://www.terraform.io/docs/configuration/blocks/providers/index.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
171
Q

Which of the following Terraform CLI commands are valid? (select five)

$ terraform initialize
$ terraform delete
$ terraform taint
$ terraform fmt
$ terraform workspace select
$ terrafrom show
$ terraform login
A
  • terraform workspace select
  • terraform show
  • terraform taint
  • terraform login
  • terraform fmt

Explanation
terraform delete and terraform initialize are not valid Terraform CLI commands.

Correct Answers:

The terraform taint command manually marks a Terraform-managed resource as tainted, forcing it to be destroyed and recreated on the next apply.

The terraform fmt command is used to rewrite Terraform configuration files to a canonical format and style.

The terraform workspace select command is used to choose a different workspace to use for further operations.

The terraform show command is used to provide human-readable output from a state or plan file. This can be used to inspect a plan to ensure that the planned operations are expected, or to inspect the current state as Terraform sees it.

The terraform login command can be used to automatically obtain and save an API token for Terraform Cloud, Terraform Enterprise, or any other host that offers Terraform services.

https://www.terraform.io/docs/commands/fmt.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
172
Q

True or False? A main.tf file is always required when using Terraform?

A

False

Explanation
Although main.tf is the standard name, it’s not necessarily required. Terraform will look for any file with a .tf or .tf.json extension when running terraform commands.

https://www.terraform.io/docs/configuration/index.html#code-organization

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
173
Q

Which of the following is not a benefit of Terraform state?

  • increases performance by reducing the requirement to query multiple resources at once
  • provides a one-to-one mapping of the configuration to real-world resources
  • determines the dependency order for deployed resources
  • reduces the number of outbound traffic by requiring state is stored locally
A

reduces the number of outbound traffic by requiring state is stored locally

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
174
Q

Pam just finished up a new Terraform configuration file and has successfully deployed the configuration on Azure using Terraform open-source. After confirming the configuring on Azure, Pam changes to a new workspace and then heads to lunch. When she arrives back at her desk, Pam decides to destroy the resources to save on cost. When Pam executes a terraform destroy, the output indicates there are no resources to delete.

A

there is no Terraform state in the current workspace she is working in

Explanation
Workspaces isolate their state, so if Pam runs a terraform destroy, Terraform will not see any existing state for this configuration. Pam may use the command terraform workspace select to choose the original workspace where the Azure resources were provisioned in order to properly destroy them in Azure.

https://www.terraform.io/docs/cli/workspaces/index.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
175
Q

Ralphie has executed a terraform apply using a complex Terraform configuration file. However, a few resources failed to deploy due to incorrect variables. After the error is discovered, what happens to the resources that were successfully provisioned?

A

the resources that were successfully provisioned will remain as deployed.

Explanation
During a terraform apply, any resources that are successfully provisioned are maintained as deployed.

On the other hand, resources that failed during the provisioning process, such as a provisioned, will be tainted to be recreated during the next run. https://www.terraform.io/docs/provisioners/index.html#creation-time-provisioners

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
176
Q

When deploying an EC2 instance in AWS, for example, what value is the data source returning?

data “aws_ami” “amzlinux2” {
most_recent = true
owners = [“amazon”]

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-ebs"]
  }
}

resource “aws_instance” “vault” {
ami = data.aws_ami.amzlinux2.id
instance_type = “t3.micro”
key_name = “vault-key”
vpc_security_group_ids = var.sg
subnet_id = var.subnet
associate_public_ip_address = “true”
user_data = file(“vault.sh”)

tags = {
Name = “vault”
}
}

  • the AMI ID for the latest version of the Amazon Linux 2 image
  • a custom AMI for Amazon Linux 2
  • the IP address of an EC2 instance running in AWS
  • the latest used AMI for the Amazon Linux 2 image
A

the AMI ID for the latest version of the Amazon Linux 2 image

Explanation
Within the block body (between { and }) are query constraints defined by the data source. Most arguments in this section depend on the data source, and indeed in this example most_recent, owners and tags are all arguments defined specifically for the aws_ami data source.

https://www.terraform.io/docs/configuration/data-sources.html#using-data-sources

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
177
Q

AutoPlants, Inc is a new startup that uses AI and robotics to grow sustainable and organic vegetables for California farmers’ markets. The organization can quickly burst into the public cloud during the busy season using Terraform to provision additional resources to process AI computations and images. Since its compute stack is proprietary and critical to the organization, it needs a solution to create and publish Terraform modules that only its engineers and architects can use.

Which feature can provide this functionality?

  • public module registry
  • Terraform Enterprise Workspaces
  • private module registry
  • Sentinel
A

private module registry

Explanation
HashiCorp Terraform Enterprise and Cloud offerings deliver a private version of the Module Registry. This allows organizations to safely share private modules with their internal teams.

https://www.terraform.io/docs/cloud/registry/index.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
178
Q

What happens if multiple users attempt to run a terraform apply simultaneously when using a remote backend? (select two)

A
  • if the backend does not support locking, the state file could become corrupted
  • if the backend supports locking, the first terraform apply will lock the file for changes, preventing the second user from running the apply

Explanation
If the state is configured for remote state, the backend selected will determine what happens. If the backend supports locking, the file will be locked for the first user, and that user’s configuration will be applied. The second user’s terraform apply will return an error that the state is locked.

If the remote backend does not support locking, the state file could become corrupted, since multiple users are trying to make changes at the same time.

https://www.terraform.io/docs/state/locking.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
179
Q

Infrastructure as Code (IaC) makes infrastructure changes _______, ________, ________, and __________. (select four)

  • repeatable
  • consistent
  • idempotent
  • highly-available
  • predictable
A

idempotent
predictable
consistent
repeatable

Explanation
IaC makes changes idempotent, consistent, repeatable, and predictable. Without IaC, scaling up infrastructure to meet increased demand may require an operator to remotely connect to each machine and then manually provision and configure many servers by executing a series of commands/scripts. They might open multiple sessions and move between screens, which often results in skipped steps or slight variations between how work is completed, necessitating rollbacks. Perhaps a command was run incorrectly on one instance and reverted before being re-run correctly.

https://www.hashicorp.com/blog/infrastructure-as-code-in-a-private-or-public-cloud

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
180
Q

Rigby is implementing Terraform and was given a configuration that includes the snippet below. Where is this particular module stored?

module “consul” {
source = “hashicorp/consul/aws”
version = “0.1.0”
}

  • locally in the hashicorp/consul/aws directory
  • locally but a directory back from the current directory
  • public Terraform registry
  • a private module registry supported by your organization
A

public Terraform registry

Explanation
Modules on the public Terraform Registry can be referenced using a registry source address of the form //, with each module’s information page on the registry site including the exact address to use.

https://www.terraform.io/docs/modules/sources.html#terraform-registry

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
181
Q

True or False? Any sensitive values referenced in the Terraform code, even as variables, will end up in plain text in the state file.

A

True

Explanation
Any values that are retrieved in a data block or referenced as variables will show up in the state file.

https://www.terraform.io/docs/state/sensitive-data.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
182
Q

True or False? A backend configuration is required for using Terraform.

A

False

Explanation
This is false. If you don’t provide a backend configuration, Terraform will use the local default backend. Remote Backends are completely optional. You can successfully use Terraform without ever having to learn or use a remote backend. However, they do solve pain points that afflict teams at a certain scale. If you’re an individual, you can likely get away with never using backends.

https://www.terraform.io/docs/backends

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
183
Q

Scenario: You have a Terraform configuration file with no defined resources. However, there is a related state file for resources that were created on AWS. What happens when you run a terraform apply?

A

Terraform will destroy all of the resources

Explanation
In this case, since there is a state file with resources, Terraform will match the desired state of no resources since the configuration file doesn’t include any resources. Therefore, all resources defined in the state file will be destroyed.

https://www.terraform.io/docs/state/purpose.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
184
Q

Both Terraform CLI and Terraform Cloud offer a feature called “workspaces”. Which of the following statements are true regarding workspaces? (select three)

  • Run history is logged in a file underneath the working directory of a CLI workspace
  • Terraform Cloud maintains the state version and run history for each workspace
  • Terraform Cloud manages infrastructure collections with a workspace whereas CLI manages collections of infrastructure resources with a persistent working directory
  • Each CLI workspace coincides with a different VCS repo
  • CLI workspaces are alternative state files in the same working directory
A
  • Terraform Cloud maintains the state version and run history for each workspace
  • Terraform Cloud manages infrastructure collections with a workspace whereas CLI manages collections of infrastructure resources with a persistent working directory-
  • CLI workspaces are alternative state files in the same working directory
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
185
Q

Scenario: You are deploying a new application and want to deploy it to multiple AWS regions within the same configuration file. Which of the following features will allow you to configure this?

  • one provider block that defines multiple regions
  • using the default provider along with a single defined provider
  • a provider with multiple versions defined
  • multiple provider blocks using an alias
A
  • multiple provider blocks using an alias
Explanation
You can optionally define multiple configurations for the same provider, and select which one to use on a per-resource or per-module basis. The primary reason for this is to support multiple regions for a cloud platform; other examples include targeting multiple Docker hosts, multiple Consul hosts, etc.

https://www.terraform.io/docs/configuration/providers.html#alias-multiple-provider-configurations

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
186
Q

HashiCorp offers multiple versions of Terraform to meet the needs of individuals to large enterprises. Which of the following offerings provide access to a private module registry? (select four)

Terraform Cloud - Business
Terraform Enterprise (self-hosted)
Terraform Cloud - Team & Governance
Terraform Cloud - Free
Terraform OSS
A

Terraform Cloud - Business
Terraform Enterprise (self-hosted)
Terraform Cloud - Team & Governance
Terraform Cloud - Free

Explanation
The Private Module Registry is available in all versions of Terraform except for Open Source.

https://www.datocms-assets.com/2885/1602500234-terraform-full-feature-pricing-tablev2-1.pdf

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
187
Q

True or False? Before a terraform validate can be run, the directory must be initialized.

A

True

Explanation
Validation requires an initialized working directory with any referenced plugins and modules installed. If the directory is NOT initialized, it will result in an error.

$ terraform validate

Error: Could not load plugin

Plugin reinitialization required. Please run “terraform init”.

Plugins are external binaries that Terraform uses to access and manipulate
resources. The configuration provided requires plugins which can’t be located,
don’t satisfy the version constraints, or are otherwise incompatible.

Terraform automatically discovers provider requirements from your
configuration, including providers used in child modules. To see the
requirements and constraints, run “terraform providers”.

Failed to instantiate provider “registry.terraform.io/hashicorp/aws” to obtain

schema: unknown provider “registry.terraform.io/hashicorp/aws”
https: //www.terraform.io/docs/commands/validate.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
188
Q

Scenario: You have a Terraform configuration file defining resources to deploy on VMware, yet there is no related state file. You have successfully run a terraform init already. What happens when you run a terraform apply?

  • Terraform will scan the VMware infrastructure, create a new state file, and compare the state to the configuration file to determine what resources should be created
  • All existing infrastructure on VMware will be deleted, and the resources defined in the configuration file will be created
  • Terraform will produce an error since there is no state file
  • Since there is no state file associated with this configuration file, the defined resources will be created on the VMware infrastructure
A

Since there is no state file associated with this configuration file, the defined resources will be created on the VMware infrastructure.

Explanation
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

https://www.terraform.io/docs/state/purpose.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
189
Q

Larissa is an experienced IT professional and is working to learn Terraform to manage the F5 load balancers that front-end customer-facing applications. Larissa writes great code, but her formatting seldom meets the Terraform canonical formatting and style recommended by HashiCorp. What built-in tool or command can Larissa use to easily format her code to meet the recommendations for formatting Terraform code?

A

terraform fmt

Explanation
The terraform fmt command is used to rewrite Terraform configuration files to a canonical format and style. This command applies a subset of the Terraform language style conventions, along with other minor adjustments for readability.

https://www.terraform.io/docs/commands/fmt.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
190
Q

Terraform has detailed logs that can be enabled using the TF_LOG environment variable. Which of the following log levels is the most verbose, meaning it will log the most specific logs?

A

TRACE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
191
Q

What is Infrastructure as Code?

A

You write and execute the code to define, deploy, update, and destroy your infrastructure

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
192
Q

What are the benefits of IaC?

A

a. Automation
We can bring up the servers with one script and scale up and down based on our load with the same script.
b. Reusability of the code
We can reuse the same code
c. Versioning
We can check it into version control and we get versioning. Now we can see an incremental history of who changed what, how is our infrastructure actually defined at any given point of time, and we have this transparency of documentation
IaC makes changes idempotent, consistent, repeatable, and predictable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
193
Q

How using IaC make it easy to provision infrastructure?

A

IaC makes it easy to provision and apply infrastructure configurations, saving time. It standardizes workflows across different infrastructure providers (e.g., VMware, AWS, Azure, GCP, etc.) by using a common syntax across all of them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
194
Q

What is Ideompodent in terms of IaC?

A

The idempotent characteristic provided by IaC tools ensures that, even if the same code is applied multiple times, the result remains the same.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
195
Q

What are Day 0 and Day 1 activities?

A

IaC can be applied throughout the lifecycle, both on the initial build, as well as throughout the life of the infrastructure. Commonly, these are referred to as Day 0 and Day 1 activities.

“Day 0” code provisions and configures your initial infrastructure. (initial build)
“Day 1” refers to OS and application configurations you apply after you’ve initially built your infrastructure. (OS/App)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
196
Q

What are the use cases of Terraform?

A
Heroku App Setup
Multi-Tier Applications
Self-Service Clusters
Software Demos
Disposable Environments
Software Defined Networking
Resource Schedulers
Multi-Cloud Deployment
https://www.terraform.io/intro/use-cases.html
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
197
Q

What are the advantages of Terraform?

A

Platform Agnostic
State Management
Operator Confidence
https://learn.hashicorp.com/terraform/getting-started/intro

198
Q

Where do you describe all the components or your entire datacenter so that Terraform provision those?

A

Configuration files ends with *.tf

199
Q

How can Terraform build infrastructure so efficiently?

A
  • Terraform builds a graph of all your resources,
  • Parallelizes the creation and modification of any non-dependent resources.

Because of this, Terraform builds infrastructure as efficiently as possible, and operators get insight into dependencies in their infrastructure.

200
Q

What is multi-cloud deployment?

A

Provisoning your infrastrcutire into multiple cloud providers to increase the fault-tolerance of your applications.

201
Q

How multi-cloud deployment is useful?

A

By using only a single region or cloud provider, fault tolerance is limited by the availability of that provider.
Having a multi-cloud deployment allows for more graceful recovery of the loss of a region or entire provider.

202
Q

What is cloud-agnostic in terms of provisioning tools?

A

cloud-agnostic and allows a single configuration to be used to manage multiple providers, and to even handle cross-cloud dependencies.

203
Q

What is the use of terraform being cloud-agnostic?

A

It simplifies management and orchestration, helping operators build large-scale multi-cloud infrastructures.

204
Q

What is the Terraform State?

A

Every time you run Terraform, it records information about what infrastructure it created in a Terraform state file. By default, when you run Terraform in the folder /some/folder, Terraform creates the file /some/folder/terraform.tfstate

This file contains a custom JSON format that records a mapping from the Terraform resources in your configuration files to the representation of those resources in the real world.

205
Q

Which of the following Terraform commands will automatically refresh the state unless supplied with additional flags or arguments? Choose TWO correct answers.

A

terraform plan

terraform apply

206
Q

What happens when you apply Terraform configuration? Choose TWO correct answers.

A
  • Terraform makes any infrastructure changes defined in your configuration
  • Terraform updates the state file with any configuration changes it made
207
Q

Which flag is used to find more information about a Terraform command? For example, you need additional information about how to use the plan command. You would type: terraform plan _____. Type your answer in the field provided. The text field is not case-sensitive and all variations of the correct answer are accepted.

A

-h
-help
–help
–h
terraform plan -h
terraform plan –h
terraform plan -help
terraform -h plan
pan -h
plan –h

208
Q

When you run terraform init command, all the providers are installed in the current working directory. Is this true?

A

Providers downloaded by terraform init are only installed for the current working directory; other working directories can have their own installed provider versions.

Note that terraform init cannot automatically download providers that are not distributed by HashiCorp. See Third-party Plugins below for installation instructions.

209
Q

How do you constrain the provider version?

A

To constrain the provider version as suggested, add a required_providers block inside a terraform block:

terraform {
  required_providers {
    aws = "~> 1.0"
  }
}
210
Q

How do you upgrade to the latest acceptable version of the provider?

A

terraform init -upgrade

It upgrade to the latest acceptable version of each provider
This command also upgrades to the latest versions of all Terraform modules.

211
Q

How many ways you can configure provider versions?

A
1. With required_providers blocks under terraform block
terraform {
  required_providers {
    aws = "~> 1.0"
  }
}
  1. Provider version constraints can also be specified using a version argument within a provider block
    provider {
    version= “1.0”
    }
212
Q

How do you configure Multiple Provider Instances?

A
alias
You can optionally define multiple configurations for the same provider, and select which one to use on a per-resource or per-module basis.
213
Q

Why do we need Multiple Provider instances?

A

Some of the example scenarios:

a. multiple regions for a cloud platform
b. targeting multiple Docker hosts
c. multiple Consul hosts, etc.

214
Q

How do we define multiple Provider configurations?

A

To include multiple configurations for a given provider, include multiple provider blocks with the same provider name, but set the alias meta-argument to an alias name to use for each additional configuration.

# The default provider configuration
provider "aws" {
  region = "us-east-1"
}
# Additional provider configuration for west coast region
provider "aws" {
  alias  = "west"
  region = "us-west-2"
}
215
Q

How do you select alternate providers?

A

By default, resources use a default provider configuration inferred from the first word of the resource type name. For example, a resource of type aws_instance uses the default (un-aliased) aws provider configuration unless otherwise stated.

resource “aws_instance” “foo” {
provider = aws.west

  # ...
}
216
Q

What is the location of the user plugins directory?

A

Windows %APPDATA%\terraform.d\plugins

All other systems ~/.terraform.d/plugins

217
Q

Third-party plugins should be manually installed. Is that true?

A

True

218
Q

The command terraform init cannot install third-party plugins? True or false?

A

True
Install third-party providers by placing their plugin executables in the user plugins directory. The user plugins directory is in one of the following locations, depending on the host operating system
Once a plugin is installed, terraform init can initialize it normally. You must run this command from the directory where the configuration files are located.

219
Q

What is the naming scheme for provider plugins?

A

terraform-provider-_vX.Y.Z

220
Q

What is the CLI configuration File?

A

The CLI configuration file configures per-user settings for CLI behaviors, which apply across all Terraform working directories.
It is named either .terraformrc or terraform.rc

221
Q

Where is the location of the CLI configuration File?

A

On Windows, the file must be named named terraform.rc and placed in the relevant user’s %APPDATA% directory.
On all other systems, the file must be named .terraformrc (note the leading period) and placed directly in the home directory of the relevant user.
The location of the Terraform CLI configuration file can also be specified using the TF_CLI_CONFIG_FILE environment variable.

222
Q

How do you enable Provider Plugin Cache?

A

To enable the plugin cache, use the plugin_cache_dir setting in the CLI configuration file.
plugin_cache_dir = “$HOME/.terraform.d/plugin-cache”

Alternatively, the TF_PLUGIN_CACHE_DIR environment variable can be used to enable caching or to override an existing cache directory within a particular shell session:

export TF_PLUGIN_CACHE_DIR=”$HOME/.terraform.d/plugin-cache”

223
Q

When you are using plugin cache you end up growing cache directory with different versions. Whose responsibility to clean it?

A

User
Terraform will never itself delete a plugin from the plugin cache once it’s been placed there. Over time, as plugins are upgraded, the cache directory may grow to contain several unused versions which must be manually deleted.

224
Q

Why do we need to initialize the directory?

A
When you create a new configuration — or check out an existing configuration from version control — you need to initialize the directory
// Example
provider "aws" {
  profile = "default"
  region  = "us-east-1"
}
resource "aws_instance" "example" {
  ami           = "ami-2757f631"
  instance_type = "t2.micro"
}
Initializing a configuration directory downloads and installs providers used in the configuration, which in this case is the aws provider. Subsequent commands will use local settings and data during initialization.
225
Q

What is the command to initialize the directory?

A

terraform init

226
Q

If different teams are working on the same configuration. How do you make files to have consistent formatting?

A

terraform fmt

This command automatically updates configurations in the current directory for easy readability and consistency.

227
Q

If different teams are working on the same configuration. How do you make files to have syntactically valid and internally consistent?

A

terraform validate
This command will check and report errors within modules, attribute names, and value types.
Validate your configuration. If your configuration is valid, Terraform will return a success message.

228
Q

What is the command to create infrastructure?

A

terraform apply

229
Q

What is the command to show the execution plan and not apply?

A

terraform plan

230
Q

How do you inspect the current state of the infrastructure applied?

A

terraform show
When you applied your configuration, Terraform wrote data into a file called terraform.tfstate. This file now contains the IDs and properties of the resources Terraform created so that it can manage or destroy those resources going forward.

231
Q

If your state file is too big and you want to list the resources from your state. What is the command?

A

terraform state list

https://learn.hashicorp.com/terraform/getting-started/build#manually-managing-state

232
Q

What is plug-in based architecture?

A

Defining additional features as plugins to your core platform or core application. This provides extensibility, flexibility and isolation

233
Q

What are Provisioners?

A

If you need to do some initial setup on your instances, then provisioners let you upload files, run shell scripts, or install and trigger other software like configuration management tools, etc.

234
Q

How do you define provisioners?

A

resource “aws_instance” “example” {
ami = “ami-b374d5a5”
instance_type = “t2.micro”

provisioner “local-exec” {
command = “echo hello > hello.txt”
}
}

Provisioner block within the resource block. Multiple provisioner blocks can be added to define multiple provisioning steps. Terraform supports multiple provisioners
https://learn.hashicorp.com/terraform/getting-started/provision

235
Q

What are the types of provisioners?

A

local-exec

remote-exec

236
Q

What is a local-exec provisioner and when do we use it?

A

The local-exec provisioner executing command locally on your machine running Terraform.
We use this when we need to do something on our local machine without needing any external URL

237
Q

What is a remote-exec provisioner and when do we use it?

A

Another useful provisioner is remote-exec which invokes a script on a remote resource after it is created.
This can be used to run a configuration management tool, bootstrap into a cluster, etc.

238
Q

Are provisioners runs only when the resource is created or destroyed?

A

Provisioners are only run when a resource is created or destroyed. Provisioners that are run while destroying are Destroy provisioners.
They are not a replacement for configuration management and changing the software of an already-running server, and are instead just meant as a way to bootstrap a server.

239
Q

What do we need to use a remote-exec?

A

In order to use a remote-exec provisioner, you must choose an “ssh or winrm” connection in the form of a “connection block” within the provisioner.

Here is an example
provider "aws" {
  profile = "default"
  region  = "us-west-2"
}
resource "aws_key_pair" "example" {
  key_name   = "examplekey"
  public_key = file("~/.ssh/terraform.pub")
}
resource "aws_instance" "example" {
  key_name      = aws_key_pair.example.key_name
  ami           = "ami-04590e7389a6e577c"
  instance_type = "t2.micro"
connection {
    type        = "ssh"
    user        = "ec2-user"
    private_key = file("~/.ssh/terraform")
    host        = self.public_ip
  }
provisioner "remote-exec" {
    inline = [
      "sudo amazon-linux-extras enable nginx1.12",
      "sudo yum -y install nginx",
      "sudo systemctl start nginx"
    ]
  }
}
240
Q

When terraform mark the resources are tainted?

A

If a resource successfully creates but fails during provisioning, Terraform will error and mark the resource as “tainted”.
A resource that is tainted has been physically created, but can’t be considered safe to use since provisioning failed.

241
Q

You applied the infrastructure with terraform apply and you have some tainted resources. You run an execution plan now what happens to those tainted resources?

A

When you generate your next execution plan, Terraform will not attempt to restart provisioning on the same resource because it isn’t guaranteed to be safe.
Instead, Terraform will remove any tainted resources and create new resources, attempting to provision them again after creation.
https://learn.hashicorp.com/terraform/getting-started/provision

242
Q

Terraform also does not automatically roll back and destroy the resource during the apply when the failure happens. Why?

A

Terraform also does not automatically roll back and destroy the resource during the apply when the failure happens because that would go against the execution plan: the execution plan would’ve said a resource will be created but does not say it will ever be deleted. If you create an execution plan with a tainted resource, however, the plan will clearly state that the resource will be destroyed because it is tainted.
https://learn.hashicorp.com/terraform/getting-started/provision

243
Q

How do you manually taint a resource?

A

terraform taint resource.id

244
Q

Does the taint command modify the infrastructure?

A

terraform taint resource.id

This command will not modify infrastructure
Modifies the state file in order to mark a resource as tainted.
Once a resource is marked as tainted, the next plan will show that the resource will be destroyed and recreated and the next apply will implement this change.

245
Q

By default, provisioners that fail will also cause the Terraform apply itself to fail. Is this true?

A

True

246
Q

By default, provisioners that fail will also cause the Terraform apply itself to fail. How do you change this?

A

The on_failure setting can be used to change this.
The allowed values are:
continue: Ignore the error and continue with creation or destruction.
fial: Raise an error and stop applying (the default behavior). If this is a creation provisioner, taint the resource.

// Example
resource "aws_instance" "web" {
  # ...
  provisioner "local-exec" {
    command  = "echo The server's IP address is ${self.private_ip}"
    on_failure = "continue"
  }
}
247
Q

How do you define destroy provisioner and give an example?

A

You can define destroy provisioner with the parameter when
provisioner “remote-exec” {
when = “destroy”

# 

}

248
Q

Can you export the debug logs from terraform just by setting TF_LOG_PATH environment variable and providing a path as the value to this variable?

A

No You also need to export the variable TF_LOG and set it to one of the log levels.

249
Q

How do you apply constraints for the provider versions?

A
The required_providers setting is a map specifying a version constraint for each provider required by your configuration.
terraform {
  required_providers {
    aws = ">= 2.7.0"
  }
}
250
Q

What should you use to set both a lower and upper bound on versions for each provider?

A
~>
terraform {
  required_providers {
    aws = "~> 2.7.0"
  }
}
251
Q

How do you try experimental features?

A

In releases where experimental features are available, you can enable them on a per-module basis by setting the experiments argument inside a terraform block:

terraform {
experiments = [example]
}

252
Q

When does the terraform does not recommend using provisions?

A
  • Passing data into virtual machines and other compute resources
  • Running configuration management software

https: //www.terraform.io/docs/provisioners/#passing-data-into-virtual-machines-and-other-compute-resources
https: //www.terraform.io/docs/provisioners/#running-configuration-management-software

253
Q

Expressions in provisioner blocks cannot refer to their parent resource by name. Is this true?

A

True
The self object represents the provisioner’s parent resource, and has all of that resource’s attributes.
For example, use self.public_ip to reference an aws_instance’s public_ip attribute.

254
Q

What does this symbol version = “~> 1.0” mean when defining versions?

A

Any version more than 1.0 and less than 2.0

255
Q

Terraform supports both cloud and on-premises infrastructure platforms. Is this true?

A

True

256
Q

Terraform assumes an empty default configuration for any provider that is not explicitly configured. A provider block can be empty. Is this true?

A

True

257
Q

How do you configure the required version of Terraform CLI can be used with your configuration?

A

The required_version setting can be used to constrain which versions of the Terraform CLI can be used with your configuration. If the running version of Terraform doesn’t match the constraints specified, Terraform will produce an error and exit without taking any further actions.

258
Q

Terraform CLI versions and provider versions are independent of each other. Is this true?

A

True

259
Q

You are configuring aws provider and it is always recommended to hard code aws credentials in *.tf files. Is this true?

A

False
HashiCorp recommends that you never hard-code credentials into *.tf configuration files. We are explicitly defining the default AWS config profile here to illustrate how Terraform should access sensitive credentials.
If you leave out your AWS credentials, Terraform will automatically search for saved API credentials (for example, in ~/.aws/credentials) or IAM instance profile credentials. This is cleaner when .tf files are checked into source control or if there is more than one admin user

260
Q

You are provisioning the infrastructure with the command terraform apply and you noticed one of the resources failed. How do you remove that resource without affecting the whole infrastructure?

A

You can taint the resource and the next apply will destroy the resource
terraform taint

261
Q

What is command fmt?

A

The terraform fmt command is used to rewrite Terraform configuration files to a canonical format and style. This command applies a subset of the Terraform language style conventions, along with other minor adjustments for readability.

262
Q

What is the recommended approach after upgrading terraform?

A

The canonical format may change in minor ways between Terraform versions, so after upgrading Terraform we recommend to proactively run terraform fmt on your modules along with any other changes you are making to adopt the new version.

263
Q

What is the command usage?

A

terraform fmt [options] [DIR]

264
Q

By default, fmt scans the current directory for configuration files. Is this true?

A

True
By default, fmt scans the current directory for configuration files. If the dir argument is provided then it will scan that given directory instead. If dir is a single dash (-) then fmt will read from standard input (STDIN).

265
Q

You are formatting the configuration files and what is the flag you should use to see the differences?

A

terraform fmt -diff

266
Q

You are formatting the configuration files and what is the flag you should use to process the subdirectories as well?

A

terraform fmt -recursive

267
Q

You are formatting configuration files in a lot of directories and you don’t want to see the list of file changes. What is the flag that you should use?

A

terraform fmt -list=false

268
Q

What is the command taint?

A

The terraform taint command manually marks a Terraform-managed resource as tainted, forcing it to be destroyed and recreated on the next apply.
This command will not modify infrastructure, but does modify the state file in order to mark a resource as tainted. Once a resource is marked as tainted, the next plan will show that the resource will be destroyed and recreated and the next apply will implement this change.

269
Q

What is the command usage?

A

terraform taint [options] address
The address argument is the address of the resource to mark as tainted. The address is in the resource address syntax syntax

270
Q

When you are tainting a resource terraform reads the default state file terraform.tfstate. What is the flag you should use to read from a different path?

A

terraform taint -state=/path

271
Q

Give an example of tainting a single resource?

A
terraform taint aws_security_group.allow_all
The resource aws_security_group.allow_all in the module root has been marked as tainted.
272
Q

Give an example of tainting a resource within a module?

A

terraform taint “module.couchbase.aws_instance.cb_node[9]”

Resource instance module.couchbase.aws_instance.cb_node[9] has been marked as tainted.

273
Q

What is the command import?

A

The terraform import command is used to import existing resources into Terraform.
Terraform is able to import existing infrastructure. This allows you take resources you’ve created by some other means and bring it under Terraform management.
This is a great way to slowly transition infrastructure to Terraform, or to be able to be confident that you can use Terraform in the future if it potentially doesn’t support every feature you need today.

274
Q

What is the command import usage?

A

terraform import [options] ADDRESS ID

275
Q

What is the default workspace name?

A

default

276
Q

What are workspaces?

A

Each Terraform configuration has an associated backend that defines how operations are executed and where persistent data such as the Terraform state are stored.

The persistent data stored in the backend belongs to a workspace.

Initially, the backend has only one workspace, called “default”, and thus there is only one Terraform state associated with that configuration.

Certain backends support multiple named workspaces, allowing multiple states to be associated with a single configuration.

277
Q

What is the command to list the workspaces?

A

terraform workspace list

278
Q

What is the command to create a new workspace?

A

terraform workspace new

279
Q

What is the command to show the current workspace?

A

terraform workspace show

280
Q

What is the command to switch the workspace?

A

terraform workspace select

281
Q

What is the command to delete the workspace?

A

terraform workspace delete

282
Q

Can you delete the default workspace?

A

No. You can’t ever delete the default workspace

283
Q

You are working on the different workspaces and you want to use a different number of instances based on the workspace. How do you achieve that?

A

resource “aws_instance” “example” {
count = “${terraform.workspace == “default” ? 5 : 1}”

  # ... other arguments
}
284
Q

You are working on the different workspaces and you want to use tags based on the workspace. How do you achieve that?

A

resource “aws_instance” “example” {
tags = {
Name = “web - ${terraform.workspace}”
}

  # ... other arguments
}
285
Q

You want to create a parallel, distinct copy of a set of infrastructure in order to test a set of changes before modifying the main production infrastructure. How do you achieve that?

A

Workspaces

286
Q

What is the command state?

A

The terraform state command is used for advanced state management. As your Terraform usage becomes more advanced, there are some cases where you may need to modify the Terraform state. Rather than modify the state directly, the terraform state commands can be used in many cases instead.
https://www.terraform.io/docs/commands/state/index.html

287
Q

What is the command usage?

A

terraform state [options] [args]

288
Q

. You are working on terraform files and you want to list all the resources. What is the command you should use?

A

terraform state list

289
Q

How do you list the resources for the given name?

A

terraform state list

290
Q

What is the command that shows the attributes of a single resource in the state file?

A

terraform state show ‘resource name’

291
Q

How do you do debugging terraform?

A

Terraform has detailed logs which can be enabled by setting the TF_LOG environment variable to any value.
This will cause detailed logs to appear on stderr.
You can set TF_LOG to one of the log levels TRACE, DEBUG, INFO, WARN or ERROR to change the verbosity of the logs. TRACE is the most verbose and it is the default if TF_LOG is set to something other than a log level name.
To persist logged output you can set TF_LOG_PATH in order to force the log to always be appended to a specific file when logging is enabled.
Note that even when TF_LOG_PATH is set, TF_LOG must be set in order for any logging to be enabled.
https://www.terraform.io/docs/internals/debugging.html

292
Q

If terraform crashes where should you see the logs?

A

“crash.log”

If Terraform ever crashes (a “panic” in the Go runtime), it saves a log file with the debug logs from the session as well as the panic message and backtrace to crash.log.
https://www.terraform.io/docs/internals/debugging.html

293
Q

What is the first thing you should do when the terraform crashes?

A

panic message

The most interesting part of a crash log is the panic message itself and the backtrace immediately following. So the first thing to do is to search the file for panic
https://www.terraform.io/docs/internals/debugging.html

294
Q

You are building infrastructure for different environments for example test and dev. How do you maintain separate states?

A

There are two primary methods to separate state between environments:

  • directories
  • workspaces
295
Q

What is the difference between directory-separated and workspace-separated environments?

A

“Directory separated” environments rely on “duplicate Terraform code”, which may be useful if your deployments need to differ, for example, to test infrastructure changes in development. But they can run the risk of creating drift between the environments over time. (UAT Testing)

“Workspace-separated” environments use the same Terraform code but have “different state files”, which is useful if you want your environments to stay as similar to each other as possible, for example, if you are providing development infrastructure to a team that wants to simulate running in production. (Promoting an environment)

296
Q

What is the command to pull the remote state?

A

terraform state pull

This command will download the state from its current location and output the raw format to stdout.
https://www.terraform.io/docs/commands/state/pull.html

297
Q

What is the command is used manually to upload a local state file to a remote state

A

terraform state push

The terraform state push command is used to manually upload a local state file to remote state. This command also works with local state.
https://www.terraform.io/docs/commands/state/push.html

298
Q

The command terraform taint modifies the state file and doesn’t modify the infrastructure. Is this true?

A

True

This command will not modify infrastructure, but does modify the state file in order to mark a resource as tainted. Once a resource is marked as tainted, the next plan will show that the resource will be destroyed and recreated and the next apply will implement this change.

299
Q

Your team has decided to use terraform in your company and you have existing infrastructure. How do you migrate your existing resources to terraform and start using it?

A

You should use terraform import and modify the infrastructure in the terraform files and do the terraform workflow (init, plan, apply)

300
Q

When you are working with the workspaces how do you access the current workspace in the configuration files?

A

${terraform.workspace}

301
Q

When you are using workspaces where does the Terraform save the state file for the local state?

A

terraform.tfstate.d

For local state, Terraform stores the workspace states in a directory called terraform.tfstate.d.

302
Q

When you are using workspaces where does the Terraform save the state file for the remote state?

A

For remote state, the workspaces are stored directly in the configured backend.

303
Q

How do you remove items from the Terraform state?

A

terraform state rm ‘packet_device.worker’
The terraform state rm command is used to remove items from the Terraform state. This command can remove single resources, single instances of a resource, entire modules, and more.
https://www.terraform.io/docs/commands/state/rm.html

304
Q

How do you move the state from one source to another?

A

terraform state mv ‘module.app’ ‘module.parent.module.app’

The terraform state mv command is used to move items in a Terraform state. This command can move single resources, single instances of a resource, entire modules, and more. This command can also move items to a completely different state file, enabling efficient refactoring.
https://www.terraform.io/docs/commands/state/mv.html

305
Q

How do you rename a resource in the terraform state file?

A

terraform state mv ‘packet_device.worker’ ‘packet_device.helper’

The above example renames the packet_device resource named worker to helper:

306
Q

Where do you find and explore terraform Modules?

A
The "Terraform Registry" makes it simple to find and use modules.
The search query will look at module name, provider, and description to match your search terms. On the results page, filters can be used to further refine search results.
307
Q

How do you make sure that modules have stability and compatibility?

A

By default, only verified modules are shown in search results.
Verified modules are reviewed by HashiCorp to ensure stability and compatibility.
By using the filters, you can view unverified modules as well.

308
Q

How do you download any modules?

A
You need to add any module in the configuration file like below
module "consul" {
  source = "hashicorp/consul/aws"
  version = "0.1.0"
}

terraform init command will download and cache any modules referenced by a configuration.

309
Q

What is the syntax for referencing a registry module?

A
//
// for example
module "consul" {
  source = "hashicorp/consul/aws"
  version = "0.1.0"
}
310
Q

What is the syntax for referencing a private registry module?

A
///
// for example
module "vpc" {
  source = "app.terraform.io/example_corp/vpc/aws"
  version = "0.9.3"
}
311
Q

The terraform recommends that all modules must follow semantic versioning. Is this true?

A

True

312
Q

What is a Terraform Module?

A

A Terraform module is a set of Terraform configuration files in a single directory.

Even a simple configuration consisting of a single directory with:
“one or more .tf files is a module.”

313
Q

Why do we use modules for?

A
  • Organize configuration
  • Encapsulate configuration
  • Re-use configuration
  • Provide consistency and ensure best practices
    https: //learn.hashicorp.com/terraform/modules/modules-overview
314
Q

How do you call modules in your configuration?

A
Your configuration can use "module blocks" to call modules in other directories. 
When Terraform encounters a module block, it loads and processes that module's configuration files.
315
Q

How many ways you can load modules?

A
  • Local
  • Remote
Modules can either be loaded from the local filesystem or from a remote source. 
Terraform supports a variety of remote sources, including the Terraform Registry, most version control systems, HTTP URLs, and Terraform Cloud or Terraform Enterprise private module registries.
316
Q

What are the best practices for using Modules?

A
  1. Start writing your configuration with modules in mind. Even for modestly complex Terraform configurations managed by a single person, you’ll find the benefits of using modules outweigh the time it takes to use them properly.
  2. Use local modules to organize and encapsulate your code. Even if you aren’t using or publishing remote modules, organizing your configuration in terms of modules from the beginning will significantly reduce the burden of maintaining and updating your configuration as your infrastructure grows in complexity.
  3. Use the public Terraform Registry to find useful modules. This way you can more quickly and confidently implement your configuration by relying on the work of others to implement common infrastructure scenarios.
  4. Publish and share modules with your team. Most infrastructure is managed by a team of people, and modules are important way that teams can work together to create and maintain infrastructure. As mentioned earlier, you can publish modules either publicly or privately. We will see how to do this in a future guide in this series.
    https: //learn.hashicorp.com/terraform/modules/modules-overview#module-best-practices
317
Q

What are the different source types for calling modules?

A
Local paths
Terraform Registry
GitHub
Generic Git, Mercurial repositories
Bitbucket
HTTP URLs
S3 buckets
GCS buckets
https://www.terraform.io/docs/modules/sources.html
318
Q

What are the arguments you need for using modules in your configuration?

A
source and version
// example
module "consul" {
  source = "hashicorp/consul/aws"
  version = "0.1.0"
}
319
Q

How do you set input variables for the modules?

A
The configuration that calls a module is responsible for setting its input values, which are passed as arguments in the module block. Aside from source and version, most of the arguments to a module block will set variable values.
On the Terraform registry page for the AWS VPC module, you will see an Inputs tab that describes all of the input variables that module supports.

For example, we have defined a lot of input variables for the modules such as ads, cidr, name, etc

provider “aws” {
region = “us-west-2”
}

module “vpc” {
source = “terraform-aws-modules/vpc/aws”
version = “2.21.0”

name = var.vpc_name
cidr = var.vpc_cidr

azs = var.vpc_azs
private_subnets = var.vpc_private_subnets
public_subnets = var.vpc_public_subnets

enable_nat_gateway = var.vpc_enable_nat_gateway

tags = var.vpc_tags
}

module “ec2_instances” {
source = “terraform-aws-modules/ec2-instance/aws”
version = “2.12.0”

name = “my-ec2-cluster”
instance_count = 2

ami = “ami-0c5204531f799e0c6”
instance_type = “t2.micro”
vpc_security_group_ids = [module.vpc.default_security_group_id]
subnet_id = module.vpc.public_subnets[0]

  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}
320
Q

How do you access output variables from the modules?

A

You can access them by referring

module..

321
Q

Where do you put output variables in the configuration?

A

Module outputs are usually either passed to other parts of your configuration or defined as outputs in your root module. You will see both uses in this guide.
Inside your configuration’s directory, outputs.tf will need to contain:

output “vpc_public_subnets” {
description = “IDs of the VPC’s public subnets”
value = module.vpc.public_subnets
}

output “ec2_instance_public_ips” {
description = “Public IP addresses of EC2 instances”
value = module.ec2_instances.public_ip
}

322
Q

How do you pass input variables in the configuration?

A
You can define variables.tf in the root folder
variable "vpc_name" {
  description = "Name of VPC"
  type        = string
  default     = "example-vpc"
}

Then you can access these varibles in the configuration like this
module “vpc” {
source = “terraform-aws-modules/vpc/aws”
version = “2.21.0”

name = var.vpc_name
cidr = var.vpc_cidr

azs = var.vpc_azs
private_subnets = var.vpc_private_subnets
public_subnets = var.vpc_public_subnets

enable_nat_gateway = var.vpc_enable_nat_gateway

tags = var.vpc_tags
}

323
Q

What is the child module?

A

A module that is called by another configuration is sometimes referred to as a “child module” of that configuration.

324
Q

When you use local modules you don’t have to do the command init or get every time there is a change in the local module. why?

A

When installing a local module, Terraform will instead refer directly to the source directory.
Because of this, Terraform will automatically notice changes to local modules without having to re-run terraform init or terraform get.

325
Q

When you use remote modules what should you do if there is a change in the module?

A

When installing a remote module, Terraform will download it into the .terraform directory in your configuration’s root directory.
You should initialize with terraform init

326
Q

A simple configuration consisting of a single directory with one or more .tf files is a module. Is this true?

A

True

327
Q

When using a new module for the first time, you must run either terraform init or terraform get to install the module. Is this true?

A

True

328
Q

When installing the modules and where does the terraform save these modules?

A
.terraform/modules
// Example
.terraform/modules
├── ec2_instances
│   └── terraform-aws-modules-terraform-aws-ec2-instance-ed6dcd9
├── modules.json
└── vpc
    └── terraform-aws-modules-terraform-aws-vpc-2417f60
329
Q

What is the required argument for the module?

A

“source”

All modules require a source argument, which is a meta-argument defined by Terraform CLI. Its value is either the path to a local directory of the module’s configuration files, or a remote module source that Terraform should download and use. This value must be a literal string with no template sequences; arbitrary expressions are not allowed. For more information on possible values for this argument, see Module Sources.

330
Q

What are the other optional meta-arguments along with the source when defining modules

A

“version”

  • (Optional) A version constraint string that specifies which versions of the referenced module are acceptable. The newest version matching the constraint will be used. version is supported only for modules retrieved from module registries.

“providers”

  • (Optional) A map whose keys are provider configuration names that are expected by child module and whose values are corresponding provider names in the calling module. This allows provider configurations to be passed explicitly to child modules. If not specified, the child module inherits all of the default (un-aliased) provider configurations from the calling module.
331
Q

What is the Core Terraform workflow?

A

The core Terraform workflow has three steps:

  1. Write - Author infrastructure as code.
  2. Plan - Preview changes before applying.
  3. Apply - Provision reproducible infrastructure.
332
Q

What is the workflow when you work as an Individual Practitioner?

A

https://www.terraform.io/guides/core-workflow.html#working-as-an-individual-practitioner

333
Q

What is the workflow when you work as a team?

A

https://www.terraform.io/guides/core-workflow.html#working-as-a-team

334
Q

What is the workflow when you work as a large organization?

A

https://www.terraform.io/guides/core-workflow.html#the-core-workflow-enhanced-by-terraform-cloud

335
Q

What is the command init?

A

The terraform init command is used to initialize a working directory containing Terraform configuration files.
This is the first command that should be run after writing a new Terraform configuration or cloning an existing one from version control.
It is safe to run this command multiple times.

336
Q

You recently joined a team and you cloned a terraform configuration files from the version control system. What is the first command you should use?

A

terraform init
This command performs several different initialization steps in order to prepare a working directory for use.
This command is always safe to run multiple times, to bring the working directory up to date with changes in the configuration.
Though subsequent runs may give errors, this command will never delete your existing configuration or state.
If no arguments are given, the configuration in the current working directory is initialized. It is recommended to run Terraform with the current working directory set to the root directory of the configuration, and omit the DIR argument.
https://www.terraform.io/docs/commands/init.html

337
Q

What is the flag you should use to upgrade modules and plugins a part of their respective installation steps?

A

upgrade

terraform init -upgrade

338
Q

When you are doing initialization with terraform init, you want to skip child module installation. What should you do?

A

terraform init -get=false

339
Q

When you are doing initialization where do all the plugins stored?

A

On most operationg systems : ~/.terraform.d/plugins

on Windows : %APPDATA%\terraform.d\plugins

340
Q

When you are doing initialization with terraform init, you want to skip plugin installation. What should you do?

A

terraform init -get-plugins=false

Skips plugin installation. Terraform will use plugins installed in the user plugins directory, and any plugins already installed for the current working directory. If the installed plugins aren’t sufficient for the configuration, init fails.

341
Q

What does the command terraform validate does?

A

The terraform validate command validates the configuration files in a directory, referring only to the configuration and not accessing any remote services such as remote state, provider APIs, etc.

Validate runs checks that verify whether a configuration is syntactically valid and internally consistent, regardless of any provided variables or existing state.

It is thus primarily useful for general verification of reusable modules, including the correctness of attribute names and value types.
https://www.terraform.io/docs/commands/validate.html

342
Q

What does the command plan do?

A

The terraform plan command is used to create an execution plan. Terraform performs a refresh, unless explicitly disabled, and then determines what actions are necessary to achieve the desired state specified in the configuration files.

343
Q

What does the command apply do?

A

The terraform apply command is used to apply the changes required to reach the desired state of the configuration, or the pre-determined set of actions generated by a terraform plan execution plan.
https://www.terraform.io/docs/commands/apply.html

344
Q

You are applying the infrastructure with the command apply and you don’t want to do interactive approval. Which flag should you use?

A

terraform apply -auto-approve

https://www.terraform.io/docs/commands/apply.html

345
Q

What does the command destroy do?

A

The terraform destroy command is used to destroy the Terraform-managed infrastructure.

346
Q

How do you preview the behavior of the command terraform destroy?

A

terraform plan -destroy

347
Q

What are implicit and explicit dependencies?

A

“Implicit dependency:”
By studying the resource attributes used in interpolation expressions, Terraform can automatically infer when one resource depends on another.
Terraform uses this dependency information to determine the correct order in which to create the different resources.
Implicit dependencies via interpolation expressions are the primary way to inform Terraform about these relationships and should be used whenever possible.

“Explicit dependency:”
Sometimes there are dependencies between resources that are not visible to Terraform. The depends_on argument is accepted by any resource and accepts a list of resources to create explicit dependencies for.

348
Q

Give an example of implicit dependency?

A
In the example below, the reference to aws_instance.example.id creates an implicit dependency on the aws_instance named example.
provider "aws" {
  profile    = "default"
  region     = "us-east-1"
}
resource "aws_instance" "example" {
  ami           = "ami-b374d5a5"
  instance_type = "t2.micro"
}
resource "aws_eip" "ip" {
    vpc = true
    instance = aws_instance.example.id
}
349
Q

Give an example of explicit dependency?

A
In the example below, an application we will run on our EC2 instance expects to use a specific Amazon S3 bucket, but that dependency is configured inside the application code and thus not visible to Terraform. In that case, we can use depends_on to explicitly declare the dependency
resource "aws_s3_bucket" "example" {
  bucket = "some_bucket"
  acl    = "private"
}
resource "aws_instance" "example" {
  ami           = "ami-2757f631"
  instance_type = "t2.micro"

depends_on = [aws_s3_bucket.example]
}

350
Q

How do you save the execution plan?

A

terraform plan -out=tfplan

you can use that file with apply
terraform apply tfplan

351
Q

You have started writing terraform configuration and you are using some sample configuration as a basis. How do you copy the example configuration into your working directory?

A

terraform init -from-module=MODULE-SOURCE

https://www.terraform.io/docs/commands/init.html#copy-a-source-module

352
Q

What is the flag you should use with the terraform plan to get detailed on the exit codes?

A

terraform plan -detailed-exitcode

Return a detailed exit code when the command exits. When provided, this argument changes the exit codes and their meanings to provide more granular
information about what the resulting plan contains:

  • 0 = Succeeded with empty diff (no changes)
  • 1 = Error
  • 2 = Succeeded with non-empty diff (changes present)
353
Q

How do you target only specific resources when you run a terraform plan?

A

-target=resource - A Resource Address to target. This flag can be used multiple times. See below for more information.

354
Q

How do you update the state prior to checking differences when you run a terraform plan?

A

terraform plan -refresh=true

355
Q

The behavior of any terraform destroy command can be previewed at any time with an equivalent “terraform plan -destroy” command.
Is this true?

A

True

356
Q

You have the following file and created two resources docker_image and docker_container with the command terraform apply and you go to the terminal and delete the container with the command docker rm. You come back to your configuration and run the command again. Does terraform recreates the resource?

A

resource “docker_image” “nginx” {
name = “nginx:latest”
keep_locally = false
}

resource "docker_container" "nginx" {
    image = docker_image.nginx.latest
    name = "nginxtutorial"
    ports {
        internal = 80
        external = 8080
    }
    upload {
        source = "${abspath(path.root)}/files/index.html"
        file = "/usr/share/nginx/html/index.html"
    }
}

Yes. Terraform creates the resource again since the execution plan says two resources and the terraform always maintains the desired state

357
Q

You created a VM instance on AWS cloud provider with the terraform configuration and you log in AWS console and removed the instance. What does the next apply do?

A

It creates the instance again

358
Q

You have the following file and created two resources:

  • docker_image
  • docker_container

W/the command
“terraform plan”

You go to the terminal and delete the container with the command:
“docker rm”

You come back to your configuration and run
“terraform plan”

What is the output of the command plan?

A

resource “docker_image” “nginx” {
name = “nginx:latest”
keep_locally = false
}

resource "docker_container" "nginx" {
    image = docker_image.nginx.latest
    name = "nginxtutorial"
    ports {
        internal = 80
        external = 8080
    }
    upload {
        source = "${abspath(path.root)}/files/index.html"
        file = "/usr/share/nginx/html/index.html"
    }
}
Terraform will perform the following actions:
# docker_container.nginx will be created
Plan: 1 to add, 0 to change, 0 to destroy.
359
Q

What are Backends?

A

A “backend” in Terraform determines how the state is loaded and how an operation such as apply is executed. This abstraction enables non-local file state storage, remote execution, etc.
By default, Terraform uses the “local” backend, which is the normal behavior of Terraform

360
Q

What is local Backend?

A

The local backend stores state on the local filesystem, locks that state using system APIs, and performs operations locally.

// Example
terraform {
  backend "local" {
    path = "relative/path/to/terraform.tfstate"
  }
}
361
Q

What is the default path for the local backend?

A

This defaults to “terraform.tfstate” relative to the root module by default.

362
Q

What is State Locking?

A

If supported by your backend, Terraform will lock your state for all operations that could write state. This prevents others from acquiring the lock and potentially corrupting your state.
State locking happens automatically on all operations that could write state. You won’t see any message that it is happening. If state locking fails, Terraform will not continue.

363
Q

Does Terraform continue if state locking fails?

A

No.

If state locking fails, Terraform will not continue.

364
Q

Can you disable state locking?

A

Yes.

You can disable state locking for most commands with the -lock flag but it is not recommended.

365
Q

What are the types of Backend?

  • Remote-backend
  • Enhanced
  • Local-backend
  • Standard
A
  • Standard
  • Enhanced

Backend Types
Terraform’s backends are divided into two main types, according to how they handle state and operations:

Enhanced backends can both store state and perform operations. There are only two enhanced backends: local and remote.
Standard backends only store state, and rely on the local backend for performing operations.

366
Q

What are remote Backends?

A

Remote backends allow Terraform to use a “shared storage space” for “state data”, so any member of your team can use Terraform to manage the same infrastructure.

367
Q

What is the benefit of using remote backend?

A

Remote state storage:

  • Makes collaboration easier
  • State and secret information off your local disk.
  • “loaded only in memory”
368
Q

If you want to switch from using remote backend to local backend. What should you do?

A

If you want to move back to local state, you can

  • “remove the backend configuration block from your configuration”
  • run terraform init again.

Terraform will once again ask if you want to migrate your state back to local.

369
Q

What does the command refresh do?

A

The “terraform refresh” command is used to reconcile the state Terraform knows about (via its state file) with the real-world infrastructure.

This can be used to detect any “drift” from the last-known state, and to update the state file.

370
Q

Does the command refresh modify the infrastructure?

A

No:
The command “terraform refresh” does not modify infrastructure but it does modify the state file.
If the state is changed, this may cause changes to occur during the next plan or apply.

371
Q

How do you backup the state to the remote backend?

A
  1. When configuring a backend for the first time (moving from no defined backend to explicitly configuring one), Terraform will give you the option to migrate your state to the new backend. This lets you adopt backends without losing any existing state.
  2. To be extra careful, we always recommend manually backing up your state as well. You can do this by simply copying your terraform.tfstate file to another location.
372
Q

What is a partial configuration in terms of configuring Backends?

A

You do not need to specify every required argument in the backend configuration.

Omitting certain arguments may be desirable to avoid storing secrets, such as access keys, within the main configuration.

“When some or all of the arguments are omitted, we call this a “partial” configuration.”

373
Q

What are the ways to provide remaining arguments when using partial configuration?

A

“Interactively:” Terraform will interactively ask you for the required values unless interactive input is disabled. Terraform will not prompt for optional values.

“File:” A configuration file may be specified via the init command line. To specify a file, use the “-backend-config=PATH” option when running terraform init. If the file contains secrets it may be kept in a secure data store, such as Vault, in which case it must be downloaded to the local disk before running Terraform.

“Command-line key/value pairs:” Key/value pairs can be specified via the init command line. Note that many shells retain command-line flags in a history file, so this isn’t recommended for secrets. To specify a single key/value pair, use the -backend-config=”KEY=VALUE” option when running terraform init.
https://www.terraform.io/docs/backends/config.html

374
Q

What is the basic requirement when using partial configuration?

A

When using partial configuration, Terraform requires at a minimum that an “empty backend” configuration is specified in one of the root Terraform configuration files, to specify the backend type

// Example
terraform {
  backend "consul" {}
}
375
Q

Give an example of passing partial configuration with Command-line Key/Value pairs?

A

terraform init \

- backend-config="address=demo.consul.io" \
- backend-config="path=example_app/terraform_state" \
- backend-config="scheme=https"
376
Q

How to unconfigure a backend?

A

If you no longer want to use any backend, you can simply remove the configuration from the file. Terraform will detect this like any other change and prompt you to reinitialize.

As part of the reinitialization, Terraform will ask if you’d like to migrate your state back down to a normal local state.

Once this is complete then Terraform is back to behaving as it does by default.

377
Q

How do you encrypt sensitive data in the state?

A

Terraform Cloud always encrypts 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. This can be used to control access and track activity.

Terraform Enterprise also supports detailed audit logging.
The S3 backend supports encryption at rest when the encrypt option is enabled.
IAM policies and logging can be used to identify any invalid access.
Requests for the state go over a TLS connection.

378
Q

Backends are completely optional. Is this true?

A

Backends are completely optional. You can successfully use Terraform without ever having to learn or use backends. However, they do solve pain points that afflict teams at a certain scale. If you’re an individual, you can likely get away with never using backends.

379
Q

What are the benefits of Backends?

A

“Working in a team:” Backends can store their state remotely and protect that state with locks to prevent corruption. Some backends such as Terraform Cloud even automatically store a history of all state revisions.

“Keeping sensitive information off disk:” State is retrieved from backends on demand and only stored in memory. If you’re using a backend such as Amazon S3, the only location the state ever is persisted is in S3.

“Remote operations:” For larger infrastructures or certain changes, terraform apply can take a long, long time. Some backends support remote operations which enable the operation to execute remotely. You can then turn off your computer and your operation will still complete. Paired with remote state storage and locking above, this also helps in team environments.

380
Q

Why should you be very careful with the Force unlocking the state?

A

Terraform has a force-unlock command to manually unlock the state if unlocking failed.
Be very careful with this command. If you unlock the state when someone else is holding the lock it could cause multiple writers. Force unlock should only be used to unlock your own lock in the situation where automatic unlocking failed.
To protect you, the force-unlock command requires a unique lock ID. Terraform will output this lock ID if unlocking fails. This lock ID acts as a nonce, ensuring that locks and unlocks target the correct lock.

381
Q

You should only use force unlock command when automatic unlocking fails. Is this true?

A

True

382
Q

How do you define a variable?

A

variable “region” {
default = “us-east-1”
}
This defines the region variable within your Terraform configuration.

383
Q

How do you access the variable in the configuration?

A
// accessing a variable
provider "aws" {
  region = var.region
}
384
Q

How many ways you can assign variables in the configuration?

A
(1) "Command-line flags"
terraform apply -var 'region=us-east-1'
From a file
To persist variable values, create a file and assign variables within this file. Create a file named terraform.tfvars with the following contents:
region = "us-east-1"
terraform apply \
  -var-file="secret.tfvars" \
  -var-file="production.tfvars"

(2) “From environment varibles”
Terraform will read environment variables in the form of TF_VAR_name to find the value for a variable. For example, the TF_VAR_region variable can be set in the shell to set the region variable in Terraform.

(3) “UI input”
If you execute terraform apply with any variable unspecified, Terraform will ask you to input the values “interactively”. These values are not saved, but this provides a convenient workflow when getting started with Terraform. UI input is not recommended for everyday use of Terraform.

385
Q

Do environment variables support List and map types?

A

No

Environment variables can only populate “string-type variables”.

List and map type variables must be populated via one of the other mechanisms.

386
Q

How do you provision infrastructure in a staging environment or a production environment using the same Terraform configuration?

A
You can use different varible files with the same configuration:
// Example
// For development
terraform apply -var-file="dev.tfvars"
// For test
terraform apply -var-file="test.tfvars"
387
Q

How do you assign default values to variables?

A

If no value is assigned to a variable via any of these methods and the variable has a default key in its declaration, that value will be used for the variable.

variable “region” {
default = “us-east-1”
}

388
Q

What are the data types for the variables?

A
string
number
bool
list()
set()
map()
object({ = , ... })
tuple([, ...])
389
Q

Give an example of data type List variables?

A
Lists are defined either explicitly or implicitly.
variable "availability_zone_names" {
  type    = list(string)
  default = ["us-west-1a"]
}
390
Q

Give an example of data type Map variables?

A
variable "region" {}
variable "amis" {
  type = map(string)
}
amis = {
  "us-east-1" = "ami-abc123"
  "us-west-2" = "ami-def456"
}
// accessing
resource "aws_instance" "example" {
  ami           = var.amis[var.region]
  instance_type = "t2.micro"
}
391
Q

What is the Variable Definition Precedence?

A

The above mechanisms for setting variables can be used together in any combination. If the same variable is assigned multiple values, Terraform uses the last value it finds, overriding any previous values. Note that the same variable cannot be assigned multiple values within a single source.
Terraform loads variables in the following order, with later sources taking precedence over earlier ones:
* Environment variables
* The terraform.tfvars file, if present.
* The terraform.tfvars.json file, if present.
* Any *.auto.tfvars or *.auto.tfvars.json files, processed in lexical order of their filenames.
* Any -var and -var-file options on the command line, in the order they are provided. (This includes variables set by a Terraform Cloud workspace.)

392
Q

What are the output variables?

A

output variables as a way to organize data to be easily queried and shown back to the Terraform user.

Outputs are a way to tell Terraform what data is important.

This data is outputted when apply is called

can be queried using the terraform output command.

393
Q

Hoe do you define an output variable?

A

output “ip” {
value = aws_eip.ip.public_ip
}
Multiple output blocks can be defined to specify multiple output variables.

394
Q

How do you view outputs and queries them?

A

You will see the output when you run the following command

terraform apply

You can query the output with the following command

terraform output ip

395
Q

What are the dynamic blocks?

A

some resource types include repeatable nested blocks in their arguments, which do not accept expressions
You can dynamically construct repeatable nested blocks like setting using a special dynamic block type, which is supported inside resource, data, provider, and provisioner blocks:

A dynamic block acts much like a for expression but produces nested blocks instead of a complex typed value. It “iterates over a given complex value, and generates a nested block for each element of that complex value.”

https://www.terraform.io/docs/configuration/expressions.html#dynamic-blocks

resource “aws_elastic_beanstalk_environment” “tfenvtest” {
name = “tf-test-name”
application = “${aws_elastic_beanstalk_application.tftest.name}”
solution_stack_name = “64bit Amazon Linux 2018.03 v2.11.4 running Go 1.12.6”

  dynamic "setting" {
    for_each = var.settings
    content {
      namespace = setting.value["namespace"]
      name = setting.value["name"]
      value = setting.value["value"]
    }
  }
}
396
Q

What are the best practices for dynamic blocks?

A

Overuse of dynamic blocks can make configuration hard to read and maintain, so we recommend using them only when you need to hide details in order to build a clean user interface for a re-usable module.
Always write nested blocks out literally where possible.

397
Q

What are the Built-in Functions?

A

The Terraform language includes a number of built-in functions that you can call from within expressions to transform and combine values.
max(5, 12, 9)

398
Q

Does Terraform language support user-defined functions?

A

No
The Terraform language does not support user-defined functions, and so only the functions built into the language are available for use.

399
Q

What is the built-in function to change string to a number?

A

parseint parses the given string as a representation of an integer in the specified base and returns the resulting number. The base must be between 2 and 62 inclusive.
> parseint(“100”, 10)
100
More Number Functions here
https://www.terraform.io/docs/configuration/functions/abs.html

400
Q

What is the built-in function to evaluates a given expression and returns a boolean whether the expression produced a result without any errors?

A

can
condition = can(formatdate(“”, var.timestamp))
https://www.terraform.io/docs/configuration/functions/can.html

401
Q

What is the built-in function to evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors?

A
try
locals {
  example = try(
    [tostring(var.example)],
    tolist(var.example),
  )
}
402
Q

What is Resource Address?

A
A Resource Address is a string that references a specific resource in a larger infrastructure. An address is made up of two parts:
[module path][resource spec]
403
Q

What is the Module path?

A
A module path addresses a module within the tree of modules. It takes the form:
module.A.module.B.module.C...
Multiple modules in a path indicate nesting. If a module path is specified without a resource spec, the address applies to every resource within the module. If the module path is omitted, this addresses the root module.
404
Q

What is the Resource spec?

A

A resource spec addresses a specific resource in the config. It takes the form:
resource_type.resource_name[resource index]
* resource_type - Type of the resource being addressed.
* resource_name - User-defined name of the resource.
* [resource index] - an optional index into a resource with multiple instances, surrounded by square brace characters ([ and ]).
// Examples
resource “aws_instance” “web” {
# …
count = 4
}
aws_instance.web[3] // Refers to only last instance
aws_instance.web // Refers to all four “web” instances.
resource “aws_instance” “web” {
# …
for_each = {
“terraform”: “value1”,
“resource”: “value2”,
“indexing”: “value3”,
“example”: “value4”,
}
}
aws_instance.web[“example”] // Refers to only the “example” instance in the config.

405
Q

What are complex types and what are the collection types Terraform supports?

A
A complex type is a type that groups multiple values into a single value.
There are two categories of complex types: 
collection types (for grouping similar values)
* list(...): a sequence of values identified by consecutive whole numbers starting with zero.
* map(...): a collection of values where each is identified by a string label.
* set(...): a collection of unique values that do not have any secondary identifiers or ordering.
structural types (for grouping potentially dissimilar values).
* object(...): a collection of named attributes that each have their own type.
* tuple(...): a sequence of elements identified by consecutive whole numbers starting with zero, where each element has its own type.
406
Q

What are the named values available and how do we refer to?

A

Terraform makes several kinds of named values available. Each of these names is an expression that references the associated value; you can use them as standalone expressions, or combine them with other expressions to compute new values.

  • . is an object representing a managed resource of the given type and name. The attributes of the resource can be accessed using dot or square bracket notation.
  • var. is the value of the input variable of the given name.
  • local. is the value of the local value of the given name.
  • module.. is the value of the specified output value from a child module called by the current module.
  • data.. is an object representing a data resource of the given data source type and name. If the resource has the count argument set, the value is a list of objects representing its instances. If the resource has the for_each argument set, the value is a map of objects representing its instances.
  • path.module is the filesystem path of the module where the expression is placed.
  • path.root is the filesystem path of the root module of the configuration.
  • path.cwd is the filesystem path of the current working directory. In normal use of Terraform this is the same as path.root, but some advanced uses of Terraform run it from a directory other than the root module directory, causing these paths to be different.
  • terraform.workspace is the name of the currently selected workspace.
407
Q

What is the built-in function that reads the contents of a file at the given path and returns them as a base64-encoded string?

A

filebase64(path)

https://www.terraform.io/docs/configuration/functions/filebase64.html

408
Q

What is the built-in function that converts a timestamp into a different time format?

A

formatdate(spec, timestamp)

https://www.terraform.io/docs/configuration/functions/formatdate.html

409
Q

What is the built-in function encodes a given value to a string using JSON syntax?

A

jsonencode({“hello”=”world”})

https://www.terraform.io/docs/configuration/functions/jsonencode.html

410
Q

What is the built-in function that calculates a full host IP address for a given host number within a given IP network address prefix?

A

> cidrhost(“10.12.127.0/20”, 16)

  1. 12.112.16
    https: //www.terraform.io/docs/configuration/functions/cidrhost.html
411
Q

What is Sentinel?

A

Sentinel is an embedded policy-as-code framework integrated with the HashiCorp Enterprise products. It enables fine-grained, logic-based policy decisions, and can be extended to use information from external sources.

412
Q

What is the benefit of Sentinel?

A
  • Codifying policy
    removes the need for ticketing queues
    , without sacrificing enforcement.
    One of the other benefits of Sentinel is that it also has a
    fullull testing framework.
    Avoiding a ticketing workflow allows organizations to provide more self-service capabilities and end-to-end automation, minimizing the friction for developers and operators.
    https://www.hashicorp.com/blog/why-policy-as-code/
413
Q

What is the Private Module Registry?

A

Terraform Cloud’s private module registry helps you share Terraform modules across your organization. It includes support for module versioning, a searchable and filterable list of available modules, and a configuration designer to help you build new workspaces faster.

414
Q

What is the difference between public and private module registries when defined source?

A

The public registry:
3-part // format

private modules:
4-part /// format

// example
module "vpc" {
  source  = "app.terraform.io/example_corp/vpc/aws"
  version = "1.0.4"
}
415
Q

Where is the Terraform Module Registry available at?

A

https://registry.terraform.io/

416
Q

What is a workspace?

A

A workspace contains everything Terraform needs to manage a given collection of infrastructure, and separate workspaces function like completely separate working directories.

417
Q

What are the benefits of workspaces?

A

https://www.hashicorp.com/resources/terraform-enterprise-understanding-workspaces-and-modules/

418
Q

You are configuring a remote backend in the terraform cloud. You didn’t create an organization before you do terraform init. Does it work?

A

While the organization defined in the backend stanza must already exist,

419
Q

You are configuring a remote backend in the terraform cloud. You didn’t create a workspace before you do terraform init. Does it work?

A

Terraform Cloud will create it if necessary. If you opt to use a workspace that already exists, the workspace must not have any existing states.

420
Q

Terraform workspaces when you are working with CLI and Terraform workspaces in the Terraform cloud. Is this correct?

A

If you are familiar with running Terraform using the CLI, you may have used Terraform workspaces. Terraform Cloud workspaces behave differently than Terraform CLI workspaces. Terraform CLI workspaces allow multiple state files to exist within a single directory, enabling you to use one configuration for multiple environments. Terraform Cloud workspaces contain everything needed to manage a given set of infrastructure and function like separate working directories.

421
Q

How do you authenticate the CLI with the terraform cloud?

A

Newer Versions:
1. terraform login
2. it will open the terraform cloud and generate the token
3. paste that token back in the CLI
https://learn.hashicorp.com/terraform/tfc/tfc_login
Older versions:
keep the following token in the CLI configuration file
credentials “app.terraform.io” {
token = “xxxxxx.atlasv1.zzzzzzzzzzzzz”
}
https://www.terraform.io/docs/commands/cli-config.html#credentials

422
Q

You are building infrastructure on your local machine and you changed your backend to remote backend with the Terraform cloud. What should you do to migrate the state to the remote backend?

A

terraform init
Once you have authenticated the remote backend, you’re ready to migrate your local state file to Terraform Cloud. To begin the migration, reinitialize. This causes Terraform to recognize your changed backend configuration.
During reinitialization, Terraform presents a prompt saying that it will copy the state file to the new backend. Enter “yes” and Terraform will migrate the state from your local machine to Terraform Cloud.
https://learn.hashicorp.com/terraform/tfc/tfc_migration#migrate-the-state-file

423
Q

How do you configure remote backend with the terraform cloud?

A
You need to configure in the terraform block
terraform {
  backend "remote" {
    hostname      = "app.terraform.io"
    organization  = ""
    workspaces {
      name = "state-migration"
    }
  }
}
424
Q

What are Run Triggers?

A

Terraform Cloud’s run triggers allow you to link workspaces so that a successful apply in a source workspace will queue a run in the workspace linked to it with a run trigger.

For example, adding new subnets to your network configuration could trigger an update to your application configuration to rebalance servers across the new subnets.

425
Q

What is the benefit of Run Triggers?

A

When managing complex infrastructure with Terraform Cloud, organizing your configuration into different workspaces helps you to better manage and design your infrastructure.

Configuring run triggers between workspaces allows you to set up infrastructure pipelines as part of your overall deployment strategy.

426
Q

What are the available permissions that terraform clouds can have?

A

Terraform Cloud teams can have:

  • read
  • plan
  • write
  • admin

Permissions on individual workspaces

427
Q

Who can grant permissions on the workspaces?

A

“Organization owners”

grant permissions by grouping users into teams and giving those teams privileges based on their need for access to individual workspaces.

428
Q

Which plan do you need to manage teams on Terraform cloud?

A

Team Plan

429
Q

How can you add users to an organization?

A

You can add users to an organization by inviting them using their email addresses.
Even if your team member has not signed up for Terraform Cloud yet, they can still accept the invitation and create a new account.

430
Q

The Terraform Cloud Team plan charges you on a per-user basis. Is this true?

A

Yes. The Terraform Cloud Team plan is charged on a per-user basis so adding new users to your organization incurs cost.

431
Q

Which one of the following answers is NOT a key benefit of Terraform Cloud?

  • Remote state management
  • Private Terraform module registry
  • A built-in version control similar GitHub
  • Remote Terraform execution
  • Cloud cost estimation
A
  • A built-in version control similar to GitHub

Terraform does not have version control built-in.

432
Q

Which of the following statements is NOT accurate about the difference between open-source Terraform workspaces and Terraform Cloud workspaces?

  • State is stored in Terraform Cloud workspaces
  • Terraform Cloud workspaces store the Terraform configuration in a linked version control repository
  • State can be stored on disk or in a remote backend for open-source Terraform workspaces.
  • Variable values are stored in Terraform local workspaces in .tfvars files or in a shell environment
  • Open-source Terraform workspaces can automatically back up your configuration to Terraform Cloud.
A

Open-source Terraform workspaces can automatically back up your configuration to Terraform Cloud.

Terraform does not automatically back up your configuration to Terraform Cloud. If you are running Terraform locally, it stores the configuration in the designated directory on your machine.

433
Q

What is the Terraform public registry?

A

A repository of publicly available Terraform:

1) . providers
2) . modules

434
Q

What does the Terraform Vault provider offer Terraform users?

A
  • Provides short-lived, temporary credentials for users with only the permissions needed for infrastructure creation.
  • Allows you to store sensitive data securely that can be used for your Terraform configurations.
  • A secure place to manage access to the secrets to your Terraform configurations, in addition to integrating with other popular cloud vendors.
435
Q

What is the purpose of Terraform Cloud?

A
  • It helps teams use Terraform together.

- Easy access to shared state and secret data

436
Q

What does the Terraform Registry consist of?

A
  • Publicly available Terraform providers

- Publicly available modules

437
Q

How can HashiCorp Vault help secure your Terraform deployments?

A
  • It can store your long-lived credentials in a secure way and dynamically inject short-lived, temporary keys to Terraform at deployment
438
Q

Which of the following best describes Terraform providers?

A

A plugin that enables Terraform to interface with the API layer of various cloud platforms and environments

439
Q

How can Terraform input variables be defined?

A
  • They can be included in the command-line options.
  • They can be predetermined in a file
  • They can be pulled down from Terraform Cloud and referenced in your code
440
Q

True or False? Terraform provisioners help bootstrap custom commands onto the resources being deployed via Terraform.

A

True
terraform provisioners can help execute custom scripts and commands on resources. The best practice is to avoid using them if a built-in mechanism is provided by the resource API itself.

441
Q

What is the default name of the file where Terraform state is stored when working locally?

A

terraform.tfstate

442
Q

Which are the uses of the Terraform output variables?

A
  • A child module can use outputs to expose a subset of its resource attributes to a parent module.
  • A root module can use outputs to print certain values in the CLI output after running terraform apply
  • When using remote state, root module outputs can be accessed by other configurations via a terraform_remote_state
443
Q

How can Terraform Providers be sourced in Terraform?

  • By default, Terraform looks for providers in the Terraform provider registry.
  • You can reference providers from an internal registry in your Terraform code
  • Terraform can use a providers list that you can set up in a file within your working directory
  • You can reference providers locally in your Terraform Configuration
A
  • By default, Terraform looks for providers in the Terraform provider registry.
  • You can reference providers from an internal registry in your Terraform code
  • You can reference providers locally in your Terraform Configuration
444
Q

Given the following snippet of Terraform code:

variable "training" {
  type = object({
    name = string
    age = number
  })
  default = {
    name = "Ryan"
    age = 36
  }
}
Which of the following type constraints can the variable configured in the code be classified as?
  • Structural
  • Collection
  • Primitive
  • Tuple
A

Structural

A structural variable type allows multiple values of various primitive types to be grouped together as a single value. In this case, the variable training has 2 separate types of values within it, namely a string and a number.

445
Q

The dynamic blocks feature in Terraform CANNOT be used with which of the following types of resources?

A

lifecycle blocks

Dynamic blocks CANNOT be used with lifecycle blocks, as Terraform must process this type of block before it is safe to evaluate expressions.

446
Q

True or False? Collection variable types allow multiple values of one primitive type variable to be grouped together.

A

True

Per the definition, a collection type allows multiple values of one other type to be grouped together as a single value

447
Q

True or False? In Terraform, you can create your own user-defined functions.

A

Terraform comes pre-packaged with a number of built-in functions. Users cannot create their own functions like in a programming language

448
Q

What is Infrastructure as Code (IaC)?

A

A method of writing human-readable code to deploy resources in the cloud and elsewhere.

IaC is basically code that deploys your infrastructure resources onto various platforms instead of managing them manually through a user interface.

449
Q

What are some benefits of using Terraform as an IaC tool?

  • Automate software-defined networks.
  • Support only public cloud vendors.
  • Interacts and takes care of the communication with control-layer APIs with ease.
  • Tracks state of each resource deployed
A
  • Automate software-defined networks.
  • Interacts and takes care of the communication with control-layer APIs with ease.
  • Tracks state of each resource deployed
450
Q

What does the terraform plan command do?

A

Presents a plan of the actions that will be taken during deployment for review prior to execution.

The terraform plan command goes through the code and creates a plan of execution on which the apply command acts.

451
Q

True or False? The terraform init command does not help set up the backend for storing state files.

A

False

The terraform init does in fact help configure and set up the backend which will store the state file.

452
Q

Where in Terraform code can you configure where the state file is stored?

A

In the terraform block, using the backend attribute.

453
Q

What benefits does storing Terraform state remotely offer?

A

It provides granular access, integrity, security, availability, collaboration.

454
Q

What does the terraform state mechanism do?

A

It maps real-world resources to Terraform configuration/code.

It’s basically a map between real-world resource IDs and configurations to logical resources in your Terraform code.

455
Q

Which command would you use to see all the resources that have been created and are being tracked by the Terraform state file?

A

The inclusion of list with the terraform state command will list all of the resources in the Terraform state.

456
Q

variable “cloud_users” {
default = “andrew:ken:faraz:mutsumi:peter:steve:braja”

Using this variable and the count meta-argument, create IAM users for all developers.
Convert this variable from a string to a list

A

resource “aws_iam_user” “cloud” {
name = split(“:”,var.cloud_users)[count.index]
count = length(split(“:”,var.cloud_users))

}

457
Q

What is the name of the IAM User that is created at the Index 6, of the IAM User at address aws_iam_user.cloud ?

A

echo ‘aws_iam_user.cloud[6].name’ | terraform console

458
Q

Locate the index of the element called oni in the variable called sf.

variable "sf" {
  type = list
  default = [
    "ryu",
    "ken",
    "akuma",
    "seth",
    "zangief",
    "poison",
    "gen",
    "oni",
    "thawk",
    "fang",
    "rashid",
    "birdie",
    "sagat",
    "bison",
    "cammy",
    "chun-li",
    "balrog",
    "cody",
    "rolento",
    "ibuki"

]

A

Use terraform console and check index(var.sf,”oni”) OR to use a one liner:
echo “index(var.sf,"oni")” | terraform console

459
Q

What type is the variable called media?

variable "media" {
  type = set(string)
  default = [
    "/media/tails.jpg",
    "/media/eggman.jpg",
    "/media/ultrasonic.jpg",
    "/media/knuckles.jpg",
    "/media/shadow.jpg",
      ]

}

A

set(string)

460
Q

Create an EC2 Instance with the resource name mario_servers.

Use the following specifications:
AMI: Use variable called ami.

Tags: Create a tag with key Name and value set to the variable called name.

Instance_type: Use a conditional expression so that - If the instance is created with a tag Name = “tiny”, it should use the variable called small else the variable called large.

A

resource “aws_instance” “mario_servers” {
ami = var.ami
instance_type = var.name == “tiny” ? var.small : var.large
tags = {
Name = var.name

 }

}

461
Q

In regards to deploying resources in multi-cloud environments, what are some of the benefits of using Terraform rather than a provider’s native tooling? (select three)

  • Terraform can mange cross-cloud dependencies
  • Terraform simplifies management and orchestration, helping operators build large-scale, multi-cloud infrastructure
  • Terraform is not cloud-agnostic and can be used to deploy resources across a single public cloud
  • Terraform can help businesses deploy applications on multiple clouds and on-premises infrastructure
A
  • Terraform can mange cross-cloud dependencies- Terraform can mange cross-cloud dependencies
  • Terraform simplifies management and orchestration, helping operators build large-scale, multi-cloud infrastructure
  • Terraform can help businesses deploy applications on multiple clouds and on-premises infrastructure
462
Q

From the answers below, select the disadvantages of using Infrastructure as Code. (select four)

  • Provide reusable modules for easy sharing and collaboration
  • Safely test modifications using a “dry run” before applying any actual changes
  • Easily change and update existing infrastructure
  • Provide a codified workflow to develop customer-facing applications
  • Easily integrate with application workflows (GitLab Actions, Azure DevOps, CI/CD tools)
A
  • Provide reusable modules for easy sharing and collaboration
  • Safely test modifications using a “dry run” before applying any actual changes
  • Easily change and update existing infrastructure
  • Easily integrate with application workflows (GitLab Actions, Azure DevOps, CI/CD tools)
463
Q

What happens when a “terraform apply” command is executed?

  • creates the execution plan for the deployment of resources
  • the backend is initialized and the working directory is prepped
  • applies the change required in the target infrastructure in order to reach the desired configuration
  • reconciles the state Terraform knows about with the real-world infrastructure
A
  • applies the change required in the target infrastructure in order to reach the desired configuration
464
Q

Select the feature below that best completes the sentence:

The following list represents the different types of __________ available in Terraform.

max
min
join
replace
list
length
range
  • functions
  • named values
  • backends
  • data sources
A

functions

465
Q

Using multi-cloud and provider-agnostic tools provides which of the following benefits? (select two)

  • operations teams only need to learn and manage a single tool to manage infrastructure, regardless of where the infrastructure is deployed
  • can be used across major cloud providers and VM hypervisors
  • increased risk due to all infrastructure relying on a single tool for management
  • slower provisioning speed allows the operations team to catch mistakes before they are applied
A
  • operations teams only need to learn and manage a single tool to manage infrastructure, regardless of where the infrastructure is deployed
  • can be used across major cloud providers and VM hypervisors

Using a tool like Terraform can be advantageous for organizations deploying workloads across multiple public and private cloud environments. Operations teams only need to learn a single tool, a single language, and can use the same tooling to enable a DevOps-like experience and workflows.

https://www.terraform.io/intro/use-cases.html#multi-cloud-deployment

466
Q

When using parent/child modules to deploy infrastructure, how would you export a value from one module to import into another module.

For example, a module dynamically deploys an application instance or virtual machine, and you need the IP address in another module to configure a related DNS record in order to reach the newly deployed application.

  • preconfigure the IP address as a parameter in the DNS module
  • configure an output value in the application module in order to use that value for the DNS module
  • export the value using terraform export and input the value using terraform input
  • configure the pertinent provider’s configuration with a list of possible IP addresses to use
A
  • configure an output value in the application module in order to use that value for the DNS module

Output values are like the return values of a Terraform module and have several uses such as a child module using those outputs to expose a subset of its resource attributes to a parent module.

https://www.terraform.io/docs/configuration/expressions.html#references-to-named-values

467
Q

What are some of the problems of how infrastructure was traditionally managed before Infrastructure as Code? (select three)

  • Traditional deployment methods are not able to meet the demands of the modern business where resources tend to live days to weeks, rather than months to years
  • Pointing and clicking in a management console is a scalable approach and reduces human error as businesses are moving to a multi-cloud deployment model
  • Requests for infrastructure or hardware required a ticket, increasing the time required to deploy applications
  • Traditionally managed infrastructure can’t keep up with the cyclic or elastic applications
A
  • Traditional deployment methods are not able to meet the demands of the modern business where resources tend to live days to weeks, rather than months to years
  • Requests for infrastructure or hardware required a ticket, increasing the time required to deploy applications
  • Traditionally managed infrastructure can’t keep up with the cyclic or elastic applications

Explanation
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.

https://www.terraform.io/intro/index.html#infrastructure-as-code

468
Q

HashiCorp offers multiple versions of Terraform, including Terraform open-source, Terraform Cloud, and Terraform Enterprise. Which of the following Terraform features are “only” available in the Enterprise edition? (select one)

  • Private Network Connectivity
  • Private Module Registry
  • Clustering
  • Audit Logs
  • Locally hosted installation
  • SAML/SSO
A

Clustering

  • Clustering is the ONLY answer that is available ONLY in Terraform Enterprise. You can’t cluster Terraform open-source, and the other options are hosted solutions. This makes clustering the only correct answer. Note that Clustering was available for Enterprise for a while, then HashiCorp removed it. As of January 15, 2021, it’s back and you can read more about it at this link.
469
Q

Which database has its own provider?

  • MySQL
  • Mongo
  • Dynamo
  • influx
A

MySQL

470
Q

Which all of below are supported backend types in terraform?

  • consul
  • gcs
  • manta
  • bitbucket
A
  • consul
  • gcs
  • manta
471
Q

You are new to terraform and are asked to find out which providers you are using?

  • terraform state
  • terraform apply
  • terraform providers
  • terraform plan
A

terraform providers

The terraform providers command shows information about the provider requirements of the configuration in the current working directory, as an aid to understanding where each requirement was detected from.

472
Q

What is a null_resource?

A

If you need to run provisioners that aren’t directly associated with a specific resource, you can associate them with a null_resource.

Instances of null_resource are treated like normal resources, but they don’t do anything. Like with any other resource, you can configure provisioners and connection details on a null_resource. You can also use its triggers argument and any meta-arguments to control exactly where in the dependency graph its provisioners will run.

Example usage
resource “aws_instance” “cluster” {
count = 3

  # ...
}
resource "null_resource" "cluster" {
  # Changes to any instance of the cluster requires re-provisioning
  triggers = {
    cluster_instance_ids = "${join(",", aws_instance.cluster.*.id)}"
  }
  # Bootstrap script can run on any instance of the cluster
  # So we just choose the first in this case
  connection {
    host = "${element(aws_instance.cluster.*.public_ip, 0)}"
  }
  provisioner "remote-exec" {
    # Bootstrap script called with private_ip of each node in the cluster
    inline = [
      "bootstrap-cluster.sh ${join(" ", aws_instance.cluster.*.private_ip)}",
    ]
  }
}
473
Q

What features are exclusive to Terraform Enterprise from below. (select three)

  • Saml/sso
  • Audit logging
  • Remote State
  • Servicenow integration
  • Private module registry
A
  • SAML/SSO
  • Audit Logging
  • ServiceNow Integration
474
Q

Not all of the backend types support locking?
Choose from below which support locking?

  • artifactory
  • consul
  • DynamoDB
  • azurerm
A
  • consul
  • DynamoDB
  • azurerm
475
Q

A new intern has joined your Team, how to just check whether the terraform code he has written is in canonical format and style without modifying terraform configuration files?

  • terraform fmt
  • terraform fmt -check
  • terraform fmt -diff
  • terraform fmt -list=false
A

terraform fmt -check

This command checks if the input is formatted. Exit status will be 0 if all input is properly formatted and non-zero otherwise.

476
Q

A newbie is allocated to the project, he has been given the task of configuring applications on servers. All the servers are created using terraform. While doing configuration he succeeds in all
servers, but one server is messed due to application configuration, So he wants to destroy this server and launch a new one.

How can this be achieved using terraform?

A.terraform destroy -Target=resource_name.variable_name

B.terraform plan -target=resource_name.variable_name then terraform apply

C. terraform taint resource_name.variable_name then terraform apply

D. terraform state rm resource_name.variable_name then terraform apply

A

Explanation:

Answer: C

+ Option A is INCORRECT because this will destroy resources but will not recreate.

+ Option B is INCORRECT because this command will not destroy anything or recreate resources as it only plans what has to be changed.

+ Option C is CORRECT because taint manually marks a Terraform-managed resource as tainted, forcing it to be destroyed and recreated on the next apply.

+ Option D is INCORRECT because this option will destroy the resource but will not recreate it.

If we want to just recreate a resource that is managed by terraform then, we can use the taint command, this will mark the resource as tainted and will destroy and recreate a similar
resource in the next apply. Once taint is applied It only changes the state file. It marks the resource status as tainted.

« https///wwwterraformio/docs/commands/tainthtml

477
Q

What happens when terraform taint is applied to a resource?

A terraform will destroy the resource
B. terraform will modify the state file with resource status marked as tainted. v right
@ C.terraform will destroy and recreate a new resource with the same configuration. x wrong

D. terraform destroys and recreates all resources in the state file.

A

Explanation:

Answer:B

Option A is INCORRECT because taint will not destroy resources but marks the resource for recreation in the next apply.

Option B is CORRECT because taint marks the resource for recreation in the state file. It marks the status as tainted in the state file.

Option C is INCORRECT because taint command alone can’t destroy and recreate a file.

Option D is INCORRECT because taint only recreates a resource mentioned in the command. It will not recreate all resources in the state file.

The terraform taint command manually marks a Terraform-managed resource as tainted, forcing it to be destroyed and recreated on the next apply. it command is applied it only
marks the status as tainted in the state file. To recreate a resource terraform apply should be executed.

« https///wwwterraformio/docs/commands/tainthtml

478
Q

‘A user wants to rename the resource variable from web to webapp, how can this be achieved in terraform efficiently. New name should also get reflected in the configuration file?

resource “aws_instance” web” {

ami = amral23456789

instance_type =”t3.micro”
}

A. Manually change the varlable to webapp and then run terratorm apply

B. terratorm state mv aws_instance.web aws_instancewebapp

C.terraform state mv aws_instance.web aws_Instance.webapp and then run terraform apply

D.terraform state mv aws_instance.web aws_instance.webapp and changing variable name In configuration file

A

Explanation:
Answer:D
+ Option A Is INCORRECT because this will destroy the resource and then creates a new resource with variable name webapp
+ Option Bis INCORRECT because this will only change in state file, but will not get reflected in the configuration file
+ Option C is INCORRECT because this will change in the state file, but when terraform apply is applied it will recreate a resource with resource variable web
+ Option D is CORRECT this option will change in the state file and if we want the change to be applied in the configuration file then we need to manually do it.

The terraform state mv command is used to move items in a Terraform state. This command can move single resources, single instances of a resource, entire modules, and more. This command can also move items to a completely different state file, enabling efficient refactoring.

+ https//wwwterraformio/doos/eommands/state/mv.html

479
Q

A user Is referencing to child module, He wants to override one of the attributes in the child module. Below Is the following code of the child module. He wants to override the Instance type
from m5.micro to m6.small, so he passes it as an input variable from the root module. Will he succeed in doing that?

resource “aws_instance” “webapp” {
ami = “ami-labedfghi”
instance _type = “m5.micro”
}

True
False

A

True

If a value is already set in the child module, then it can be overwritten by the root module.

480
Q

Which among the following is not module source options?

A. Local Path
B. Terratorm registry
C. Bit bucket
D.HTTP URLS

E.BLOBstorage

A

nswer:E
+ Options A, 8, C and D are INCORRECT because these are valid source options for a module.
+ Option Eis CORRECT because we cannot use BLOB storage as module source option

The source argument in a module block tells Terraform where to find the source code for the desired child module.Terraform uses this during the module installation step of terraform

The module installer supports installation from a number of different source types, as listed below.

Local paths

Terraform Registry

GitHub

Bitbucket

Generic Git, Mercurial repositories

HTTP URLs

S3 buckets

GCS buckets

+ https//wnwterratormio/does/modiules/sourceshtmL

481
Q

Is it mandatory to specify the module version for the public registry? (defining/releasing a module without version)

True
False

A

Explanation:
Answer:B

Specifying module version is not mandatory for the public module. When using modules installed from a module registry, we recommend explicitly constraining the acceptable version

numbers to avoid unexpected or unwanted changes

https://www.terraform.io/docs/configuration/modules.html#module-versions

482
Q

Bob works for a company Fusion Corp. The internal IT team has downloaded and kept the plugins in the common path so that all team members use the same version of plugins. How can wi

configure terratorm to use these pre-downloaded plugins, instead of downloading new plugins.

A. terraform init plugin-dir=PATH
B. terraformn init plugin-path=PATH
C. terraform init -get-plugins=PATH
D. terraform init plugin-file=PATH

A

Explanation:

Answer: A
+ Option A is CORRECT plugin-dir option Skips plugin installation and loads plugins only from the specified directory.
+ Option Bis INCORRECT because plugin-path option is not present in nit command

+ Option C is INCORRECT because get-plugins accepts value a Boolean value. Skips plugin installation, Terraform will use plugins installed in the user plugins directory. and any
plugins already installed for the current working directory. Ifthe installed plugins aren’t sufficient for the configuration, init fal

+ Option Dis INCORRECT plugin-fil is not a valid option for init command,

~plugin-dir=PATH Skips plugin installation and loads plugins only from the specified directory. This ignores the user plugins directory and any plugins already installed in the current

working directory. To restore the default behavior after using this option, run init again and pass an empty string to -plugin-dir

https: //www.terraform.io/docs/commands/init.html#plugin-installation
https: //www.terraform.io/docs/commands/init.html

483
Q

Which of the following is true about third-party plugins? (SELECT TWO)

Third-party plugins also get downloaded automatically from terraform version 0.12

B. Third-party plugins (both providers and provisioners) can be manually installed into the user plugins directory based on OS type.

B. Third-party plugins should be installed only into the user plugins directory, no other directories are supported for the third-party plugin.

C. Third-party plugins should be installed only into the user plugins directory, no other directories are supported for third-party plugins.

D. Third-party plugins that are approved by HashiCorp are supported.

E.Plugins can be written only in the Go language.

A

Explanation:
Answers: B and E

+ Option A is INCORRECT third-party plugins should be manually downloaded.

+ Option B is CORRECT third-party plugins can be manually installed in the user’s plugin directory

+ Option C is INCORRECT third-party plugins can be manually installed in any directory but we need to specify its path using -plugin-cir=PATH option during initialization.

+ Option D is INCORRECT anyone can freely write and distribute plugins without HashiCorp approval

+ Option E is CORRECT plugins that can only be written in GO language as of now.

Third-party plugins should be manually downloaded and installed. They can be installed in any directory. As of now, Plugins can only be written in the GO language.

https: //www.terraform.io/docs/plugins/basics.html
https: //www.terraform.io/docs/configuration/providers.html#third-party-plugins

484
Q

How can we skip interactive approval for terraform apply command? (SELECT TWO)

A. terratorm apply -auto-approve
B. terratorm apply -yes
C. terraform plan -out=”testfplan” and terraform apply testtfplan
D.terraform apply -auto-approvestrue

A

Explanation:
‘Answers: A and C

+ Option A is CORRECT auto-approve option is used to skip interactive approval

+ Option Bi s INCORRECT -yes is not a valid option in terraform

+ Option C is CORRECT to apply will not ask for approval if plans is supplied as an argument,

+ Option Dis INCORRECT -auto-approve will not ask for value.

We can skip interactive approval in 2 ways.

+ “and” operator is specific to Operating System on which this command is executed, If the OS is”Linux’ then “and” command will be used as conjunction and if the OS is Windows,
then (semicolon) is used for conjunction as terraform plan ~out=”test.fplan’; terraform apply test.fplan

+ Using ~auto-approve option along with terraform apply

+ When terraform apply runs on execution plan. It will net ask for approval This is useful when terraform is used in automation.

https://www.terraform.io/docs/commands/apply.html

485
Q

Bob has launched a server using terraform. He wanted to change the server size from 268 to 4GB. He makes changes to configuration and applies to terraform plan and goes for a break But

another team member changes the size to 4G2 manually from the cloud provider console. When Bob enters terraform apply what happens?

A. Terraform will destroy and create a new server with 4GB. Apply complete! Resources: | added, 0 changed 1 destroyed.

B. Terraform will create a new server with 4GB.
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

C. Terraform will not do any changes as already server is of size 4GB. Apply complete! Resources: 0 added, 0 changed, O destroyed.

D.Terratorm will try to change the server size again to 4GB. Apply complete! Resources: 0 added, I changed, 0 destroyed.

A

Explanation:
Answer: C
+ Option A is INCORRECT because terraform will not create destroy and create as size, is already 4GB.

+ Option B is INCORRECT to terraform will not create a new resource as already resource is already present

+ Option C is CORRECT because as already server has reached the desired state terraform will not do any changes.

+ Option D is INCORRECT because ais already server has reached desired state terraform will not do any changes.

Terraform uses the concept of the desired and current state. Whenever it tries to apply any changes it refreshes the state and sees what the current state is.

Then it compares the current state to desired state present in the configuration file. hen it decides what changes to do.

486
Q

Is terraform destroy the only method to delete a resource provisioned by terraform?

True
False

A

Explanation
Answer: B

Til Terraform version 016, terraform destroy is the only command to destroy the infrastructure, but in terraform 015.2 and above versions, terraform apply -destroy is also used to

destroy the infrastructure. For more information, see the links below:

487
Q

You are « DevOps Engineer for @ company that has no experience with Terraform and you have to design and multi-environment Terraform State Architecture for “dev’, “stg” and

‘prod’ on an S3 bucket for Terraform Cloud to delegate permissions on your infrastructure. What of the following approach you could consider to follow:

‘A Have a single bucket with a single state for different states like my bucket/dev.tfstate mybucket/stg.tfstate mybucket/prod.tfstate

B.Create different workspaces per environment:

mybucket/dev/application.tfstate mybucket/stg/application.tfstate mybucket/prod/applicationt.tfstate

C. Use the default workspace for all the stages

D. all of the above

A

Correct Answer: B

Explanation:
Workspaces are the main tool for Terraform to delegating access between different environments.
The recommendations by Hashicorp have always been to create a workspace per environment.

+ Option A is incorrect when using workspaces in Terraform Cloud. On Terraform OpenSource an approach could be

mybucket/dev/dev.tfstate
mybucket/stg/stg.tfstate
mybucket/prod/prod.tfstate
but you are missing the permissions control

+ Option C is incorrect as we don’t have segmentation between the different environments.

+ Option D is incorrect as A and C don’t suit the best practices

Reference:

https://www.terraform.io/docs/cloud/guides/recommended-practices/part1.html#the-recommended-terraform-workspace-structure

488
Q

With which version controls can you add modules on your Terraform Cloud private registry?

A. AWS CodleCommit and Gitkub

B. 2.AWS Codecommit Github, Gitlab, BitBucket, GCP Cloud Source Repositories

C.AWS CodeCommit, GCP Cloud Source Repositories, Azure DevOps

D.Github, GitLab, BitBucket, Azure DevOps

A

D.Github, GitLab, BitBucket, Azure DevOps

Supported VCS Providers
Terraform Cloud supports the following VCS providers:

GitHub.com
GitHub.com (OAuth)
GitHub Enterprise
GitLab.com
GitLab EE and CE
Bitbucket Cloud
Bitbucket Server
Azure DevOps Server
Azure DevOps Services
Use the links above to see details on configuring VCS access for each supported provider. If you use another VCS that is not supported, you can build an integration via the API-driven run workflow.

https://www.terraform.io/docs/cloud/vcs/index.html#supported-vcs-providers

489
Q

Importing infrastructure manipulates Terraform state in ways that could leave existing Terraform projects in an invalid state. What can you do before using Terraform import on a real Terraform project?

A

Make a backup of your terraform.tfstate file and .terraform directory before using Terraform import on a real Terraform project, and store them securely.

490
Q

What are the two ways to choose which permissions a given team has on a Terraform Cloud workspace?

A

Fixed permission sets
Custom permissions

Additionally, there is a special “admin” permission set that grants the highest level of permissions on a workspace.

https://www.terraform.io/docs/cloud/users-teams-organizations/permissions.html#workspace-permissions

491
Q

What are the two categories of complex types: ?

A
  • Collection types: for grouping similar values

- Structural types: for grouping potentially dissimilar values