OFFICIAL DOCUMENTATION Flashcards

1
Q

Terraform cloud

A

Terraform Cloud runs Terraform operations and stores state remotely, so you can use Terraform without worrying about the stability of your local machine, or the security of your state file.

Terraform Cloud (free for up to five users), you can securely share your state with your teammates, provide a stable environment for Terraform to run in, and prevent race conditions when multiple people make configuration changes at once.

The remote state backend feature allows for collaboration and state sharing, provides a stable environment for Terraform to run in, and prevents race conditions when multiple people make config changes simultaneously of Terraform Cl.

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

Terraform Statefile

A

Source of truth about your environment.
It uses the statefile to determine/calculate what changes are required to match your configuration

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

Terraform Providers

A

Same as Terraform Plugins

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

provider maintainers

A

Terraform providers manage resources by communicating between Terraform and target APIs. Whenever the target APIs change or add functionality, provider maintainers may update and version the provider.

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

Collaboration notes

A

When multiple users or automation tools run the same Terraform configuration, they should all use the same versions of their required providers.

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

Managing Provider consistency

A

There are two ways for you to manage provider versions in your configuration.
1. provider ** version constraints** in your configuration’s terraform block.
2. Use the dependency lock file

If you do not scope provider version appropriately, Terraform will download the latest provider version that fulfills the version constraint. This may lead to unexpected infrastructure changes. By specifying carefully scoped provider versions and using the dependency lock file, you can ensure Terraform is using the correct provider version so your configuration is applied consistently.

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

TF Cloud Variable sets

A

Terraform Cloud lets you define input variables and environment variables using either workspace-specific variables(config or user/workspace variable), or sets of variables that you can reuse in multiple workspaces(global/environment variables).

One common use case for variable sets is for provider credentials. By defining a variable set for your credentials, you can easily reuse the same variables across multiple workspaces and efficiently and securely rotate your credentials.

You can define both input variables and environment variables in variable sets

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

Input Variables vs Environment variables

A

Input variables aka Terraform variables define the values for variables you reference in your configuration,

while environment variables aka global variables typically store provider credentials or modify Terraform’s behavior, such as logging verbosity

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

variable sets and security concerns

A

You can apply a variable set to all workspaces in your organization, or scope it to specific ones. When using variable sets with credentials, reuse the variable set with care and avoid the global option, since it does not follow least privilege best practices.

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

Sensitive Variable

A

Marking a variable as sensitive prevents Terraform from displaying it in the Terraform Cloud UI and makes the variable write-only.

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

Lock workspace

A

the lock icon indicating whether the workspace is locked, which prevents others from triggering new runs.

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

-var flag

A

When using the CLI-driven workflow for Terraform Cloud, any variables passed using the -var flag will override workspace-specific variables. However, Terraform Cloud will not save the new value in your workspace unless you update the variable in the UI. This feature can be useful when you want to test or temporarily apply a change that you expect to revert on the next apply, so your stored variable values continue to reflect the desired eventual configuration.

aka per/run variables

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

VCS vs CLI driven workflow

A

The CLI-driven workflow allows you to quickly iterate on your configuration and work locally, while the VCS-driven workflow enables collaboration within teams by establishing your shared repositories as the source of truth for infrastructure configuration.

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

Sentinel Enforcement Level

A

Enforcement levels establish whether or not an operation can proceed if a policy fails. Sentinel provides three enforcement levels:

Hard-mandatory requires that the policy passes. If a policy fails, the run stops. You must resolve the failure to proceed.

Soft-mandatory lets an organization owner or a user with override privileges proceed with the run in the event of failure. Terraform Cloud logs all overrides.

Advisory will notify you of policy failures, but proceed with the operation.

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

Sentinel Enforcement Level

A

Enforcement levels establish whether or not an operation can proceed if a policy fails. Sentinel provides three enforcement levels:

Hard-mandatory requires that the policy passes. If a policy fails, the run stops. You must resolve the failure to proceed.

Soft-mandatory lets an organization owner or a user with override privileges proceed with the run in the event of failure. Terraform Cloud logs all overrides.

Advisory will notify you of policy failures, but proceed with the operation.

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

Creating TFC workspace, CLI

A

When using the CLI-driven Terraform Cloud workflow, running terraform init on configuration with a cloud block creates the Terraform Cloud workspace specified in the block, if it does not already exist.

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

Terraform variables(console)

A

This feature can be useful when you want to test or temporarily apply a change that you expect to revert on the next apply, so your stored variable values continue to reflect the desired eventual configuration.

Entering terraform variables on the GUI can be effective in quick testing

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

Speculative plan logs(VCS integration)

A

Speculative plans are non-destructive, plan-only runs that show you the changes Terraform will make to your infrastructure if you merge a pull request. The runs will not appear in your Terraform Cloud logs and you can only access them through a direct link, which Terraform Cloud will attach to your pull request.

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

Policy sets vs Policy

A

Definition:
Policy sets are a named grouping of policies and their enforcement levels.

To apply a policy to a workspace and it’s run, you must first add it to a policy set. Each policy set can apply to specific workspaces, or to all workspaces within an organization. Policy sets are the mapping between policies and workspaces.

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

sentinel file format

A

<policy>.sentinel
</policy>

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

terraform init

A

When you initialize a Terraform workspace, Terraform configures the backend, installs all providers and modules referred to in your configuration, and creates a version lock file if one doesn’t already exist. In addition, you can use the terraform init command to change your workspace’s backend and upgrade your workspace’s providers and modules.

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

Open Policy Agent (OPA).

A

Configuration-level validation such as variable constraints and preconditions let you socialize standards from within your written configuration. However, module authors and users must voluntarily comply with the standards. Module authors must include conditions in module definitions, and users must consume those modules to provision infrastructure. To enforce infrastructure standards across entire workspaces or organizations, you can use OPA policies, which work without requiring your users to write their infrastructure configuration in a specific way.

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

Lifecycle pre-conditions

A

lifecycle {
precondition {
condition = data.aws_ec2_instance_type.bastion.default_cores <= 2
error_message = “Change the value of bastion_instance_type to a type that has 2 or fewer cores to avoid over provisioning.”
}
}

the above block of code restricts instance to a maximum of 2cores.

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

Drift Detection and Healthcheck

A

Drift Detection and Health checks are only available on Enterprise tf cloud

