Terraform
Terraform Modules
- Can centralize the terraform resources and call out TF files whenever required
List
A sequence of values identified by consecutive whole numbers starting with zero. The keyword list is a shorthand for list (any), which accepts any element type as long as every element is the same type
Refer to the following CLI Code: locals { db_password = { admin = "password" } } output "db_password" { value = local.db_password } Whenever a terraform apply operation runs, the value of password is shown in the CLI. What is the easiest way to hide the value from CLI?
Use a sensitive parameter
James has decided to not use the terraform.tfvars file, instead, he wants to store all data into custom.tfvars file? Is it possible?
Yes - This will work however user will have to explicitly specify the tfvars file during the apply operation..... Sample Commond: terraform apply -var-file="custom.tfvars"
Are there any different ways to destroy the resources without needing to run terraform destroy command?
Yes - You can also simply remove the resource configuration from your code and run Terraform apply. This will also destroy the resource
James has decided to not use the terraform.tfvars file, instead, he wants to store all data into custom.tfvars file? How can he deal with this use-case while running terraform plan?
terraform plan -var-file="custom.tfvars"
Medium Corp is using Terraform Workspace feature. After the "terraform apply" is completed, the terraform.tfstate file does not appear in the main project directory. In which directory is the terraform.tfstate file created?
terraform.tfstate.d
Variable definition precedence
- Environment variables - terraform.tfvars file, if present - terraform.tfvars.json file, if present - any *.auto.tfvars or *.auto.tfvars.json files, processed in lexical order of their filenames - Any -var and -var-file options on the command line, in the order they are provided - If the same variable is assigned multiple values, TF usees the last value it finds
Terraform Lock
- If supported by your backend, Terraform will lock your state for all operations that could write state - Terraform has a force-unlock command to manually unlock the state if unlocking fails (this should only be used as a last resort)
Sentinel
- An embedded policy-as-code framework integrated with Hashicorp - Can be used for variety of things: - Verify if EC2 instance has tags - Verify if the S3 bucket has encryption enabled General Logic: Terraform Plan ----> Sentinel Checks ----> Terraform Apply
Local Values
- Assigns a name to an expression, allowing it to be used multiple times within a module without repeating it. - Can be used to refer to other locals, but cannot refer to itself or to a variable that refers (directly or indirectly) back to it. - Recommended to group together logically-related local values into a single block
Misc pointers - 1
- Benefits of IAC: Automation, Versioning and Reusability
Terraform Unlock
- If supported by your backend, can lock state for all operations that could write state - Not supported by all backends - Can manually unlock the state if unlocking failed(not recommended to do)
Misc - 4
- If you already run your own Vault cluster in prod, you can configure TF Enterprise to use that one, instead of running its own internal vault instance
Terraform Registry
- Integrated directly into Terraform <NAMESPACE>/<NAME>/<PROVIDER> hashicorp/consul/aws
Provisioner - Failure behavior
- By default the provisioning failure will cause the TF apply to fail - Can bypass this with the on_failure setting. 1) Continue: Ignores the errors and continues with creation or destruction 2) Fail: Raises an error and stops applying. If this is a creation provisioner, taints the resource
Terraform taint
- Can be used to taint resources within a module - Terraform taint [options] address - EX: Terraform taint "module.couchbase.aws_instance.cb_node[9]" Multiple sub modules, following syntax-based example can be used - Module.foo.module.bar.aws_instance.qux
Count and Count Index
- Can simplify configs and allow you to scale resources by incrementing a number - In resource blocks where the count is set, an additional count object (count.index) allows you to modify the configuration of each instance
Private Registry
- Can use modules from private registry too, like Terraform Cloud Have source strings of the following form: <HOSTNAME>/<NAMESPACE>/<NAME>/<PROVIDER> - While fetching a module, having a version is required
Backend Configuration
- Configured directly in TF files and has to be initialized
Data Source Code
- Data sources allow data to be fetched or computed for use elsewhere in Terraform configuration - Reads from a specific data source (aws_ami) and exports results under "app_ami" pg 137
Resource Block
- Describes one or more infrastructure objects, such as virtual networks, DNS records etc. - A resource block declares a resource of a given type ("aws_instance") with a given local name ("web")
Debugging Terraform
- Detailed logs that can be enabled by setting the TF_LOG env variable to any value - TF_LOG can be set to 1) Trace 2) Debug 3) Info 4) Warn 5) Error - To persist logged output, you can set TF_LOG_PATH
Terraform Workspaces
- Managed with the TF workspace set of commands - State File Directory = terraform.tfstate.d - Not suitable for isolation for strong separation between workspaces (stage/prod) - Create new workspace: Terraform workspace new ablabs - Switch to a specific workspace: Terraform workspace select prod
Suppressing Values in CLI Output
- Output value can be marked as sensitive using the sensitive argument. This prevents TF from showing its value in the list of output at the end of Terraform Apply. - However, this does not prevent the information from being seen in the state file
Module - Accessing Output Values
- Resources defined in a module cannot be accessed by calling modules directly. - However, child module can declare output values to selectively export certain values to be accessed by the calling module
Misc Pointers - 2
- Sentinel is a proactive service - TF refresh does not modify infra, just the state file - Slice function is not part of the string function... join, split and chomp are - Not mandatory to include the module version while pulling code from TF registry
Explicit Dependency
- Specifying a dependency is only necessary when a resource relies on some other resource's behavior but doesn't access any of that resource's data in its arguments
TF Cloud Remote Backend
- Stores TF state and may be used to run operations in TF Cloud - When using full remote operations, ops like TF plan or TF apply can be executed in TF cloud's run ENV, with log output streaming to the local terminal
Implicit Dependency
- TF can automatically find references of the object and create an implicit ordering requirement between the two resources
Required Providers
- TF modules must declare which providers it requires and must be declared in a required_providers block
Terraform Output
- Used to extract the value of an output variable from the state file
If a user directly runs terraform apply without running the terraform plan, will the apply operation fail?
No - When you run terraform apply without passing a saved plan file, Terraform automatically creates a new execution plan as if you had run Terraform plan, prompts you to approve that plan and takes the indicated actions
Matt has a requirement to reference a local value to another local value in the same terraform code. Is this feature supported in Terraform?
Yes - The locals block defines one or more local variables within a module. Each locals block can have as many local as needed
Alice has added a simple variable definition in Terraform code. variable "kpnumber" { default = 3 } Alice has also have a defined the following environment variable: TF_kpnumber=6, TF_VAR_kpnumber=9. There is also a terraform.tfvars file with the following contents kpnumber = 7 When you run the following apply command, what is the value assigned to the number variable? terraform apply -var kpnumber=4
4
Which among the following allows constructing a set of nested configuration blocks?
Dynamic blocks
James needs to make use of the module within his terraform code. Should the module always need to be public and open-source to be able to be used?
False
Bob intends to pull the Terraform Module associated with AWS VPC. In the line 3, there is a version argument that is defined. Is it a mandatory requirement to specify version while pulling code from Terraform Registry? module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "3.14.2" }
False - If we do not specify the version argument, Terraform will download the newest version of the module
What does the following data represents in Terraform? max min element join concat file
Functions
Where do we define provisioner block in Terraform? resource "aws_instance" "myec2" { ami = "ami-082b5a644766e0e6f" instance_type = "t2.micro" }
Inside the resource block
A variable named demo has following value. What is the data type of the variable? demo = ["admin","alice"]
List - List represents a sequence of values, like ["us-west-1a", "us-west-1c]
Alice is writing a module and within the module, there are multiple places where she has defined the same set of Terraform expression. Whenever there is modification required in the expression, Alice has to go through multiple places in the code and modify everywhere. What is a better approach to dealing with this?
Local Values
Matthew is writing a module and within the module, there are multiple places where he has to use the same conditional expression but he wants to avoid repeating the same values or expressions multiple times in a configuration. What is a better approach to dealing with this?
Local Values
Based on the following lookup function example, what is the data type that is referenced? lookup({a="ay", b="bee"}, "a", "what?")
Map
Do all the backends that are supported in Terraform has the state locking functionality?
No
Matthew has referred to a child module that has the following code. resource "aws_instance" "myec2" { ami = "ami-082b5a644766e0e6f" instance_type = "t2.micro } Can Matthew override the instance_type from t2.micro to t2.large from the ROOT module directly?
No
Does terraform refresh perform any kind of modification on the running infrastructure?
No - The terraform refresh command reads the current settings from all managed remote objects and updates the Terraform state to match
Matthew has written the configuration file of a manually created EC2 instance in Terraform. Following is the code: resource "aws_instance" "myec2" { ami = "ami-bf5540df" instance_type = "t2.micro" vpc_security_group_ids = ["sg-6ae7d613", "sg-53370035"] key_name = "remotepractical" subnet_id = "subnet-9e3cfbc5" tags { Name = "manual" } } The instance id of the manually created EC2 instance is i-041886ebb7e9bd20 How he can import data of that EC2 to the state file and link it with the resource block?
Terraform import aws_instance.myec2 i-041886ebb7e9bd20
Matthew works as a DevOps Engineer in Enterprise Corp. Whenever he runs operations like terraform plan, terraform apply, it takes a lot of time. What can be the issue behind this?
Terraform performs sync for all resources in the state file by default for every plan and apply. If there are a lot of resources, it can slow down the operation
Alice has started to make use of Terraform Cloud Workspace and has linked a Git Repository to it. Whenever a new code change is committed to version control repository, will Terraform automatically run the terraform plan operation?
True
Following is the sample Child module configuration: resource "aws_instance" "myec2" { ami = "ami-082b5a644766e0e6f" instance_type = var.instance_type } variable instance_type {} If this module is called from a ROOT module, can the user set the value associated with variable of instance_type?
True
Due to some issues, the state file is in the locked state and users are not able to perform terraform apply operations further. What actions can be taken to overcome this?
Use the terraform force-unlock
A variable name "update" must only support boolean value. How can we define the type of value that is expected for a specific variable?
Use type in variable block
Alice has written a Terraform code for creating a new EC2 instance. There is a requirement that before EC2 instance is created, a public IP must first be created. What functionality of Terraform must be used to ensure this?
depends_on
Quiz 2 start: Following is an exert of the code which Alice has written. There is a reference to count.index in Tags. variable "tags" { type = list default = ["firstec2","secondec2","thirdec2"] } tags = { Name = element(var.tags,count.index) } If count.index is set to 1, which of the following values will be used?
secondec2 - Count.index counts the distrinct index number (starting with 0)
John is an intern and he had recently created an EC2 instance manually. Can he import the EC2 instance to Terraform without having to write a terraform configuration file for that EC2 instance from scratch?
No - The current implementation of Terraform import can only import resources into the state. It does not generate configuration. A future version of Terraform will also generate configuration
John is working as a DevOps Engineer and is managing the Terraform Infrastructure. Based on a new requirement, John has to create a new security group (firewall) and 60 different ports needs to be whitelisted in this firewall. John wants to avoid writing 60 different ingress blocks and maintain (add/remove) whenever a new IP address need to be added or removed in the subsequent updates. ingress { description = "kplabs-sg" from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = 172.31.0.5 } Which Terraform functionality can John use to minimize the overall Terraform code that can also be managed easily?
Dynamic Block
Matthew is trying to achieve a use-case that is not directly supported by default Terraform functions that are available. Can Matthew create his own set of function that his team can use for custom use-cases?
False - The Terraform language does not support user-defined functions, and so only the functions built into the language are available for use
If there is any disperency between the current and desired state of the infrastructure, can terraform validate command display the issue?
False - The terraform validate command validates the configuration files in a directory, referring only to the configuration and not accessing any remote services such as remote state, provider APIs, etc.
Matthew has created a new workspace named "DEV". Do Matthew needs to manually switch to the DEV workspace in order to start using it?
False -By default, when you create a new workspace you are automatically switched to it
Following are the output values defined in Child and Root Module: Child Module output "child_module" { value = "This is Child Module" } Root Module: output "root_module" { value = "This is ROOT Module" } On a terraform apply, which output values will be displayed?
Output values of Root Module
Enterprise Corp has a Terraform State file that contains details related to 100s of resources that are currently created in their Cloud Infrastructure. There is a requirement to quickly list all the resources that are part of the state file. What is the best way to achieve this?
Terraform State list
Matthew has created an EC2 instance via Terraform. Matthew has defined the following rules within the security group: Port 443 allowed from 0.0.0.0/0 Port 22 allowed from 125.36.50.23/32 John has added the following rule manually: Port 80 allowed from 0.0.0.0/0 Next time when Matthew runs a terraform plan, what will happen?
Terraform plan will show output to remove the manually created rule
TF and GIT - 1
- .gitignore should be configured to ignore certain TF files that might contain sensitive data
Version Arguments
- >= 1.0 Greater than equal to - <=1.0 Less than equal to - ~>2.0 Any version in that range - >=2.10,<=2.30 Any version between
When a terraform apply operation is performed, which of these operations are performed?
Terraform will match the current state to desired state
Required Version
- Accepts a version constraint string, which specifies the version of TF to be used with your config - If the running version of TF doesn't match with the specified constraints, TF will produce an error and exit without taking any further actions
Structural Data Types
- Allow multiple values of several distinct types to be grouped together as a single value - List contains multiple values of same type, while object can contain multiple values of different types
Terraform workspaces
- Allows different sets of environment variables. - Workspaces allow multiple state files of a single configuration
Splat expressions
- Allows us to get a list of all the attributes.... like wildcard in AWS search (asterisk)
Terraform Provider alias
- Allows you to have multiple providers instances. - Provider block without alias is known as the default provider configuration.
Terraform provisioners
- Can be used to model specific actions on the local machine or on a remote machine to prepare servers or other infra objects for service. - Should only be used as a last resort - Provisioners are inside the resource block - Have an overview of local and remote provisioner
Terraform Import
- Can import existing infra and bring it under terraform mgmt..... IT DOES NOT generate config files(YET), because of this it is necessary to write a resource configuration block manually for the resource, to which the imported object will be mapped
Dealing with larger infra
- Cloud providers have rate limits set - Break larger configs into smaller configs that can be independently applied - Can make use of -refresh=false and target flag for a workaround (not recommended)
Provider configuration
- Don't need provider when running locals code block.... just running tf code on local machine and not accessing AWS
Provisioner - Local
- Invokes a local executable after a resource is created. Invoking a process on the machine, not the resource
TF Local Backend
- Local backend stores state on the local filesystem, locks that state using system APIs and performs operations locally - By default, TF uses the "local" backend, which is the normal behavior of TF
Miscellaneous Pointers
- Lookup retrieves the value of a single element from a map EX: Lookup (map, key, default) - Various commands run terraform refresh implicitly, such as TF plan, apply and destroy. Others like TF init and import do not. Array data type is not supported in Terraform
Modules - Root and Child
- Main module is known as root module and consists of the resource defined in the .tf files in the main working directory - Modules can call other modules, which let you include the child module's resources into the configuration in a concise way. - A module that includes a module block like this is the calling module of the child module.
Sensitive Data in TF state file
- Manage any TF state file with sensitive data as a sensitive data set within itself - TF Cloud always encrypts the state at rest and protects with TLS in transit
TF Taint
- Manually marks a TF-managed resource as tainted, forcing it to be destroyed and recreated on the next apply. - Once tainted, the next plan will show the resource being destroyed, created and then the next apply will implement
Credentials in Config
- Not recommended to hard code credentials - Store creds outside of TF config - Store creds as part of ENV variables
Terraform functions
- Number of built-in values to transform and combine values (Ex: max(5,12,9)) - Terraform does not support user-defined functions -Be aware of functions like element, lookup
Module Versions
- Recommended to explicitly constrain acceptable version numbers for each external module to avoid unexpected/wanted changes - Version constraints are only supported for modules installed from a module registry
Terraform Providers
- Responsible for understanding API interactions and exposing resources. - Correspond with one cloud or on-premises infrastructure platform. -Explicitly set Versions within the block
Terraform Format
- Rewrites TF config files to a canonical format and style - Use Case: When all the configs written by team members need to have a proper style of code
Terraform Enterprise advantages compared to TF Cloud
- SSO - Auditing - Private Data Center Networking - Clustering Team & Governance feats are not available for TF Cloud Free
Misc - 3
- Terraform console command provides an interactive console for evaluating expressions - Difference between TF version 0.11 and 0.12 - "4{var.instance_type}" ---> 0.11 - var.instance_type --> 0.12
Misc Pointers - 3
- Try not to overuse dynamic blocks, it can make configs hard to read and maintain - Terraform apply can change, destroy and provision resources but cannot import any resource
Terraform Destroy
- Used to destroy terraform-managed infrastructure - Can run destroy to remove managed infra or you can remove the resource block and run terraform apply to remove the managed infra(Trying to match the desired state of the tf file)
TF Graph
- Used to generate visual rep of a config or execution plan. Output is in DOT format
Terraform init
- Used to initialize a working directory containing Terraform configuration files - During init, config is searched for module blocks and the source code is retrieved from the locations given in their source arguments. - Will not create any sample files like example.tf
terraform refresh
- Used to reconcile the state file with the real-world infrastructure - Does not modify infrastructure but does modify the state file.
Misc - 2
- Various variable definite files will be loaded automatically in TF - 1) Terraform.tfvars - 2) Terraform.tfvars.json - 3) Any files with names ending in .auto.tfvars.json - Explicit and implicit dependency info is stored in terraform.tfstate file - Terraform init -upgrade updates all previously installed plugins to the newest version
Terraform validate
- Verifies whether a configuration is syntactically valid and thus primarily used for general verification of reusable modules, including the correctness of attribute names and value types. - Safe to run automatically as part of post-save checks in text editors or a test step for a reusable module in a CI system. - Can be ran before Terraform plan - Validation requires an initialized working directory with any referenced plugins and modules installed
Variables with undefined values
- Will not directly result in an error - TF will ask you to supply the value associated with them
Terraform Module Sources
- module installer supports installs from different source types like local paths, TF registry, Github, S3 and others - Local path references allow factoring out portions of a configuration within a single source repository - Local path must begin with either ./ or ../ to indicate that a local path is intended
Misc - 6
1) Github is not the supported backend type in Terraform 2) When running Terraform init, the plugins are downloaded in the sub-directory of the present working directory at the path of .terraform/plugins 3) API and CLI access for Terraform Cloud can be managed through API tokens that cna be generated from TF CLoud UI 4) Terraform ses Parallelism to reduce the time it takes to create the resource. By default this value is set to 10 5) Terraform recommends using an Indent two spaces for each nesting level 6) .terraformrc and terraform.rc are the two CLI configuration files for TF 7) The terraform get command is used to download and update modules mentioned in the root module 8) The Sentinel command-line interface allows for the developing and testing of policies outside of a particular Sentinel implementation 9) -out=FILENAME is the flag to save a plan to a file 10) Name of the Default State File: terraform.tfstate
VCS Provider Support for Terraform Provider
1) Github.com 2) Github.com (OAuth) 3) GitHub Enterprise 4) Gitlab.com 5) Gitlab EE and CE 6) Bitbucket Cloud 7) Bitbucket Server 8) Azure DevOps Server 9) Azure DevOps Services
terraform init -upgrade
Allows you to upgrade to the latest acceptable version of each provider.
TF and GIT - 2
Arbitrary git repos can be used by prefixing the address with the special git::prefix followed by a valid Git URL to select one of the supported Git protocols Ex: source = "git::https://example.com/vpc.git
Terraform Enterprise
Before mid-2019 all distributions of TF Cloud used to be called TF Enterprise; the self-hosted distribution was called Private Terraform Enterprise (PTFE) - Supports the following data storage: 1) PostgresSQL 2) Any S3 compatible object storage service, GCP Cloud Storage or Azure blob storage meets TF Enterprise's object storage requirements
ENV Variables
Can be used to set variables - Format: TF_VAR_name - Export TF_VAR_region=us-west-1
Variable Names
Cannot use all words within variable names. Terraform reserves some additional names that can no longer be used as input variable names for modules: 1) Count 2) depends_on 3) for_each 4) lifecycle 5) providers 6) source
There is something wrong with the Terraform version that Alice is using. The HashiCorp team has requested to store the crash logs to a file and send the file over email. What is the way for Alice to store the logs to a file named /tmp/kplabs-tf-crash.log
Create an environment variable name TF_LOG_PATH=/tmp/kplabs-tf-crash.log
James is having an issue with his Terraform code. As part of the troubleshooting process, he intends to enable debugging. What is the way to do that?
Create an environment variable of TF_LOG=TRACE - https://www.terraform.io/internals/debugging
Enterprise Corp has started using Terraform Cloud. There are multiple teams that makes use of Terraform and every team is using their custom Terraform resource configuration and settings for resources like EC2 Instances, IAM users and others. You want to enforce standardization of the resources across the enterprise. What should be your approach?
Create central modules associated with EC2 and other resources and ask team to use that
Provisioner Types
Creation-time: Only ran during creation, not during updating or any other lifecycle. If it fails, the resource is marked as tainted Destroy-time: Ran before the resource is destroyed
There are 3 team members working in DevOps Team. From the Terraform documentation, they read that if there are multiple writes happening in Terraform state file from different users, it can corrupt the state. To prevent this, Terraform state file lock must be used. Is there a additional terraform code required to implement this functionality with local backend?
False - State locking happens automatically on all operations that could write state
Backend Config type - 1
First time Configuration: When configuring backend for first time ( no backend to an explicitly defined one) TF will give you the option to migrate your state to the new backend.
Matthew has studied that terraform apply is capable of performing wide variety of operations. However which is the following type of operation that terraform apply cannot do?
Import infrastructure Objects - To import existing infrastructure, you need to run the "terraform import" command
Index Function
Index finds the element index for a given value in a list
Provisioner - Remote
Invokes a script on a remote resource after it is created Supports both ssh and winrm type connections
Alice is writing a VPC module in AWS and a variable needs to be defined in the following format: az=["us-west-1a","us-west-1b"] What is the data type that alice can use to match this type of data?
List
Matthew is implementing Terraform in production. He realized that every region in AWS has a different AMI ID for CentOS 7 OS. He wants to create a Terraform code that works for all the regions. He has already created the EC2 resource but needs to figure on how he can deal with different AMI IDs based on regions? What is the best approach?
Make use of Data Source - Using Data source, we can query for the latest AMI ID based on specific conditions like availability, OS or other
Matt wants to run Terraform in his Windows Laptop. Matt read that Terraform Core is developed using Go. Is there a need for Matt to explicitly install GO programming language in his Windows laptop in order to run Terraform?
No - Terraform Core is a statically-compiled binary written in the Go programming language
Refer to the following example code: provider "aws" { region = "us-west-2" access_key = "YOUR-ACCESS-KEY" secret_key = "YOUR-SECRET-KEY" } variable "istest" {} resource "aws_instance" "dev" { ami = "ami-082b5a644766e0e6f" instance_type = "t2.micro" } Since the value of the variable "istest" is undefined, will the terraform plan operation show an error?
No - Terraform will simply ask you to input the variable value
Backend Config type - 2
Partial time Configuration: You do not need to specify every required argument in the backend config. Omitting certain args may be desirable if they contain secrets within the main config. - The remaining config arguments must be provided as part of the initialization process (pg. 131)
State Command
Rather than modifying the state directly, the TF state commands can be used: - Terraform State List: List resources within TF state - Terraform state mv: Move items within terraform state. Can be used for resource naming - Terraform State pull: Manually download and output the state from state file - Terraform state rm: remove items from TF state file - Terraform state show: Show the attributes of a single resource in the TF state
Data Types
String: Sequence of unicode characters representing some text, like "hello" List: Sequential list of values identified by their position. Starts with 0, ["mumbai", "singapore", "usa"] Map: A group of values identified by named labels, like {name = "Mabel", age =52} Number: Example = 200
TF and GIT - 3
TF will clone and use the default branch, can be overridden by using the ref argument - EX: source = "git::https//example.com/vpc.git?reft=v1.2.0" - Value of the ref argument can be any reference that would be accepted by the git checkout command, including branch and tag names
Terraform Plan Destroy
Terraform Plan -destroy lets us preview the destroy behavior
Terraform Apply
The terraform apply command is used to apply the changes required to reach the desired state of the configuration. Terraform apply will also write data to the terraform.tfstate file. Once apply is completed, resources are immediately available.
Fetching values from map
To reference image-abc from below map, need to utilize: Var.ami_ids["mumbai"] Page 136
Alice has created a variable associated with the db_password parameter in the following way: var.db_password The value associated with the variable is defined in terraform.tfvars file in the following way: db_password="mypassword" Will the password be part of the terraform state file?
True - The sensitive values are still recorded in the state file and anyone who has access to the state file will be able to see the value
Matt wants to quickly validate syntax error in the Terraform code that he has written. Initially, Matt used to run "terraform plan" but it takes lot of time. Will terraform validate command be useful in this use-case?
True - The terraform validate command validates the configuration files in a directory, referring only to the configuration and not accessing any remote services such as remote state, provider APIs, etc
Terraform Plan
Used to create an execution plan
Input Variables
Value associated with a variable can be assigned via multiple approaches - Value associated with the variables can be defined in CLI and tfvars file as well - Syntax to load custom tfvars file: Ex: Terraform apply -var-file="testing.tfvars"
Looking into the following code, what is the name of the provider that is being used? resource "aws_instance" "myec2" { ami = "ami-082b5a644766e0e6f" instance_type = var.instancetype }
aws - From the configuration, we can easily identify that resource type of aws_instance is used. This resource_type is part of the AWS provider
Based on the following Terraform code, what is the name of IAM User that will be created? variable "elb_names" { type = list default = ["dev-loadbalancer", "stage-loadbalanacer","prod-loadbalancer"] } resource "aws_iam_user" "lb" { name = var.elb_names[count.index] count = 2 path = "/system/" }
dev-loadbalancer and stage-loadbalancer - Since count is set to 2, there will be a total of 2 objects that will be created from that list
Andrew wants to read the contents of the file named id_rsa using Terraform. Which terraform function can be used to achieve this use-case?
file
Matthew is new to terraform. He is creating an EC2 instance. Matthew wants to IP address of the instance to show in output automatically once the EC2 instance is deployed? Which resource in terraform can he use?
output
Terraform terms
resource "aws_instance" "example" { ami = "abc123" } aws_instance --> resource type example ---> local name of resource ami ---> argument name abc123 ---> argument name
Refer to the following Terraform code: variable "mobile_phones" { type = list default = ["nokia", "motorola", "samsung", "apple", "siemens"] } There is a requirement to refer to "samsung" in the given list. What is the way to do that? How can the string of samsung can be referred from a variable?
var.mobilie_phones[2] - Remember that first value starts with reference of 0 and hence 3rd value of Samsung will be referenced with number 2
Following is the snippet of Terraform code that is part of the AWS VPC Module. variable "vpc_cidr_block" { type = map default = { us-east-1 = "192.168.10.0/24" ap-south-1 = "192.168.20.0/24" us-west-2 = "10.77.0.0/16" } } If there is a requirement to fetch the value of 10.77.0.0/16 associated with a specific variable?
var.vpc_cidrs_block["us-west-2"]