- terraform console In order to use the terraform console command, the CLI must be able to lock state to prevent changes. TRUE Acquiring state lock. This may take a few moments...
- terraform workspace show — Show the name of the current workspace.
- terraform workspace list — List your workspaces.
- terraform workspace select — Select a specified workspace.
- terraform workspace new — Create a new workspace with a specified name.
- terraform workspace delete — Delete a specified workspace.
- terraform apply -auto-approve ( for YES )
- terraform apply -var-file="secret.tfvars" ( if you have different tfvars file instead of terraform.tfvars )
- terraform plan -out=tfplan
- terraform apply tfplan
- terraform plan -destroy ( PREVIEW of destroy/which resources can get destroyed )
- terraform plan -refresh=true (update the state prior to checking differences)
- terraform destroy
- This command is just a convenience alias for the command terraform apply -destroy
- terraform apply -replace="<resource_id>"
- terraform apply -refresh-only does not modify your infrastructure but it does modify the state file if it detects changes were made outside of Terraform.The terraform apply -refresh-only 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. Note that this used to be terraform refresh but that command was deprecated in Terraform v0.15.4
- terraform plan -lock=false You can disable state locking for most commands with the -lock flag but it is not recommended.
- terraform plan -detailed-exitcode
- Return a detailed exit code when the command exits. When provided, this argument changes the exit codes and their meanings to provide more granular information about what the resulting plan contains:
- 0 = Succeeded with empty diff (no changes)
- 1 = Error
- 2 = Succeeded with non-empty diff (changes present)
- terraform init Either -reconfigure or -migrate-state must be supplied to update the backend configuration.
- terraform init -upgrade is the command to use if you want Terraform to upgrade your existing downloaded providers
- By default, terraform init downloads plugins into a subdirectory of the working directory, .terraform/providers so that each working directory is self-contained.Both the terraform get and terraform init commands will install and update modules. The terraform init command will also initialize backends and install plugins.
- terraform get -update is used to download and update modules that are referenced in your Terraform configuration files
- terraform get - this command is used to download modules
- terraform show command is used to provide human-readable output from a state or plan file.
- -recursive flag to instruct terraform fmt to also process files in subdirectories.
- 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 and destroy only the virtual machine and then run a terraform apply again.
- Starting with Terraform 0.13 and above, terraform init can now automatically download community providers.
- terraform state list does not cause Terraform to refresh its state. This command simply reads the state file but it will not modify it.
- terraform state rm
- terraform state mv
- terraform state show 'packet_device.worker'
TF_VAR_ followed by the name of a declared variable.
TF_LOG=TRACE
Default is verbost: DEBUG,WARN,ERROR,INFO
TF_LOG_PATH="filename"
The CLI configuration file configures per-user settings for CLI behaviors, which apply across all Terraform working directories. It is named either .terraformrc or terraform.rc On Windows, the file must be named terraform.rc and placed in the relevant user's %APPDATA% directory. On all other systems, the file must be named .terraformrc (note the leading period) and placed directly in the home directory of the relevant user. The location of the Terraform CLI configuration file can also be specified using the TF_CLI_CONFIG_FILE environment variable.
-
Expressions * would be something more in the line of string, number, bool, null, etc.
-
Functions * min,max,format,join
tostring is not a string function, it is a type conversion function. tostring converts its argument to a string value.
Strings, numbers, and bools are sometimes called primitive types. Lists/tuples and maps/objects are sometimes called complex types, structural types, or collection types. array isn't a valid Type constraint in Terraform
count = "${terraform.workspace == "default" ? 5 : 1}"
join("-", ["svr", "prd", "web"])
svr-prd-web
> index(["a", "b", "c","d"],"d")
3
> index(["a", "b", "c","d"],"b")
1
To enable the plugin cache, use the plugin_cache_dir setting in the CLI configuration file. plugin_cache_dir = "$HOME/.terraform.d/plugin-cache" Alternatively, the TF_PLUGIN_CACHE_DIR environment variable can be used to enable caching or to override an existing cache directory within a particular shell session.
~> 1.2.0 will match any non-beta version of the provider between >= 1.2.0 and < 1.3.0. For example, 1.2.X
Terraform Cloud workspaces and local working directories serve the same purpose, but they store their data differently: Workspaces, managed with the terraform workspace command, isn't the same thing as Terraform Cloud's workspaces. Terraform Cloud workspaces act more like completely separate working directories. CLI workspaces (OSS) are just alternate state files.
A workspace can only be configured to a single VCS repo, however, multiple workspaces can use the same repo, if needed. A good explanation of how to configure your code repositories can be found here.
Terraform Cloud workspaces act more like completely separate working directories. CLI workspaces (OSS) are just alternate state files.
The persistent data stored in the backend belongs to a workspace. Initially, the backend has only one workspace, called "default", and thus there is only one Terraform state associated with that configuration. Terraform OSS, workspaces generally use the same code repository cli workspace are alternative state files in the same working directory whereas cli manages collections of the infrastructure resources with a persistent working directory. For local state, Terraform stores the workspace states in a directory called terraform.tfstate.d. terraform.tfstate.d/WORKSPACE_NAME/
When run locally, Terraform manages each collection of infrastructure with a persistent working directory, which contains a configuration, state data, and variables
workspaces in Terraform Enterprise/Cloud are often mapped to different code repositories. Terraform Cloud manages infrastructure collections with workspaces instead of directories. A workspace contains everything Terraform needs to manage a given collection of infrastructure, and separate workspaces function like completely separate working directories. terraform cloud maintains the state version and run history for the each workspace. When workspaces are linked to a VCS repository, Terraform Cloud can automatically initiate Terraform runs when changes are committed to the specified branch.
IaC enables API-driven workflows
The idempotent characteristic provided by IaC tools ensures that, even if the same code is applied multiple times, the result remains the same.
Platform Agnostic State Management Operator Confidence
Terraform is not a configuration management tool - It is a provisional management tool Terraform is a declarative language Terraform supports a syntax that is JSON compatible Terraform is primarily designed on immutable infrastructure principles (immutable infrastructures do not allow modifications once the software has been deployed)
Mapping to the Real World metadata performance syncing
state Rather than having to scan and inspect every resource on every run, Terraform relies on what feature to help manage resources? State
mapping configuration to resources in the real world, Terraform uses its own state structure.
State is a hard requirement for Terraform - there's no getting around it. You can have the state stored locally or you can configure a remote backend to store it somewhere else. But overall, state is always required for Terraform.
Only constants are allowed inside the terraform block. Is this correct? Yes Within a terraform block, only constant values can be used; arguments may not refer to named objects such as resources, input variables, etc, and may not use any of the Terraform language built-in functions.
A remote provisioner will execute a process on a remote resource, such as the resource created by Terraform.
The file provisioner is used to copy files or directories from the machine executing Terraform to the newly created resource
The local-exec provisioner invokes a local executable after a resource is created. This invokes a process on the machine running Terraform, not on the resource.
The on_failure setting can be used to change this. The allowed values are: continue: Ignore the error and continue with creation or destruction. fail: Raise an error and stop applying (the default behavior). If this is a creation provisioner, taint the resource.
provisioner "local-exec" { command = "echo The server's IP address is ${self.private_ip}" on_failure = "continue" }
DESTROY PROVISIONER provisioner "remote-exec" { when = "destroy" # <...snip...> }
The EC2 instance labeled web_server is the implicit dependency as the aws_eip cannot be created until the aws_instance labeled web_server has been provisioned and the id is available.
Note that aws_s3_bucket.example is an explicit dependency. Because it means once AWS_S3 get created then it is allowed to create the AWS_INSTANCE
resource "aws_eip" "public_ip" {
vpc = true
instance = aws_instance.web_server.id
}
resource "aws_instance" "web_server" {
ami = "ami-2757f631"
instance_type = "t2.micro"
depends_on = [aws_s3_bucket.company_data]
}
Terraform can limit the number of concurrent operations as Terraform walks the graph using the -parallelism=n argument. The default value for this setting is 10. This setting might be helpful if you're running into API rate limits.
https://www.datocms-assets.com/2885/1602500234-terraform-full-feature-pricing-tablev2-1.pdf Single Sign-On requires Terraform Cloud for Business or Terraform Enterprise. It is NOT available in Terraform OSS or Terraform Cloud (free) and team & Governance. Sentinel is available in Terraform Cloud (Team & Governance), Terraform Enterprise, and Terraform Cloud for Business. It is NOT available in Terraform OSS or Terraform Cloud (free). Audit Logging is available in Terraform Enterprise, and Terraform Cloud for Business. It is NOT available in Terraform OSS or Terraform Cloud (free). Public Module Registry is available to users of any version of Terraform. Workspaces are a feature of all versions of Terraform, both Terraform OSS/Cloud and all other paid versions. https://www.datocms-assets.com/2885/1602500234-terraform-full-feature-pricing-tablev2-1.pdf
Terraform OSS and Terraform Enterprise are versions of Terraform that can be installed locally on your own servers, therefore giving you the ability to manage both the Terraform binary and the underlying operating system where Terraform runs.
Terraform Enterprise is often installed on-premises or in a public cloud and provides the ability to deploy resources using any provider/plugin that is supported by Terraform. TFE gives you many features that are not available with Terraform OSS. Many of these features, however, are available in Terraform Cloud, though.
You can use modules from a private registry, like the one provided by Terraform Cloud. Private registry modules have source strings of the form ///. This is the same format as the public registry, but with an added hostname prefix.
It is important to consider that Terraform reads from data sources during the plan phase and writes the result into the plan. For something like a Vault token which has an explicit TTL, the apply must be run before the data, or token, in this case, expires, otherwise, Terraform will fail during the apply phase. Another example of this is AWS credentials: The token is generated from the moment the configuration retrieves the temporary AWS credentials (on terraform plan or terraform apply). If the apply run is confirmed after the 120 seconds, the run will fail because the credentials used to initialize the Terraform AWS provider has expired. For these instances or large multi-resource configurations, you may need to adjust the default_lease_ttl_seconds.
Currently, Terraform has no mechanism to redact or protect secrets that are returned via data sources, so secrets read via this provider will be persisted into the Terraform state, into any plan files, and in some cases in the console output produced while planning and applying. These artifacts must, therefore, all be protected accordingly.
local:::
module "consul" {
source = "./consul"
}
terraform registry::::
public repo
module "consul" {
source = "hashicorp/consul/aws"
version = "0.1.0"
}
private repo:
module "consul" {
source = "app.terraform.io/example-corp/k8s-cluster/azurerm"
version = "1.1.0"
}
github::
module "consul" {
source = "github.com/hashicorp/example"
}
with ssh github:
module "consul" {
source = "[email protected]:hashicorp/example.git"
}
bitbucket:::
module "consul" {
source = "bitbucket.org/hashicorp/terraform-consul-aws"
}
generic GIT Repo::::
module "vpc" {
source = "git::https://example.com/vpc.git"
}
module "storage" {
source = "git::ssh://[email protected]/storage.git"
}
with versioning:
# select a specific tag
module "vpc" {
source = "git::https://example.com/vpc.git?ref=v1.2.0"
}
# directly select a commit using its SHA-1 hash
module "storage" {
source = "git::https://example.com/storage.git?ref=51d462976d84fdea54b47d80dcabbf680badcdb8"
}
mericual URL::::Mercurial is a free, distributed source control management tool. It efficiently handles projects of any size and offers an easy and intuitive interface.
module "vpc" {
source = "hg::http://example.com/vpc.hg"
}
The .terraform 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.
HashiCorp style conventions state that you should use 2 spaces between each nesting level to improve the readability of Terraform configurations.
The format of resource block configurations is as follows: "" "<local name/label>"
To configure each provider, you need to define a provider block and provide the configuration within that block. You would need to do this for each provider that you need to configure. For example, if you needed to customize the aws, gcp, and vault provider, you'd need to create three separate provider blocks, one for each provider. Don't forget that configurations for a provider go inside of a provider block, but any provider constraints go inside of the terraform --> required_providers block.
Providers can be installed using multiple methods, including downloading from a Terraform public or private registry, the official HashiCorp releases page, a local plugins directory, or even from a plugin cache. Terraform cannot, however, install directly from the source code.
The most common source of dependencies is an implicit dependency between two resources or modules for example: aws_instance_ec2.webserver.id ( so kind of instance is required to be created )
Backends are configured with a nested backend block within the top-level terraform block.
Kubernetes, Consul, and S3 backends all support state locking
Beyond the value, you won't find the variable name or description in the state file because they are simply used on the development side of Terraform, and not the backend operational aspect of how Terraform works.
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.
In other words, if you don't have any specific configurations for your provider, you may indeed leave it out of your configuration. You don't have to specify a provider block since Terraform is smart enough to download the right provider based on the specified resources.
Sentinel policies to define and enforce policies, it (Sentinel) runs after a terraform plan, but before a terraform apply
output block locals block backend resource
terraform {
backend "s3" {
}
required_providers {
myaws = {
source = "hashicorp/aws"
version = "4.23.0"
}
aws = {
source = "hashicorp/aws"
version = "4.0.0"
}
}
required_version = "1.1.2"
}
provider "myaws" {
region = "eu-central-1"
default_tags {
tags = local.tags
}
}
provider "aws" {
alias = "us-east-1"
region = "us-east-1"
default_tags {
tags = local.tags
}
}
provider "aws" {
alias = "general-prod"
region = "eu-central-1"
assume_role {
role_arn = "arn:aws:iam::016560259007:role/psapp-r53-create-record"
session_name = "ps-aws-terraform"
}
default_tags {
tags = local.tags
}
}
module "ps_cloudfront_certificate" {
source = "./modules/acm_certificate"
domain_name = var.cloudfront_dns_name
route53_zone_id = var.prescreen_io_dns_zone_id
providers = {
aws = aws.us-east-1
aws.general-prod = aws.general-prod
}
}
In Terraform, if there is no alias specified for a provider, it means that provider is the default provider for the given resource type.