Drift detection only reports on changes to the resource attributes defined in your configuration.

Fixing drift is a manual process, because you need to understand whether you want to keep the infrastructure changes made outside of Terraform, or overwrite them(terraform apply)
Shortly after enabling health assessments, the first assessment runs on the workspace. After the first assessment, following assessments run once every 24 hours.

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

required_providers block

A

The terraform required_providers block contains the r, which specifies the provider
1. local name,
2. the source address,
3. and the version.

When you initialize this configuration, Terraform will download:

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

Minimum provider version

A

The >= version constraint operator specifies the minimum provider version that is compatible with the configuration.

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

terraform.lock.hcl

A

When you initialize a Terraform configuration for the first time with Terraform 1.1 or later, Terraform will generate a new .terraform.lock.hcl file in the current working directory.

Terraform Dependency Lock File

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

The -upgrade flag

A

Upgrade the AWS provider version

The -upgrade flag will upgrade all providers to the latest version consistent within the version constraints specified in your configuration.

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

Terraform lock file and VCS

A

When you initialize a Terraform configuration for the first time with Terraform 1.1 or later, Terraform will generate a new .terraform.lock.hcl file in the current working directory. You should include the lock file in your version control repository to ensure that Terraform uses the same provider versions across your team and in ephemeral remote execution environments.

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

~ terraform show

A

to Inspect the current state, use terraform show

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

~ terraform state

A

use terraform state for advanced state management. Use the list subcommand to list of the resources in your project’s state.

~terraform state list

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

~ terraform output

A

this command can print out all output parameters in the statefile

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

provider version and version constraints

A

Each provider plugin has its own set of available versions, allowing the functionality of the provider to evolve over time. Each provider dependency you declare should have a version constraint given in the version argument so Terraform can select a single version per provider that all modules are compatible with.

The version argument is optional; if omitted, Terraform will accept any version of the provider as compatible. However, we strongly recommend specifying a version constraint for every provider your module depends on.

To ensure Terraform always installs the same provider versions for a given configuration, you can use Terraform CLI to create a dependency lock file and commit it to version control along with your configuration. If a lock file is present, Terraform Cloud, CLI, and Enterprise will all obey it when installing providers.

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

Special note

A

A Terraform configuration may refer to two different kinds of external dependency that come from outside of its own codebase:

Providers, which are plugins for Terraform that extend it with support for interacting with various external systems.
Modules, which allow splitting out groups of Terraform configuration constructs (written in the Terraform language) into reusable abstractions.
Both of these dependency types can be published and updated independently from Terraform itself and from the configurations that depend on them. For that reason, Terraform must determine which versions of those dependencies are potentially compatible with the current configuration and which versions are currently selected for use.

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

Providers and Module versions

A

Version constraints within the configuration itself determine which versions of dependencies are potentially compatible, but after selecting a specific version of each dependency Terraform remembers the decisions it made in a dependency lock file so that it can (by default) make the same decisions again in future.

At present, the dependency lock file tracks only provider dependencies. Terraform does not remember version selections for remote modules, and so Terraform will always select the newest available module version that meets the specified version constraints. You can use an exact version constraint to ensure that Terraform will always select the same module version.

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

Terraform state lock file format

A

The dependency lock file uses the same low-level syntax as the main Terraform language, but the dependency lock file is not itself a Terraform language configuration file. It is named with the suffix .hcl instead of .tf in order to signify that difference.

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

Dependecy Lockfile creation

A

The lock file is always named .terraform.lock.hcl, and this name is intended to signify that it is a lock file for various items that Terraform caches in the .terraform subdirectory of your working directory.

Terraform automatically creates or updates the dependency lock file each time you run the terraform init command. You should include this file in your version control repository so that you can discuss potential changes to your external dependencies via code review, just as you would discuss potential changes to your configuration itself.

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

Dependencies lockfile scope

A

The dependency lock file is a file that belongs to the configuration as a whole, rather than to each separate module in the configuration. For that reason Terraform creates it and expects to find it in your current working directory when you run Terraform, which is also the directory containing the .tf files for the root module of your configuration.

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

dependency version choice

A

When terraform init is working on installing all of the providers needed for a configuration, Terraform considers both the version constraints in the configuration and the version selections recorded in the lock file.

If a particular provider has no existing recorded selection, Terraform will select the newest available version that matches the given version constraint, and then update the lock file to include that selection.

If a particular provider already has a selection recorded in the lock file, Terraform will always re-select that version for installation, even if a newer version has become available. You can override that behavior by adding the -upgrade option when you run terraform init, in which case Terraform will disregard the existing selections and once again select the newest available version matching the version constraint.

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

Understanding Lock File Changes

A

Because the dependency lock file is primarily maintained automatically by Terraform itself, rather than being updated manually by you or your team, your version control system may show you that the file has changed.

There are a few different types of changes that Terraform can potentially make to your lock file, which you may need to understand in order to review the proposed changes.

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

Note on module versions

A

A module intended to be used as the root of a configuration — that is, as the directory where you’d run terraform apply — should also specify the maximum provider version it is intended to work with, to avoid accidental upgrades to incompatible new versions. The ~> operator is a convenient shorthand for allowing the rightmost component of a version to increment.

Do not use ~> (or other maximum-version constraints) for modules you intend to reuse across many configurations, even if you know the module isn’t compatible with certain newer versions. Doing so can sometimes prevent errors, but more often it forces users of the module to update many modules simultaneously when performing routine upgrades. Specify a minimum version, document any known incompatibilities, and let the root module manage the maximum version.

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

Terraform folder structure

A

tree
.
├── LICENSE
├── README.md
├── main.tf
├── modules
│ └── aws-ec2-instance
│ ├── main.tf
│ └── variables.tf
├── terraform.tf
└── variables.tf

The example repository includes the following:

LICENSE - includes the text of the Mozilla Public License under which HashiCorp distributes the example configuration.

README.md - describes the example configuration.

main.tf - includes the resources and data sources used by the example configuration.

the modules/aws-ec2-instance - directory includes a Terraform module to provision an EC2 instance on AWS.

terraform.tf - defines the terraform block, which defines the providers, remote backend, and the Terraform version(s) to be used with this configuration.

variables.tf - defines the variables used in this configuration.

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

After ~terraform init

A

