Come installare Terraform su Ubuntu 22.04|20.04 |18.04
Questa guida ti aiuterà a installare Terraform su Ubuntu 22.04|20.04 |18.04. Terraform è uno strumento Infrastructure as code che consente di gestire facilmente le risorse cloud in modalità versione. Utilizzi Terraform per creare, modificare e modificare le versioni dell'infrastruttura distribuita sui provider di servizi più diffusi. Questo strumento non è indipendente dal cloud e supporta soluzioni interne personalizzate.
Con Terraform puoi gestire cloud computing, reti, bilanciatori del carico, DNS e così via utilizzando un semplice linguaggio di programmazione dichiarativo. Visualizza l'elenco completo dei provider Terraform. È possibile applicare modifiche complesse alla tua infrastruttura con un'interazione umana minima
Installa Terraform su Ubuntu 22.04|20.04 |18.04
Terraform è distribuito come tarball su Github. Controlla l'ultima versione sulla pagina delle versioni di Terraform prima di scaricarla di seguito. Esistono due metodi con cui possiamo installare terraform su Ubuntu
Metodo 1: installa Terraform dal repository APT
Il team Terraform offre repository di pacchetti per Linux basato su Debian, che consentono di installare Terraform utilizzando lo strumento di gestione dei pacchetti apt o qualsiasi altro frontend APT.
Innanzitutto, installa le dipendenze aggiuntive del repository:
sudo apt update
sudo apt install software-properties-common gnupg2 curl
Ora importa la chiave GPG del repository
curl https://apt.releases.hashicorp.com/gpg | gpg --dearmor > hashicorp.gpg
sudo install -o root -g root -m 644 hashicorp.gpg /etc/apt/trusted.gpg.d/
Con la chiave importata ora aggiungi il repository Hashicorp al tuo sistema Ubuntu:
sudo apt-add-repository "deb [arch=$(dpkg --print-architecture)] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
Risultato dell'esecuzione previsto:
Repository: 'deb [arch=amd64] https://apt.releases.hashicorp.com jammy main'
Description:
Archive for codename: jammy components: main
More info: https://apt.releases.hashicorp.com
Adding repository.
Press [ENTER] to continue or Ctrl-c to cancel.
Adding deb entry to /etc/apt/sources.list.d/archive_uri-https_apt_releases_hashicorp_com-jammy.list
Adding disabled deb-src entry to /etc/apt/sources.list.d/archive_uri-https_apt_releases_hashicorp_com-jammy.list
Hit:1 https://mirror.hetzner.com/ubuntu/packages jammy InRelease
Hit:2 https://mirror.hetzner.com/ubuntu/packages jammy-updates InRelease
Hit:3 https://mirror.hetzner.com/ubuntu/packages jammy-backports InRelease
Hit:4 https://mirror.hetzner.com/ubuntu/security jammy-security InRelease
Get:5 https://apt.releases.hashicorp.com jammy InRelease [12.0 kB]
Get:6 https://apt.releases.hashicorp.com jammy/main amd64 Packages [74.4 kB]
Fetched 86.4 kB in 1s (84.6 kB/s)
Reading package lists... Done
Ora installa terraform sul tuo sistema Ubuntu Linux:
sudo apt install terraform
Controlla la versione di terraform installata sul tuo sistema
$ terraform --version
Terraform v1.5.5
on linux_amd64
Metodo 2: installa Terraform manualmente
I pacchetti di distribuzione principali per Terraform sono archivi .zip contenenti singoli file eseguibili che puoi estrarre ovunque sul tuo sistema
Assicurati che i pacchetti wget e unzip siano installati sul tuo sistema Ubuntu:
sudo apt install wget unzip -y
Quindi scarica l'ultimo archivio Terraform.
TER_VER=$(curl -s https://api.github.com/repos/hashicorp/terraform/releases/latest | grep tag_name | cut -d: -f2 | tr -d \"\,\v | awk '{$1=$1};1')
wget https://releases.hashicorp.com/terraform/${TER_VER}/terraform_${TER_VER}_linux_amd64.zip
Una volta scaricato, estrai l'archivio:
$ unzip terraform_${TER_VER}_linux_amd64.zip
Archive: terraform_1.5.5_linux_amd64.zip
inflating: terraform
Ciò creerà un file binario terraform nella tua directory di lavoro. Sposta questo file nella directory/usr/local/bin
.
sudo mv terraform /usr/local/bin/
Ciò renderà lo strumento accessibile a tutti gli account utente.
$ which terraform
/usr/local/bin/terraform
Conferma la versione installata
$ terraform version
Terraform v1.5.5
on linux_amd64
Verifica che lo strumento funzioni:
$ terraform
Usage: terraform [global options] <subcommand> [args]
The available commands for execution are listed below.
The primary workflow commands are given first, followed by
less common or more advanced commands.
Main commands:
init Prepare your working directory for other commands
validate Check whether the configuration is valid
plan Show changes required by the current configuration
apply Create or update infrastructure
destroy Destroy previously-created infrastructure
All other commands:
console Try Terraform expressions at an interactive command prompt
fmt Reformat your configuration in the standard style
force-unlock Release a stuck lock on the current workspace
get Install or upgrade remote Terraform modules
graph Generate a Graphviz graph of the steps in an operation
import Associate existing infrastructure with a Terraform resource
login Obtain and save credentials for a remote host
logout Remove locally-stored credentials for a remote host
output Show output values from your root module
providers Show the providers required for this configuration
refresh Update the state to match remote systems
show Show the current state or a saved plan
state Advanced state management
taint Mark a resource instance as not fully functional
test Experimental support for module integration testing
untaint Remove the 'tainted' state from a resource instance
version Show the current Terraform version
workspace Workspace management
Global options (use these before the subcommand, if any):
-chdir=DIR Switch to a different working directory before executing the
given subcommand.
-help Show this help output, or the help for a specified subcommand.
-version An alias for the "version" subcommand.
Utilizzo di Terraform per gestire l'infrastruttura
Ora che Terraform è installato, creiamo un progetto di prova.
mkdir projects
cd projects
Crea il file di configurazione principale di Terraform.
touch main.tf
Sto eseguendo un test con il provider AWS, ma puoi utilizzare altri provider per i tuoi progetti. La sezione del mio provider di configurazione Terraform è la seguente.
$ vim main.tf
# Provider
provider "aws" {
access_key = ""
secret_key = ""
region = "us-west-1"
}
Incolla la chiave di accesso AWS e la chiave segreta rispettivamente nelle sezioni access_key
e secret_key
. Puoi anche configurare le tue credenziali di accesso AWS con lo strumento AWS CLI.
Al termine, esegui terraform init
per inizializzare una directory di lavoro Terraform.
$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v5.12.0...
- Installed hashicorp/aws v5.12.0 (signed by HashiCorp)
Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
Terraform scaricherà automaticamente il provider configurato nella directory .terraform
.
Aggiungiamo ora la sezione delle risorse per creare risorse AWS VPC e sottorete modificando il file main.tf
.
# Provider
provider "aws" {
access_key = ""
secret_key = ""
region = ""
}
# Retrieve the AZ where we want to create network resources
data "aws_availability_zones" "available" {}
# VPC Resource
resource "aws_vpc" "main" {
cidr_block = "10.11.0.0/16"
enable_dns_support = true
enable_dns_hostnames = true
tags {
Name = "Test-VPC"
}
tags {
Environment = "Test"
}
}
# AWS subnet resource
resource "aws_subnet" "test" {
vpc_id = "${aws_vpc.main.id}"
cidr_block = "10.11.1.0/24"
availability_zone = "${data.aws_availability_zones.available.names[0]}"
map_public_ip_on_launch = "false"
tags {
Name = "Test_subnet1"
}
}
Salva il file dopo aver aggiunto le definizioni delle risorse e impostato le variabili AWS, quindi genera e mostra un piano di esecuzione.
$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
data.aws_availability_zones.available: Refreshing state...
------------------------------------------------------------------------
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_subnet.test
id: <computed>
arn: <computed>
assign_ipv6_address_on_creation: "false"
availability_zone: "us-east-1a"
availability_zone_id: <computed>
cidr_block: "10.11.1.0/24"
ipv6_cidr_block: <computed>
ipv6_cidr_block_association_id: <computed>
map_public_ip_on_launch: "false"
owner_id: <computed>
tags.%: "1"
tags.Name: "Test_subnet1"
vpc_id: "${aws_vpc.main.id}"
+ aws_vpc.main
id: <computed>
arn: <computed>
assign_generated_ipv6_cidr_block: "false"
cidr_block: "10.11.0.0/16"
default_network_acl_id: <computed>
default_route_table_id: <computed>
default_security_group_id: <computed>
dhcp_options_id: <computed>
enable_classiclink: <computed>
enable_classiclink_dns_support: <computed>
enable_dns_hostnames: "true"
enable_dns_support: "true"
instance_tenancy: "default"
ipv6_association_id: <computed>
ipv6_cidr_block: <computed>
main_route_table_id: <computed>
owner_id: <computed>
tags.%: "2"
tags.Environment: "Test"
tags.Name: "Test-VPC"
Plan: 2 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
Infine, crea la tua infrastruttura con Terraform utilizzando terraform apply
.
$ terraform apply
data.aws_availability_zones.available: Refreshing state...
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_subnet.test
id: <computed>
arn: <computed>
assign_ipv6_address_on_creation: "false"
availability_zone: "us-east-1a"
availability_zone_id: <computed>
cidr_block: "10.11.1.0/24"
ipv6_cidr_block: <computed>
ipv6_cidr_block_association_id: <computed>
map_public_ip_on_launch: "false"
owner_id: <computed>
tags.%: "1"
tags.Name: "Test_subnet1"
vpc_id: "${aws_vpc.main.id}"
...........................
Conferma le modifiche da apportare e digita "sì" per avviare le modifiche.
Plan: 2 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: yes
Un'esecuzione di terraform riuscita dovrebbe stampare un messaggio di successo alla fine.
Lo stato di Terraform viene salvato in ./terraform.tfstate
ma il backend può essere modificato. Puoi confermare le modifiche all'infrastruttura dalla console AWS.
Distruggere l'infrastruttura Terraform
Abbiamo confermato che la nostra installazione Terraform su Ubuntu funziona come previsto. distruggi l'infrastruttura gestita da Terraform eseguendo il comando terraform destroy
.
$ terraform destroy
aws_vpc.main: Refreshing state... (ID: vpc-0e94a7d72c02dab2b)
data.aws_availability_zones.available: Refreshing state...
aws_subnet.test: Refreshing state... (ID: subnet-0ad06c2e86542ddc1)
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
- aws_subnet.test
- aws_vpc.main
Plan: 0 to add, 0 to change, 2 to destroy.
Do you really want to destroy all resources?
Terraform will destroy all your managed infrastructure, as shown above.
There is no undo. Only 'yes' will be accepted to confirm.
Enter a value: yes
Se non vuoi la richiesta di conferma, usa:
terraform destroy -auto-approve
Installazione di Terraform su altri sistemi:
- Come installare Terraform su Fedora
- Installa e utilizza Terraform su Windows/Windows Server
Prossimi passi
Ora che hai installato e testato Terraform, è il momento di creare l'infrastruttura utilizzando un file di configurazione Terraform minimo. Terraform Use Cases è una pagina interessante da leggere per i nuovi utenti.
Potrebbe interessarti anche:
- Come effettuare il provisioning delle VM su KVM con Terraform
- Distribuisci istanze VM su Hetzner Cloud con Terraform
- Crea immagini di macchine AWS EC2 (AMI) con Packer e Ansible