Terraform

背景:因为工作调动去了外企,恶补口语的同时也需要锻炼一下英语文档能力,故此篇用英语写作。本篇文章是对Udemy上Terraform教程的学习总结与归纳。

Terraform Basic Concepts

Terraform

Terraform is used for infrastructure code developed by a company called HashiCorp.

Infrastructure

Anything that related to how we’re setting up what we want for our technology stack is our infrastructure.

Infrastructure as Code(IaC)

Infrastructure as code (IaC) is the process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools.

Terraform setup

VS code

First you need a text editor to edit the files for terraform. For this part I choose VS Code since it had good support for the grammar of Terraform.
Link to download VS Code: https://code.visualstudio.com
Link for the plugin: https://marketplace.visualstudio.com/items?itemName=HashiCorp.terraform

Folder

ctrl+shift+e => create a new folder for terraform

Terraform Windows - Chocolatey Install

Use admin access to open Power Shell and run the following command:

1
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

Terraform Windows - Terraform Install

Chocolatey is a free and open-source package management system for Windows. Install the Terraform package from the command-line.

1
choco install terraform

Type in terraform version to check if the installation is successful.

1
terraform version

Secure Keys

Set it as environment variables
Use AWS Cli
Use Vault provider

Terraform Getting Started

Creating Your First Resource

Create a file to define your infrastructure: main.tf
Open main.tf in your VScode, paste in the configuration below, and save the file.

Providers: The block configures the specified provider, in this case . A provider is a plugin that Terraform uses to create and manage your resources.

choose the region as the nearest area of you.

Resouces: Use blocks to define components of your infrastructure. A resource might be a physical or virtual component such as an EC2 instance, or it can be a logical resource such as a Heroku application. Tells terraform which plugin to use and for which cloud platform are we going to create resources for.

Terraform Block: The block contains Terraform settings, including the required providers Terraform will use to provision your infrastructure.

1
2
3
4
5
6
7
provider "aws" {
region = "eu-central-1"
}

resource "aws_vpc" "myvpc" {
cidr_block = "10.0.0.0/16"
}

Terraform INIT

When you create a new configuration — or check out an existing configuration from version control — you need to initialize the directory with .terraform init

Initializing a configuration directory downloads and installs the providers defined in the configuration, which in this case is the provider.aws

Format and Validate the configuration

The terraform fmt command automatically updates configurations in the current directory for readability and consistency.

Terraform will print out the names of the files it modified, if any. In this case, your configuration file was already formatted correctly, so Terraform won’t return any file names.

You can also make sure your configuration is syntactically valid and internally consistent by using the terraform validate command.

Terraform PLAN

To see any changes that are required for your infrastructure.

Terraform APPLY

Apply the configuration now with the terraform apply command. Terraform will print output similar to what is shown below. I have truncated some of the output to save space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ terraform apply

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

Terraform will perform the following actions:

# aws_vpc.myvpc will be created
+ resource "aws_vpc" "myvpc" {
+ arn = (known after apply)
+ assign_generated_ipv6_cidr_block = false
##...

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.

Enter a value:

Type in yes at the confirmation prompt to proceed.

Terraform DESTROY

The terraform destroy command terminates resources managed by your Terraform project.

State file

After run terraform apply there is a file named terraform.tfstate. This is like the heart of terraform. It’s the most important file for terraform. Without it, terraform simply doesn’t work. It’s written in Json format and tells us version, resources and other infomation for terraform. It keeps tracking all the changes we make, and it’s what terraform uses to reference against whether we’re creating, deleting, or updating something.

Variables

We have several variable type in terraform.

Strings, Numbers, Boolean, List and Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
variable "vpcname" {
type = string
default = "myvpc"
}

variable "sshport" {
type = number
default = 22
}

variable "enabled" {
default = true
}

variable "mylist" {
type = list(string)
default = [ "Value1", "Value2" ]
}

variable "mymap" {
type = map
default = {
Key1 = "Value1"
Key2 = "Value2"
}
}

Use variable

1
2
3
4
5
6
7
resource "aws_vpc" "myvpc" {
cidr_block = "10.0.0.0/16"

tags = {
Name = "${var.vpcname}"
}
}

In terraform 0.12 string interpolation is no longer needed. It can be written like:

1
2
3
4
5
6
7
resource "aws_vpc" "myvpc" {
cidr_block = "10.0.0.0/16"

tags = {
Name = var.vpcname
}
}

If you want to get the list value, first element starts with 0.

1
2
3
4
5
6
7
resource "aws_vpc" "myvpc" {
cidr_block = "10.0.0.0/16"

tags = {
Name = var.mylist[0]
}
}

If you want to get the map value

1
2
3
4
5
6
7
resource "aws_vpc" "myvpc" {
cidr_block = "10.0.0.0/16"

tags = {
Name = var.mymap["Key2"]
}
}

Input

1
2
3
4
variable "inputname" {
type = string
description = "Set the name of the VPC"
}

If you want to use input

1
2
3
4
5
6
7
resource "aws_vpc" "myvpc" {
cidr_block = "10.0.0.0/16"

tags = {
Name = var.inputname
}
}

Go into the config file directory, run terraform init and terraform plan

After you input the value, the value will show up in the tags for terraform plan.

Output

1
2
3
output "vpcid" {
value = aws_vpc.myvpc.id
}

After run terraform apply, the vpcid will output on console.

Tuple

Tuple is a data type that may contains multi variable types.

1
2
3
4
variable "mytuple" {
type = tuple([string, number, string])
default = ["cat", 1, "dog"]
}

Object

1
2
3
4
5
6
7
variable "myobject" {
type = object({name = string, port = list(number)})
default = {
name = "Williams"
port = [22, 25, 80]
}
}
0%