├── LICENSE
├── README.md
├── main.tf
├── modules
│ └── aws-ec2-instance
│ ├── main.tf
│ └── variables.tf
├── terraform.tf
└── variables.tf
├──.terraform
│ └── modules
│ └── providers

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

CAUTION !!!

A

├──.terraform
│ └── modules
│ └── providers

Terraform automatically manages the .terraform directory. Do not check it into version control, and do not directly modify this directory’s contents. Exploring the .terraform directory in this tutorial is meant to deepen your understanding of how Terraform works, but the contents and structure of this directory are subject to change between Terraform versions.

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

When to run terraform init

A

Initialize your Terraform workspace with terraform init when:

You create new Terraform configuration and are ready to use it to create a workspace and provision infrastructure.

You clone a version control repository containing Terraform configuration, and are ready to use it to create a workspace and provision infrastructure.

You add, remove, or change the version of a module or provider in an existing workspace.

You add, remove, or change the backend or cloud blocks within the terraform block of an existing workspace.

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

Terraform state migration

A

Migrate the state file

To migrate your existing state file to Terraform Cloud, you must reinitialize your configuration to update the backend.

Reinitialize your configuration. Terraform detects your updated backend and confirms that you wish to migrate your state file to Terraform Cloud. Type yes to confirm the migration.

This is all assuming you have your cloud Block within your configuration

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

save terraform plan

A

to save a terraform plan to a binaryfile called replan:

~ terraform plan -out “tfplan”

to print on screen:
~terraform show “tfplan”

Convert the saved plan into JSON, pass it to jq to format it, and save the output into a new file:
terraform show -json “tfplan” | jq > tfplan.json

then use jq for analysis:
- The configuration section further organizes your resources defined in your top level root_module:

~ jq ‘.configuration.root_module.resources’ tfplan.json

  • The module_calls section contains the details of the modules used, their input variables and outputs, and the resources to create:

jq ‘.configuration.root_module.module_calls’ tfplan.json

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

~ terraform apply replace

A

~ terraform apply -replace “aws_instance.main[1]”

when a resource has become unhealthy or stops working in ways that are outside of Terraform’s control. For instance, an error in your EC2 instance’s OS configuration could require that the instance be replaced. There is no corresponding change to your Terraform configuration, so you want to instruct Terraform to reprovision the resource using the same configuration.

The -replace argument requires a resource address. List the resources in your configuration with terraform state list.

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

Alternative variable injection

A
  1. CLI
    ~ terraform apply -var ec2_instance_type=t2.micro
  2. FILE
    *.auto.tfvars or terraform.tfvars file
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

Description

A

While the description argument is optional, you should include it in all output declarations to document the intent and content of the output.

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

trouleshooting terraform version issues

A

sometimes removing the terraform version specification can solve version problems. However, this has to be done cautiously

NOTE
In general, we encourage you to use the latest available version of Terraform to take advantage of the most recent features and bug fixes. However, it is unnecessary to upgrade your Terraform projects to the latest version every time you use Terraform unless you need a specific feature or bug fix.

As a best practice, consider using ~> style version constraints to pin your major and minor Terraform version. Doing so will allow you and your team to use patch version updates without updating your Terraform configuration. You can then plan when you want to upgrade your configuration to use a new version of Terraform, and carefully review the changes to ensure that your project still works as intended.

For example, if you write Terraform configuration using Terraform 1.0.0, you would add required_version = “~> 1.0.0” to your terraform { } block. This will allow you and your team to use any Terraform 1.0.x, but you will need to update your configuration to use Terraform 1.1.0 or later.

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

.tftpl

A

.terraform template file

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

terraform module sources

A

Modules can either be loaded from the local filesystem, or 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

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

Understand how modules work

A

When using a new module for the first time, you must run either terraform init or terraform get to install the module. When you run these commands, Terraform will install any new modules in the .terraform/modules directory within your configuration’s working directory. For local modules, Terraform will create a symlink to the module’s directory. Because of this, any changes to local modules will be effective immediately, without having to reinitialize or re-run terraform get.

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

GIT IGNORE

A

The files mentioned below will often include secret information such as passwords or access keys, which will become public if those files are committed to a public version control system such as GitHub.

There are also some other files to be aware of, and ensure that you don’t distribute them as part of your module:

terraform.tfstate and terraform.tfstate.backup: These files contain your Terraform state, and are how Terraform keeps track of the relationship between your configuration and the infrastructure provisioned by it.

.terraform: This directory contains the modules and plugins used to provision your infrastructure. These files are specific to a specific instance of Terraform when provisioning infrastructure, not the configuration of the infrastructure defined in .tf files.

.tfvars: Since module input variables are set via arguments to the module block in your configuration, you don’t need to distribute any *.tfvars files with your module, unless you are also using it as a standalone Terraform configuration.

If you are tracking changes to your module in a version control system, such as git, you will want to configure your version control system to ignore these files. For an example, see this .gitignore file from GitHub.

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

Terraform Statefile

A

The Terraform state file is a record of all resources Terraform manages. **You should not make manual changes to resources controlled by Terraform, because the state file will be out of sync, **or “drift,” from the real infrastructure. If your state and configuration do not match your infrastructure, Terraform will attempt to reconcile your infrastructure, which may unintentionally destroy or recreate resources

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

terraform Refresh

A

by default, Terraform compares your state file to real infrastructure whenever you invoke terraform plan or terraform apply. The refresh updates your state file in-memory to reflect the actual configuration of your infrastructure. This ensures that Terraform determines the correct changes to make to your resources.

If you suspect that your infrastructure configuration changed outside of the Terraform workflow, you can use a -refresh-only flag to inspect what the changes to your state file would be. This is safer than the refresh subcommand, which automatically overwrites your state file without displaying the updates.

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

-refresh-only Flag

A

A refresh-only operation does not attempt to modify your infrastructure to match your Terraform configuration – it only gives you the option to review and track the drift in your state file.

If you ran terraform plan or terraform apply without the -refresh-only flag now, Terraform would attempt to revert your manual changes. Instead, you will update your configuration to associate your EC2 instance with both security groups.

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

-refresh-only

A

In Terraform, refreshing your state file updates Terraform’s knowledge of your infrastructure, as represented in your state file, with the actual state of your infrastructure. Terraform plan and apply operations run an implicit in-memory refresh as part of their functionality, reconciling any drift from your state file before suggesting infrastructure changes. You can also update your state file without making modifications to your infrastructure using the -refresh-only flag for plan and apply operations.

