Terrraform Flashcards

1
Q

Terraform Installation

A

Note for using Binary Installation(GUI) method as against package manager(CLI).

Terraform must be installed into the /usr/local/bin/terraform folder.

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

Terraform Binary File Location

A

command:
$ which terraform

Expected result:
/usr/local/bin/terraform

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

VM Configurations Musts

A

CPU
Memory
Storage
OS

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

Minimal requirement for Instance creation

A

resource “RESOURCE NAME” “INSTANCE NAME” {
ami = “ami-0230bdFD60aa48260c6”
Instance_Type = “t2.micro”

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

Required Block

A

Provider block is the only required block. All other blocks can be changed

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

Terraform init

A

Downloads the provider plugins defined in the provider block of your code

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

A single Terraform Directory can contain morethan one provider plugin

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

Required_provider block

A

This specification must be explicitly defined in the provider block to enable terraform plugin daemon to look for the plugins required for that provider. For providers that are not maintained by HashiCorp.

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

Hashicorp maintained provider

A

This can be in the direct form: provider: “aws”
However if it is not a HashiCorp maintained(a community based or individual ) provider, the the required_proider block must be used.

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

Terraform destroy in a multicloud directory

A

use the -target flag

Syntax
- target resource_type + local resource name

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

terraform apply on a blank code

A

is equal to terraform destroy, however this can be used to remove specific resources from a deployment

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

terraform state file

A

a metadata file that stores the details of the physical result of a running physical deployment. However whenever a resource is destroyed, the statefile is also destroyed.

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

Terraform command and directory files

A

terraform commands work on all deployment codes in its directory. ie, it can deploy to multiple platforms with a single terraform plan command.

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

Statefile Warning

A

DO NOT EDIT A STATEFILE

STORE A BACKUP COPY OF YOUR

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

Terraform code is also known as Desire at State.
While the state file can be called the current state

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

Terraform refresh

A

Terraform refresh synchronizes the current state and statefile, giving an opportunity for Terraform plan to update you on what you are about to destroy or create.

Note:
terraform refresh functionality is intrinsic, does not requre a manual declaration

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

Provider version

A

Terraform init will download the version of provider specified in the provider block. This specification is very necessary in order to avoid infrastructure mismatch.

> = 1.0
~> 3.0 - any version in the 3x range.
=2, <=3.5

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

Terraform version best practice

A

best to define a specific provider version, a vague version(eg ~>x) , leaves room for terraform downloading even beta versions, and thereby affecting your resource.

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

.terraform.lock.hcl

A

The terraform dependency lock file in our terraform directory restricts terraform to the chosen or preffered plugin version it downloaded during terraform init

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

terraform init -upgrade

A

this flag added to the terraform init command bypasses and downloads the newer dependency/plugin version within the specified version range.
Also note that the upgrade can either be an upward or downward upgrade.

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

terraform apply -auto-approve

A

this tag bypasses the need for an approval before deployment

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

Credentials and security concerns

A

It is a dangerous practice to declare configuration files or their path in a tf document/code.
If these lines are not added to the provider block, Terraform will locate these files at HOME/.aws/config
and HOME/.aws/credentials
on Linux and macOS. And USERPROFILE%.aws\config,
you have a USERPROFILE%.aws\credentials
for windows

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

aws configure (command on aws CLI)

A

This command applies and creates the relevant directories to store aws credentials; ie,

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

attribute

A

characteristics/contents of values generated in a deployment process

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

Outputs

A

this statement fetches and presents artifactes generated from a deployment to the user for further use

Syntax

output “StringName” {
value = resourcename.attributeName
}

*eg. for ec2 instance deployment

output “public_ip” {
value = aws_instance.web.public_ip

}

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

variables.tf

A

values are stored in this file and called upon within the terraform code using the var.variableName function.

eg.
In Variable.tf
variable “vpn_ip” {
default = “116.50.30.50/32”
}

in file.tf value_of_x = [var.vpn_ip]

the result of the above will be the value of default. ie,
value_of_x = 116.50.30.50/32

note that terraform compiler takes note of every file within the working directory.

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

Resource Syntax

A

resource “resource_name” “local_name” {
item = “item value”
}

28
Q

Variable assignment types

A
  1. Environment Variables
  2. Command line flags(if you leave the variable value blank, the CLI will prompt you for it.
  3. From a file
  4. Variable Defaults(set by user)
29
Q

Tags

A

you can tag all resources.

Syntax:

tags = {
Name = var.sg_name
}

30
Q

Terraform DataTypes

A

String
List
Map
Number

31
Q

List and Map Syntax

A

items on lists are identified by their index(position)

eg.
variable “list” {
default = [“t2.micro”, “t3.micro”, “t4.micro”]
}

==» var.list[“0”]
the above line will return t2.micro.

Items in maps are identified by calling their key in other to get their value
eg.
variable “types” {
type = map
default = {
us-east-1 = “t2.micro”
us-east-2 = “t4.micro”
eu-west-2 = “t2.medium”
}

==» var.types [“eu-west-2”]
the above line will return t2.medium

32
Q

Count.index parameter

A

This is used to iterate through data structure, and during each iteration, adds a unique suffix to the items found.

Syntax
count = n

Example:
1. resource “aws_instance” “web” {
2. ami = var.ami
3. instance_type = var.types[“us-east-1”]
4. count = 20
5. tags ={
6. key = “name”
7. Value = “Web_instance${count.index}”}

The above code will return
20 instances with the name *Web_instance1, Web_instance2, Web_instance3,…….Web_instance20

example2

33
Q

terraform.tfvars

A

this file is a store for variable inputs, thereby making it unnecessary to enter user input variables into configuration code or at runtime or through other means.

34
Q

terraform conditionals

A

eg
declare variable:
variable “istest” {
}

call conditional variable:
count = var.istest == true ? 1:0

35
Q

Local Values

A

ChatGPT
Not exactly. Local values in Terraform provide a way to create reusable expressions within your Terraform configuration. They are a mechanism for assigning a name to an expression and then referencing that name elsewhere in your code.

A local value is defined using the locals block, and it allows you to simplify and reuse complex expressions. It doesn’t introduce a new variable; instead, it’s a way to give a name to an expression. The local value is evaluated once and can be referred to by its name throughout your Terraform configuration.

eg
locals {
subnet_count = 3
subnet_cidr_blocks = [
for i in range(local.subnet_count) :
cidrsubnet(“10.0.0.0/24”, 8, i)
]
}

resource “aws_subnet” “example” {
count = local.subnet_count

cidr_block = local.subnet_cidr_blocks[count.index]
# other subnet configuration…
}

36
Q

Functions

A

Syntax:

Function(Argument1,Argument2)

eg
~ max(2,12,5)
12

37
Q

DAta Source

A
38
Q

Terraform Log

A

Syntax
TF_LOG=TRACE - This prints deployment logs on terminal screen.

TF_LOG_PATH=fullPathName

Log Level
TRACE
ERROR
DEBUG
INFO
WARN

39
Q

Terraform fmt

A

Terraform format can be used to format indentation issues

40
Q

terraform validate

A

Terraform plan is a combination of terraform Validate and Terraform LOG

41
Q

Lookup function

A

The lookup function in Terraform is used to retrieve the value of a specified key from a map given its key.

Syntax:

function({a=”Map Value1”, b=”Map Value2”} “desired value”, “Default value”)

42
Q

Element Function

A

retrieves items from a list.

Syntax:
element(list, index)

eg
~ element([a,b,c,d], 1)
> b

43
Q

terraform apply -replace

A

~ terraform apply -replace resource name

used to force destruction and replacement of a resource that has been manually altered and unwanted.

44
Q

DYNAMIC BLOCK

A
45
Q

terraform graph

A
46
Q

Saving Terraform plan

A

Syntax:

~ terraform apply -out=fileName

The command “terraform plan -out=dx1” is used to create an execution plan in Terraform and save it to a file named “dx1”.

When you run the “terraform plan” command, Terraform examines your configuration files, compares them against the current state of your infrastructure, and generates an execution plan that outlines the changes it will make to achieve the desired state. By specifying the “-out” flag followed by a filename, you can save this execution plan to a file for later use.

In this case, the execution plan will be saved to a file named “dx1”. You can use this file later with the terraform apply command to apply the changes outlined in the plan. For example, you can run terraform apply dx1 to apply the plan stored in the “dx1” file.

It’s important to note that the “terraform plan” command doesn’t make any changes to your infrastructure. It only generates an execution plan. To apply the changes and make modifications to your infrastructure, you need to use the “terraform apply” command.

47
Q

Terraform output

A

Terraform output parameters/attributes can always be accessed via terraform plan(don’t apply).
This is because the output is locally saved inside the .tfstate file. so, whenever the terraform plan is called, it will display the output attributes fetched from the initial installation.

48
Q

Api count concerns

A

during every terraform plan call API calls are also made to the applications. And in larger deployments, API limits can be hit easily during testing, so you want to make sure to minimize APi calls.
The following techniques can be used to help contain this:

using the

  1. ~ terraform plan -refresh=false flag
  2. ~ terraform plan -target=TargetResourceName
49
Q

Zipmap

A

constructs a map from a list of keys and a list of values.
eg.

**variable “colors” {
default = [“green”, “red”, “Orange”]
}

variable “fruits” {
default = [“Apple”, “Strawberry”, “Pineapple”]
}

output “color_fruit_map” {
value = zipmap(var.colors, var.fruits)
}
***

> {
green = “Apple”
red = “Strawberry”
Orange = “Pineapple”
}

zipmap([“green”,”red”,”Orange”], [“Apple”, “Strawberry”, “Pineapple”])

50
Q

Terraform behavior with code alteration

A
  1. When a resource block is deleted from the configuration file, Terraform assumes you no longer need them, it deletes them at the next terraform apply. This happens regardless of if the resource is in the state file.
  2. update to a resource component/attributeTerraform:
    performs in-place update on resource updates, such as a change in security group ports, change in instance tags.
  3. major Api changes:
    such as in change of an AMI, such changes can not be updated, therefore terraform will destroy and recreate the previous instance due to un-updateable AMI.
51
Q

Terraform Drift

A

Terraform operates based on the desired state declared in your configuration files. If there are manual changes made outside of Terraform, such as modifications directly through the AWS Management Console or other means, Terraform might encounter difficulties because its own state won’t match the actual state of the resources.

Here’s how Terraform typically handles these situations:

Terraform State File Mismatch: If changes are made manually, Terraform won’t be aware of them. When you run a terraform apply or any other command that needs to reconcile the desired state with the actual state, Terraform will detect a mismatch between its state file and the actual resources.
Conflicts and Drifts: Terraform will recognize the differences between the declared state and the actual state as drift or conflict. It will show you an error or warning message indicating that there are changes outside of Terraform’s control.
Resolution: In order to proceed, you typically have a few options:
Import Resources: You can use the terraform import command to bring the existing resources under Terraform management. This helps Terraform recognize and manage these resources.
Update Configuration: If the changes made manually are valid and desired, you may choose to update your Terraform configuration to reflect the actual state. This helps Terraform consider the changes as part of its managed infrastructure.
Reconciliation: Once the Terraform state is synchronized with the actual state, subsequent runs of terraform apply should not encounter issues related to drift or conflicts.
It’s essential to be cautious when manually modifying resources managed by Terraform, as this can lead to unexpected behavior and difficulties in maintaining infrastructure as code practices. Always aim to make changes through Terraform whenever possible to maintain consistency and manageability.

52
Q

Terraform Meta-Argument

A
  • Depends_on - Handle hidden resource or module dependencies that Terraform cannot automatically infer.
  • count - Accepts a whole number, and creates that many instances of the resource
  • for_each - Accepts a map or a set of strings, and creates an instance for each item in that map or set.
  • lifecycle - Allows modification of the resource lifecycle.
  • provider - Specifies which provider configuration to use for a resource, overriding Terraform’s default behavior of selecting one based on the resource type name
53
Q

Terraform Meta-Argument

LifeCycle Block

A
  • ignore_changes = boolean_value
  • create_before_destroy = boolean_value
  • prevent_destroy = boolean_value
  • ignore_changes[attribute1, attribute2,attribute3]
  • replace_triggered_by

Syntax:

~ lifecycle {
argument_option = [attribute]

}

…the above used to specify attributes and resources to be ignored during terraform apply.

Note that this block is resource specific, therefore must be part of a target resource block

54
Q

Count Parameter

A

For replication, scaling of identical resources

use for_each parameter if each item would be unique

55
Q

~toset

A

used to force deduplication of elements in a set

56
Q

module style

A

a modular configuration style that involves breaking terraform resources into small .tf files and accessing them via a Module block.
Syntax:
module “any_name” {
source = resource_folder_path/}

However, it is advisable to separate modules into sub-directories.

Modular configuration/programming helps to keep code simple, readable, and maintainable.

Values and attributes of resources are hardcoded in the module source and cannot be changed in the target block, however, with an exception to variables; if the source attribute is a variable(var.xy.z), it can be changed in the target configuration from it’s variable default.

Use of locals block
i.e,
locals {
attribute = value
}

can be used to store temporary variables within thesame source module file that can not be overwritten.

57
Q

Modular configuration note

A

Modular Configuration in Terraform

In Terraform, a modular configuration style involves breaking down resources into smaller .tf files and accessing them using the module block. This approach enhances code organization, readability, and maintainability.

Syntax:

hcl
Copy code
module “any_name” {
source = “resource_folder_path/”
}
It is recommended to further organize modules into sub-directories for a cleaner project structure.

Key Points:

Modularization simplifies code structure and promotes maintainability.
Resources are separated into smaller modules for better organization.
The module block is used to reference these modules in the main configuration.
Attributes and values of resources in modules are typically hardcoded in the module source.
Variables in the module source can be overridden in the reference block using variable defaults.
Example:

hcl
Copy code
// Module Definition (example_module.tf)
resource “aws_instance” “example_instance” {
ami = var.ami
instance_type = var.instance_type
// … other configurations
}

// Reference in Main Configuration
module “example” {
source = “./modules/example_module”
ami = “ami-12345678” // Variable override
instance_type = “t2.micro” // Variable override
// … other variable assignments
}
This modular approach enhances code maintainability, supports reusability, and facilitates collaboration on larger Terraform projects.

58
Q

Terraform - Git

A

Do not hardcode your secrets in your configuration

Even if your Passwords are encapsulated in a file function(file(x/y/dfg), tf statefilecaptures the decrypted password.

**Therefore,it is highly recommended NOT to push terraform statefile to git.

59
Q

Terraform module source

A

module sources could be
- Local
- URL (can also be a git url)

in a Local source, the pathName must be either in a parent of the configuration folder, or the grand parent, ie

source = ./../a/b/x.c

preceded by either the “ ./ “ or the “ ../ “

Any Git url are supported. both http and ssh
eg.
source = git::http://DanielAmanyi.vpc.git
source = git::ssh://DanielAmanyi.rds.git

60
Q

Terraform and git ignore

A

.terraform
terraform.tvars
terraform.tfstate
crash.log

The above files may contain delicate information that are npt safe for sharing. Therefore shoud be added to .gitignore

61
Q

Terraform Backend

A

storage for terraform state.

  1. Local
  2. Remote (eg. git, Dynamodb or S3)

terraform {
backend = “s3” {
bucket = “ xnxnxnxx “
key = “path/to/key”
region = “abj-east-5”
}
}

62
Q

S3 Backend Limitation

A

S3 backend does not support state locking, hence, dynamodb is used alongwith S3 to achieve the state locking

63
Q

terraform state file management

A

State management could be done with the following commands:

terraform state [subcommands]

Subcommands
- list - lists resources within terraform state
- mv - used to move or rename resources within statefile
- pull - manually download and output the state from a remote state.
- push - manually upload a local statefile to a remote state
- rm - removes item from the terraform state
show - show the attribute of a single resource in the state.

64
Q

terraform import

A

Syntax
.tf FILE

import {
to = new_resource_block_name
id = “resourceID
}

CLI
~ terraform plan -generate-config-out=AnyfileName.tf

65
Q

terraform remote backend operations

A

This operation can either be driven by
- CLI
- VCS

in either ways, terraform operations is streamed synchronously to the Terraform cloud. CLI commands are also run on terraform cloud console and vise versa.

using the VCS-driven, terraform cloud responds promptly to git commits by picking up the committed configuration and starts to update (Plan).

66
Q

terraform best practices

A
  1. Be sure you are working with the correct version
  2. Use Terraform fmt
  3. Use Terraform validate instead of terraform plan (minimize using your API quota)
  4. Avoid hard-coding stuff (use variables)
  5. Use of folder structure (have each resource block in a separate file to ease maintenance and usability.
  6. Use comments block to guide future readability
  7. Use tags (mainly the Name, Environment, and Team
67
Q
A