Though Terraform will continue to support the refresh subcommand in future versions, it is deprecated, and we encourage you to use the -refresh-only flag instead. This allows you to review any updates to your state file. Unlike the refresh subcommand, -refresh-only mode is supported in workspaces using Terraform Cloud as a remote backend, allowing your team to collaboratively review any modifications.

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

terraform error management

A
  1. Language error (HCL Syntax)
  2. State error (statefile logical check)
  3. Core error: The Terraform core application contains all the logic for operations. It interprets your configuration, manages your state file, constructs the resource dependency graph, and communicates with provider plugins. Errors produced at this level may be a bug. Later in this tutorial, you will learn best practices for opening a GitHub issue for the core development team.
  4. Provider error: The provider plugins handle authentication, API calls, and mapping resources to services. Later in this tutorial, you will learn best practices for opening a GitHub issue for the provider development team.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

terraform fmt vs Validate

A

terraform fmt only parses your HCL for interpolation errors or malformed resource definitions, which is why you should use terraform validate after formatting your configuration to check your configuration in the context of the providers’ expectations.

62
Q

datatypes

A

**Splat operator (*) only works with LIST type

while

for_each only works with MAP or set of strings type**

Note:
The splat expression [*] only interpolates list types, while the for_each attribute is reserved for map types. A local value can return a map type.

63
Q

Terraform logs

export TF_LOG_CORE=TRACE

A

TRACE provides the highest level of logging and contains all the information the development teams need. There are other logging levels, but are typically reserved for developers looking for specific information.

64
Q

export TF_LOG_PROVIDER=TRACE

A

You can also generate provider logs by setting the TF_LOG_PROVIDER environment variable. By including these in your bug reports, the provider development team can reproduce and debug provider specific errors.

65
Q

export TF_LOG_PATH=logs.txt

A

Once you have configured your logging, set the path for your error logs as an environment variable. If your TF_LOG_CORE or TF_LOG_PROVIDER environment variables are enabled, the TF_LOG_PATH variable will create the specified file and append logs generated by Terraform.

66
Q

terraform Cloud integration

A

To use Terraform Cloud as a backend for your configuration, you must include a cloud block in your configuration.

The Cloud block:

terraform {
cloud {
organization = “ORGANIZATION-NAME”
workspaces {
name = “learn-terraform-cloud-migrate”
}
}

67
Q

Terraform cloud with existing workspace

A

While the organization defined in the cloud stanza must already exist, the workspace does not have to; Terraform Cloud will create it if necessary. If you use an existing workspace, it must not have any existing states.

68
Q

Authenticate with Terraform Cloud

A

After configuring your Terraform Cloud integration, you must authenticate to Terraform Cloud to use it for remote operations.

Run terraform login and follow the prompts to log in, typing yes at the confirmation prompt.

69
Q

Migrate the state file

A

To migrate your existing state file to Terraform Cloud, you must reinitialize your configuration to update the backend.(terraform init)

Reinitialize your configuration. Terraform detects your updated backend and confirms that you wish to migrate your state file to Terraform Cloud. Type yes to confirm the migration.

70
Q
A

After migrating your state to Terraform Cloud, log in to the Terraform Cloud web UI and navigate to your learn-terraform-cloud-migrate workspace. Then, go to the workspace’s States page. Terraform Cloud lists the state you migrated to your new workspace.

71
Q

after state Migration

A

After verifying that Terraform migrated your state to Terraform Cloud, manually remove your local state file from your local host.

72
Q

The VCS-driven workflow

A

The VCS-driven workflow

For the VCS-driven workflow, you must configure VCS access and create your workspace, then associate it with a repository containing your Terraform configuration. You can then configure your workspace to create speculative plans for any Pull Requests, which allows your team to review how the changes would modify infrastructure. Any merges to your main branch then trigger Terraform runs to implement your changes.

73
Q

Create a terraform cloud workspace using CLI

A

When using the CLI-driven Terraform Cloud workflow, running terraform init on configuration with a cloud block creates the Terraform Cloud workspace specified in the block, if it does not already exist.

Note:
Every Terraform Cloud workspace belongs to a project, which is a group of workspaces. When you create your workspace using this automated CLI workflow, Terraform Cloud adds the workspace to your organization’s Default project unless you set the project argument in your configuration’s cloud block. Projects help you organize your workspaces into groups, making it easier to find workspaces in large Terraform Cloud organizations

74
Q

auto.tfvars f

A

auto.tfvars files have the lowest precedence in a workspace, and any workspace specific variables will override the values defined in this file.

75
Q

Terraform backends

A

By default, Terraform uses a backend called local, which stores state as a local file on disk. You can also configure one of the built-in backends included in this documentation.

Some of these backends act like plain remote disks for state files, while others support locking the state while operations are being performed. This helps prevent conflicts and inconsistencies. The built-in backends listed are the only backends. You cannot load additional backends as plugins.

Note:
You do not need to configure a backend when using Terraform Cloud because Terraform Cloud automatically manages state in the workspaces associated with your configuration.** If your configuration includes a cloud block, it cannot include a backend block.**

76
Q

terraform apply -replace

A

The terraform apply -replace command manually marks a Terraform-managed resource for replacement, forcing it to be destroyed and recreated on the apply execution.
You could also use terraform destroy -target <virtual> and destroy only the virtual machine and then run a terraform apply again.</virtual>

77
Q

Terraform versions asper migration

A

If you migrate an existing project from the CLI to Terraform Cloud, Terraform Cloud configures the workspace to use the same version as the Terraform binary you used when migrating.

78
Q

~ terraform state rm

A

To destroy all Terraform-managed resources except for a single resource, you can use the terraform state command to remove the state for the resources you want to preserve. This effectively tells Terraform that those resources no longer exist, so it will not attempt to destroy them when you run terraform destroy.

  1. run terraform state list
  2. Run terraform state rm for each resource you want to keep, like the prod_db.
  3. terraform destroy

The above can be useful in scenarios where you want to keep certain resources managed by Terraform while removing others.

Note that this approach can be dangerous and is not recommended if you have multiple Terraform workspaces or if you are using a remote state backend, as it can cause inconsistencies in your state file. In those cases, it is usually better to use a separate Terraform workspace for the resources you want to preserve or to utilize Terraform’s built-in resource-targeting functionality to destroy only specific resources.

79
Q

Terraform can be expressed using two syntaxes: HashiCorp Configuration Language (HCL), which is the primary syntax for Terraform, and JSON.

A

The HCL syntax is designed to be human-readable and easy to write, and it provides many features designed explicitly for Terraform, such as interpolation, variables, and modules.
The JSON syntax is a machine-readable alternative to HCL, and it is typically used when importing existing infrastructure into Terraform or when integrating Terraform with other tools that expect data in JSON format.
While Terraform will automatically detect the syntax of a file based on its extension,

Note
Most Terraform configurations are written in the native Terraform language syntax, which is designed to be relatively easy for humans to read and update.

Terraform also supports an alternative syntax that is JSON-compatible. This syntax is useful when generating portions of a configuration programmatically, since existing JSON libraries can be used to prepare the generated configuration files.

The JSON syntax is defined in terms of the native syntax. Everything that can be expressed in native syntax can also be expressed in JSON syntax, but some constructs are more complex to represent in JSON due to limitations of the JSON grammar.

Terraform expects native syntax for files named with a .tf suffix, and JSON syntax for files named with a .tf.json suffix.

80
Q

implicit vs Explicit dependencies

A

Depends-on - Explicit
vpc_id = data.aws_vpc.web.id - implicit

Note:
In general, Terraform implicit dependencies are handled automatically, but sometimes it may be necessary to use the depends_on argument to ensure that resources are created in the correct order.

81
Q

HCL indentation

A

HashiCorp, the creator of Terraform, recommends using two spaces for indentation when writing Terraform code. This is a convention that helps to improve readability and consistency across Terraform configurations.
While this is the recommended convention, it is not a strict requirement and Terraform will still function correctly even if you use a different number of spaces or a different type of indentation. However, using two spaces for indentation is a widely adopted convention in the Terraform community and is recommended by HashiCorp to improve the readability and maintainability of your Terraform configurations.

82
Q

alias

A

An alias meta-argument is used when using the same provider with different configurations for different resources. This feature allows you to include multiple provider blocks that refer to different configurations. In this example, you would need something like this:

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

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

83
Q

Providers Block special note

A

Resources that don’t set the provider meta-argument will use the default provider configuration that matches the first word of the resource type name. (For example, an aws_instance resource uses the default aws provider configuration unless otherwise stated.)

84
Q

Required providers

A

In Terraform, there are two related but distinct concepts: the provider block and the required_providers block.

  1. provider Block:
    The provider block is used to configure a specific instance of a provider within a Terraform configuration. This block is where you define the configuration details for a particular provider, such as AWS, Azure, or others.

Example using the aws provider:

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

resource “awsinstance” “example” {
ami = “ami-0123456789abcdef0”
instancetype = “t2.micro”
}

In this example, the provider “aws” block configures an instance of the AWS provider with the specified region. The subsequent resource “aws_instance” block then uses this provider instance to create an EC2 instance.

  1. required_providers Block:
    The required_providers block is used to **declare the providers required by a Terraform configuration and specify their versions. **This block is typically placed at the top level of your Terraform configuration.

***terraform {
required_providers {
aws = {
source = “hashicorp/aws”
version = “~> 3.0”
}
}
}

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

85
Q

Data block

A

In Terraform, data blocks are used to retrieve data from external sources, such as APIs or databases, and make that data available to your Terraform configuration. With data blocks, you can use information from external sources to drive your infrastructure as code, making it more dynamic and flexible.

For example, you can use a data block to retrieve a list of Amazon Machine Images (AMIs) from AWS, and then use that data to select the appropriate AMI for a virtual machine you are provisioning:

86
Q

Terraform module requirement

A

GitHub. The module must be on GitHub and must be a public repo. This is only a requirement for the public registry. If you’re using a private registry, you may ignore this requirement

Named terraform-<PROVIDER>-<NAME>. Module repositories must use this three-part name format, where <NAME> reflects the type of infrastructure the module manages and <PROVIDER> is the main provider where it creates that infrastructure. The <NAME> segment can contain additional hyphens. Examples: terraform-google-vault or terraform-aws-ec2-instance.</NAME></PROVIDER></NAME></NAME></PROVIDER>

Repository description. The GitHub repository description is used to populate the short description of the module. This should be a simple one-sentence description of the module.

Standard module structure. The module must adhere to the standard module structure. This allows the registry to inspect your module and generate documentation, track resource usage, parse submodules and examples, and more.

x.y.z tags for releases. The registry uses tags to identify module versions. Release tag names must be a semantic version, which can optionally be prefixed with a v. For example, v1.0.4 and 0.9.2. To publish a module initially, at least one release tag must be present. Tags that don’t look like version numbers are ignored.

87
Q

terraform required version

A

terraform {
required_version = “>= 1.3.8”
}

The required_version parameter in a terraform block is used to specify the minimum version of Terraform that is required to run the configuration. This parameter is optional, but it can be useful for ensuring that a Terraform configuration is only run with a version of Terraform that is known to be compatible.

88
Q

terraform state command

A

By using the terraform state command and its subcommands, users can manage and manipulate the Terraform state in various ways, helping to ensure that their Terraform configurations are in the desired state.

terraform state command must be paired with a subcommand

Subcommands:
list List resources in the state
mv Move an item in the state
pull Pull current state and output to stdout
push Update remote state from a local state file
replace-provider Replace provider in the state
rm Remove instances from the state
show Show a resource in the state
import Used to import existing resources into the Terraform state. This allows Terraform to manage resources that were created outside of Terraform.

89
Q

terraform state local path

A

Terraform Open Source (OSS) stores the local state for workspaces in a file on disk. For local state, Terraform stores the workspace states in a directory called terraform.tfstate.d/<workspace_name></workspace_name>

90
Q

terraform backend

A

Storage for terraform state
1. Local
2. S3
3. vault
4. Cloud
5. Consul

91
Q

Parallellism

A

By default, Terraform will provision resources concurrently with a maximum of 10 concurrent resource operations. This setting is controlled by the parallelism configuration option in Terraform, which can be set globally in the Terraform configuration file or on a per-module basis.
The parallelism setting determines the number of resource operations that Terraform will run in parallel, so increasing the parallelism setting will result in Terraform provisioning resources more quickly, but can also increase the risk of rate-limiting or other errors from the API.
You can adjust the parallelism setting in your Terraform configuration file by adding the following code:

terraform {
parallelism = 10
}
This setting sets the maximum number of concurrent resource operations to 10. You can adjust this number to meet your specific needs and constraints.

92
Q

statefile security best practices

A

there’s no means of masking secrets in a tf statefile. It requires extra steps, such as, env vriables or Terraform input variables to store sensitive information, and then use Terraform’s data sources to retrieve the information from the environment or input variables, rather than hardcoding the information into the Terraform configuration. This helps to ensure that sensitive information is not stored in plain text in the Terraform plan or state files.

93
Q

Local Exec

A

Terraform includes the concept of provisioners as a measure of pragmatism, knowing that there are always certain behaviors that cannot be directly represented in Terraform’s declarative model.

In Terraform, the local-exec provisioner is used to execute a command on the machine running Terraform, rather than on a remote resource.
The local-exec provisioner is often used to perform actions that cannot be accomplished using Terraform’s built-in resource types or to execute local scripts or commands to perform additional setup or configuration after creating infrastructure resources.

Note
Provisioners should only be used as a last resort. For most common situations there are better alternatives. For more information, see the sections above.

94
Q

Provisioneers

A

Provisioners in Terraform are used to execute scripts or commands on a resource after it has been created. While provisioners can be useful in certain situations, such as configuring a server or setting up a database, it is generally true that provisioners should only be used as a last resort.

provisioners are used to copy files from a local machine to a resource.

provisioner block contains the source and destination parametes

Connection block
provisioner also requires a connection block that describes the protocols and route for the provisioner to use

Security Group
Security group must also permit the port declared by the connection block

key pair
provisioner also requires a keypairblock with settings for ssh access

95
Q

TF Cloud x VCS

A

In Terraform Cloud, a workspace can be mapped to only 1 VCS repos at a time

96
Q

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

A

API tokens

97
Q

tf state file format and Best practices

A

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 local state, 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 remote state is in use, and some backends can be configured to encrypt the state data at rest.

98
Q

Advantage of specifying Provider version

A

Declaring the required version of a provider in a Terraform configuration file is a good idea for several reasons:

Reproducibility: By specifying the exact version of a provider, you can ensure that anyone who runs your Terraform configuration will use the same version of the provider as you. This makes your infrastructure configuration more reproducible and helps avoid issues that can arise when different versions of a provider are used.

Predictability: When you specify a specific provider version, you can be confident that your infrastructure configuration will behave predictably, regardless of changes to the provider in future versions. This can help you avoid surprises and reduce the risk of unintended consequences.

Compatibility: Different versions of a provider may have different APIs, resources, or behaviors, which can cause issues if you switch to a new version without realizing the differences. By specifying the required version of a provider in your Terraform configuration, you can ensure that your configuration remains compatible with the specific version of the provider you have tested and validated.

Version locking: When you specify the required version of a provider in your Terraform configuration, you effectively lock the version of the provider to that version unless you explicitly change it. This can help prevent issues that may arise when using a different, potentially incompatible version of the provider.
In summary, specifying the required version of a provider in your Terraform configuration file helps ensure that your infrastructure configuration is more predictable, reproducible, compatible, and reduces the risk of unintended consequences or issues caused by version differences.

99
Q

Pros and Cons of Terraform provisioners

A

Provisioners in Terraform are used to execute scripts or commands on a resource after it has been created. While provisioners can be useful in certain situations, such as configuring a server or setting up a database, it is generally true that provisioners should only be used as a last resort.
The reason for this is that using provisioners can make your Terraform code** less predictable and harder to manage. When you use provisioners, you introduce external dependencies and additional complexity into your infrastructure configuration. This can make it harder to reproduce your infrastructure, as well as harder to troubleshoot issues that arise.**
Instead of using provisioners, it is generally recommended to use native Terraform resources and data sources to manage your infrastructure. This approach makes your code more predictable, easier to manage, and less error-prone.
However, there may be situations where provisioners are necessary or unavoidable, such as when working with legacy systems or when a resource does not support the necessary configuration options. In these cases, provisioners can be a useful tool, but they should be used judiciously and with care, and you should be aware of the potential risks and downsides of using provisioners in your infrastructure configuration.

100
Q

terraform backend

A

Location of the statefile. Backend is usually declared in the Terraform block.

terraform {
required_version = “>= 0.12.0, < 0.13.0”
backend “s3” {
bucket = “my-terraform-state”
key = “terraform.tfstate”
region = “us-west-2”
}
}

The terraform block can also be used to configure other settings such as the maximum number of concurrent operations (max_parallelism), the number of retries for failed operations (retryable_errors), and the default input values for variables (default).
By including a terraform block in the Terraform configuration, you can ensure that the correct version of Terraform is used and that the configuration is validated against the correct syntax and semantics for that version. This helps to ensure that the configuration will run correctly and consistently across different environments.

101
Q

Remote Exec connection types

A

The remote-exec provisioner in Terraform is used to execute commands on a resource after it has been created over an SSH or WinRM connection. The supported connection types for remote-exec depend on the type of resource being provisioned and the underlying operating system.
For Linux-based resources, the remote-exec provisioner supports the following connection types:
SSH (Secure Shell) over TCP (Transmission Control Protocol)
For Windows-based resources, the remote-exec provisioner supports the following connection types:
WinRM (Windows Remote Management) over HTTP (Hypertext Transfer Protocol) or HTTPS (HTTP Secure)
Note that both SSH and WinRM connections can be configured to use specific usernames and passwords or SSH keys, depending on the resource being provisioned and the security requirements of the environment.
It is worth noting that while remote-exec provisioner can be useful in certain situations, it should generally be used as a last resort due to the potential risks and complexities involved in executing remote commands on resources. Whenever possible, it is recommended to use Terraform’s native resource types to manage your infrastructure, rather than relying on external scripts or tools.

102
Q

Partial Configuration

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.
With a partial configuration, the remaining configuration arguments must be provided as part of the initialization process. There are several ways to supply the remaining arguments:

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.

103
Q

Terraform Vault

A

Terraform vault does not stream to terraform. Secret files must be downloaded first before use

104
Q

TF vs git commit/.gitignore

A

When using Terraform with Git, it is generally recommended to ignore certain files in order to avoid committing sensitive or unnecessary information to your repository. The specific files that should be ignored may vary depending on your project and configuration, but as a general rule, you should ignore the following files:

.terraform directory: This directory contains local Terraform state files, which should not be committed to the repository.
terraform.tfstate and terraform.
tfstate.backup: These files contain the current state of your infrastructure, and should not be committed to the repository.
.tfvars files: These files may contain sensitive information, such as passwords or API keys, and should be kept out of version control. Instead, you can use environment variables or other secure methods to pass this information to Terraform.
*.tfplan files: These files contain the plan generated by Terraform when applying changes to your infrastructure, and may include sensitive information such as resource IDs. They should not be committed to the repository.
To ignore these files in Git, you can add them to your .gitignore file.

105
Q

terraform fmt

A

The terraform fmt command is a formatting tool in Terraform that helps to automatically format Terraform configuration files to follow a consistent style and make them more readable.
Running terraform fmt will parse the configuration files in the current directory and recursively in subdirectories and rewrite them using a standard formatting style, including indentation, spacing, and line breaks. It will modify the original files in place, so it’s vital to ensure that the files are backed up or committed to a version control system before running this command.

By running terraform fmt, it helps to ensure that the Terraform configuration files are consistent across the project and easy to read, especially when working with large and complex infrastructure codebases. Consistent code style makes it easier for multiple people to collaborate on a project and makes it easier to understand the configuration files when returning to the project after an extended period.
It’s a best practice to run terraform fmt before committing any changes to the configuration files, to ensure that all changes have the same formatting style and are easy to read.

terraform fmt –diff

106
Q

terraform show

A

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.

107
Q

dynamic blocks

A
108
Q

~

A

The prefix -/+ means that Terraform will destroy and recreate the resource, rather than updating it in-place. Some attributes and resources can be updated in-place and are shown with the ~ prefix. Basically, editing/modifying the resource in realtime.

109
Q

terraform module output

A

visibility in Calling Code: If you’re using a module without outputs, the calling code won’t be able to reference any values directly from the module. The module’s side effects, such as creating resources, are still visible in the Terraform state, but specific data might not be accessible.

110
Q

Terraform state backend locking

A

Locking Using System APIs:
To ensure that multiple instances of Terraform don’t interfere with each other, the local backend uses system APIs to perform basic file locking. This prevents simultaneous modifications to the state file by multiple Terraform instances.
However, the local backend doesn’t provide robust locking mechanisms for distributed teams or environments with multiple Terraform users.

111
Q

config directory files

A

In a typical Terraform project, several files and directories play important roles in managing configurations, state, and variables:

Terraform StateFile:
The Terraform state file contains the current state of your infrastructure. It tracks the relationships between resources and their current configuration.
By default, the state file is named terraform.tfstate.
It is stored in the directory where you run Terraform commands unless a backend is configured to store it remotely.

.terraform:
The .terraform directory is used to store local Terraform metadata and plugins.
It contains information about the provider plugins required for your configuration, as well as any local plugins you might have.
This directory is managed by Terraform and can be safely deleted if you want to start with a clean slate. It can be regenerated using terraform init.

.tfvars :
.tfvars files are used to store variable values for your Terraform configurations.
These files typically have a .tfvars extension, e.g., variables.tfvars.
They contain variable assignments and are often used to separate sensitive information (like API keys or secrets) from the main configuration.
However, every parameter passed using .tfvars will still persist to .tfstate
The .tfvars files can be passed to Terraform commands using the -var-file option.

112
Q

Statefile encryption

A

When using local state (state stored on your local machine), the state file is stored in plain-text JSON format by default. This means that sensitive information in the state file is not automatically encrypted when using local state. If security is a concern, it’s recommended to use remote state storage, especially in production environments.

To enhance security in local state scenarios, you can consider using backend configurations with encryption features or implementing additional security measures.

113
Q

terraform dry run

A

In Terraform, the terraform plan command is typically considered a dry run. The plan command generates an execution plan that describes the changes that Terraform will make to the infrastructure, but it does not apply those changes. It provides an opportunity for users to review and verify the planned changes before actually applying them.

114
Q

Data Source

A

Terraform data sources let you dynamically fetch data from APIs or other Terraform state backends.

Data sources allow Terraform to use information defined outside of Terraform, defined by another separate Terraform configuration, or modified by functions.

115
Q

Cloud workspace

A

In Terraform Cloud, workspaces let you share data between workspaces.

116
Q

.tfvars security

A

Data from .tfvars are explicitely passed on to statefile

117
Q

Multicloud configuration

A

Provisioning infrastructure across multiple clouds increases fault-tolerance, allowing for more graceful recovery from cloud provider outages. However, multi-cloud deployments add complexity because each provider has its own interfaces, tools, and workflows. Terraform lets you use the same workflow to manage multiple providers and handle cross-cloud dependencies. This simplifies management and orchestration for large-scale, multi-cloud infrastructures.

e.g Deploying Federated Multi-Cloud Kubernetes Clusters tutorial to provision Kubernetes clusters in both Azure and AWS environments, configure Consul federation with mesh gateways across the two clusters, and deploy microservices across the two clusters to verify federation.

118
Q

terraform private module registry

A

To simplify the management of approved modules, you can host all the approved Terraform modules in your organization’s Private Module Registry (PMR) on Terraform Cloud. The private registry allows you to control access to the modules and ensures they are not publicly available. By implementing PMR, your organization can effectively control and restrict module consumption to only approved modules hosted in the Terraform Private Module Registry. This enhances security, maintains consistency in infrastructure deployments, and reduces the risk of using unverified or potentially harmful modules in your Terraform configurations.

119
Q

The following will persist sensitive data to tf statefile

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

Terraform needs to store these values in your state so that it can tell if you have changed them since the last time you applied your configuration.

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. (Environment variables can end up in log files if TF_LOG is set to TRACE.)

120
Q

~terraform login

A

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.

121
Q

~terraform apply -refresh-only

A

use to reconcile the state with the real-world infrastructure in order to detect any drift from the last-known state

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.

122
Q

~terraform init -upgrade

A

Upgrades 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.

123
Q

~terraform destroy

A

only terminates resources that are specified in the configuration file

124
Q

terraform storage patterns

A

Terraform configuration
Local Terraform - On disk
Terraform Cloud - In linked version control repository, or periodically uploaded via API/CLI

Variable values
Local Terraform - As .tfvars files, as CLI arguments, or in shell environment
Terraform Cloud - In workspace

State
Local Terraform - On disk or in remote backend
Terraform Cloud - In workspace

Credentials and secrets
Local Terraform -In shell environment or entered at prompts
Terraform Cloud - In workspace, stored as sensitive variables

125
Q

Module output

A

output blocks that are created in a module aren’t displayed on the Terraform CLI. Therefore, you need to create an output block in the parent/calling module to output the value while referencing the output in the module.

And the output is referenced with the ~module.xxxx.yyy.attribute

Don’t forget that before you can reference data/values from a module, the module has to have an output declared that references the desired value(s).

126
Q

Terraform Cloud as backend

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.

127
Q

Terraform remote state

A

Terraform does not persist state to the local disk when remote state is in use, and some backends can be configured to encrypt the state data at rest.

128
Q

Multiple Provider blocks

A

Each provider must be in it’s own separate block

129
Q

TFC vs TFE vs OSS

A

Remember that Terraform Cloud and Enterprise also have Workspaces, but they behave slightly differently. In Cloud and Ent, each workspace is still isolated from others, meaning it has its own state. Still, often these workspaces point to different code repositories and use completely different Terraform configuration files.

Meanwhile in terraform OSS, all workspaces have different isolated state files but are linked to thesame configuration file.

130
Q

terraform backend and workspace

A

When using workspaces, you’re essentially using the same Terraform configuration files. Therefore the backend will remain the same for all of your workspaces. That makes this answer incorrect.

131
Q

~ terraform init -reconfigure or -migrate-state

A

Whenever a configuration’s backend changes, you must run terraform init again to validate and configure the backend before you can perform any plans, applies, or state operations. Re-running init with an already-initialized backend will update the working directory to use the new backend settings. Either -reconfigure or -migrate-state must be supplied to update the backend configuration.
When changing backends, Terraform will give you the option to migrate your state to the new backend. This lets you adopt backends without losing any existing state.

132
Q

calling a module variable

A

When using modules, it’s common practice to declare variables outside of the module and pass the value(s) to the child module when it is called by the parent/root module. However, it’s perfectly acceptable to declare a variable inside of a module if you needed. Any variables declared inside of a module are only directly referencable within that module. You can’t directly reference that variable outside of the module. You can, however, create an output in the module to export any values that might be needed outside of the module.

133
Q

Dynamic Block scope

A

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.

134
Q

Constraint a provider

A

When you need to constrain the provider to a specific version, you would do this under the terraform configuration block. Within that block, you would use the required_providers block to set certain configurations, including the version of each provider you want to lockdown.
Note that even though you would add the provider constraint under the terraform block, you may still indeed have a separate provider block to set certain configurations, like credentials, regions, or other settings specific to the provider. Just keep in mind that each distinct block is used for different settings.

135
Q

Keeping secrets on a remote system

A

On the remote system? I don’t think this is even a viable option. The credentialss would need to be read by the local system that is executing Terraform.

136
Q

Terraform state List vs Terraform state show <resource></resource>

A

terraform state list will just show you a list of the resources being managed by Terraform, but it won’t show you details on each of those resources

terraform state show <resource> will show you a lot of details on the resource, including things like the ID, IP address, the state of the resource, and lots more.</resource>

137
Q

tfstate guarantee

A

The one thing that cannot be guaranteed is that the terraform.tfstate file ALWAYS matches the deployed infrastructure since changes can easily be made outside of Terraform. For example, if you deploy a bunch of resources in GCP and nobody makes any changes, then yes, the terraform.tfstate file does match the current state of those resources. However, if an engineer makes a change in the GCP console or CLI, then the terraform.tfstate would NOT match the infrastructure deployed until you ran a terraform apply -refresh-only command.

138
Q

terraform fmt recussive

A

fmt scans the current directory for configuration files and formats them according to the HCP canonical style and format. However, if you need it to also scan and format files in sub-directories, you can use the -recursive flag to instruct terraform fmt to also process files in subdirectories.

139
Q

Where does Terraform Open Source (OSS) store the local state for workspaces?

A

/terraform.tfstate.d/<workspaceName></workspaceName>

140
Q

tfstate sub-command

A

terraform state list - List resources in the state
terraform state mv -Move an item in the state
terraform state pull - Pull current remote state and output to stdout
terraform state push - Update remote state from a local state
terraform state replace-provider Replace provider in the state
terraform state rm - Remove instances from the state
terraform show - Show a resource in the state

141
Q

terraform apply -out=FILE
terraform plan -out=FILE

A

Saved plan/apply plan is a Binary file. It cannot be viewed by high-level applications.

to Apply Config from the plan file,
You can then use ~terraform apply FILE, however, this would not require an approval.

142
Q

backends

A

Standard backends
* only store state
* does not perform terraform operations eg. Terraform apply
* To perform operations vou use the CLI on your local machine
* third-party backends are Standard backends e.g. AWS S3

Enhanced backends
* can both store state
* can perform terraform operations
enhanced backends are subdivided further:
* local - files and data are stored on the local machine executing terraform commands
* remote - files and data are stored in the cloud eg. Terraform Cloud

143
Q
A

Terraform Enterprise supports the following data storage:

PostgresSQL

Any S3-compatible object storage service, GCP Cloud Storage or Azure blob storage meets Terraform Enterprise’s object storage requirements.

144
Q

VCS Provider Support for Terraform Provider

A

GitHub.com
GitHub.com (OAuth)
GitHub Enterprise
GitLab.com
GitLab EE and CE
Bitbucket Cloud
Bitbucket Server
Azure DevOps Server
Azure DevOps Services

145
Q

GitHub is not the supported backend type in Terraform.

A

True

146
Q

Provisioners

A

Provisioners are written inside the resource block

147
Q

terraform apply creates the .tfstatefile

A

True

148
Q

Terraform import

A

Only imports the state, does not genet\rate the config file

149
Q

Sensitive values

A

Sensitive values are still visible in statefile

150
Q

Locals

A

The locals block defines one or more local variables within a module. Each locals block can have as many locals as needed.

151
Q

Output Values

A

Output values make information about your infrastructure available on the command line, and can expose information for other Terraform configurations to use. Output values are similar to return values in programming languages.

152
Q
A