This is the second day of my participation in Gwen Challenge

Function introduction

Terraform is an automated orchestration tool for IT Infrastructure. Its slogan is "Write,Plan, and Create Infrastructure as Code". Infrastructure is Code. Operate different cloud platforms, including private clouds, using the same set of rules and commands.Copy the code
Method 1: Directly log in to the cloud platform management page, manually click. This can be maintained for a single or several cloud resources, but manual operation becomes impractical and prone to misoperation when the cloud server scale reaches thousands of costs. Method 2: SDK and AIP provided by the cloud platform. This makes mass operations possible, and the code is relatively less prone to misoperations. However, development capabilities are required, and a lot of code is required for complex requirements. Method 3: Command line tools provided by cloud platforms, such as AWS CLI and Aliyun CLI, can be used to operate cloud resources by commands, just like SQL, using operation elements such as add, delete, change, and check to manage the cloud. Method 4: Terraform shines on the stage. If the CLI of method 3 is a command operation, and the cloud server needs to be clearly informed that this operation is query and add, then Terraform is a purposeful operation. The goal of maintaining a state of cloud services locally is to make the cloud server look whatever the template looks like. Compared to the above three, Teeraform has the advantage that we only need to focus on the results and do not need to care about the command to operate.Copy the code
Terraform knowledge

There are two core files, one is the choreography file, the other is the status file

  • The main.tf file is the main file for business orchestration, customizing a series of orchestration rules.
  • Terraform. tfState: a local status file, which is equivalent to a backup of the local cloud service status and affects the terraForm execution plan.
Q: What happens if the local state is different from the cloud service state? A: There is no need to worry about this. As mentioned earlier, Terraform is a purposeful orchestration that completes the orchestration according to preset results and eventually synchronously updates local files.Copy the code

Install the configuration

  • Download decompression
# download from the official website To find the corresponding platform https://www.terraform.io/downloads.html # download decompression wget https://releases.hashicorp.com/terraform/0.12.24/terraform_0.12.24_linux_amd64.zipCopy the code
  • Configuring environment Variables
vim /etc/profile
export PATH=$PATH:/data/softapps
source /etc/profile
Copy the code
  • Basic operation commands
1. Create a working directory, like a Git repository or a workspace in software development. 2. Create a xx.ft file and specify information such as provider. 3. Run terraform init to initialize the current directory like git init, download the provider from TF, and prepare necessary environment conditions for subsequent operations. 1. Terraform Plan: Preview the execution plan. It is not mandatory but strongly recommended. I know what to make of the cloud server this time. Later versions merge with Apply, so use the plan command based on your version. Terraform show: show the current status. 4. Terraform destroy: destroy cloud services and clean up the cloud services in TFCopy the code

Tencent Cloud Terraform operation

  • Terraform workflow

  • Create the provider.tf file
vim provider.tf //provider.tf provider "tencentcloud" { secret_id = "RGID*************SG*" secret_key = "CBS************GS" region = "AP-shanghai"} # It is recommended to configure API keys in environment variables. It is not recommended to write the keys directly to the source code to avoid leakage. vim /etc/profile export TENCENTCLOUD_SECRET_ID="your_accessid" export TENCENTCLOUD_SECRET_KEY="your_accesskey" export TENCENTCLOUD_REGION="ap-shanghai" vim provider. Tf provider "tencentcloud" {}Copy the code
  • Initialize the
Terraform init: Initializes the TerraForm. Erraform automatically detects the Provider field in the provider.tf file. Send a request to The official GitHub of Terraform to download the latest version of Tencent cloud resource modules and plug-ins. When the initialization is successful, the version information of the current script will also be displayed. When a new version of Tencent cloud script is released, you can run the terraform init-upgrade command to update the script and obtain the latest application.Copy the code

  • Deploy Tencent cloud resources
$vim vpc.tf Create a VPC resource "tencentcloud_vpc" "vpc_test" {name = "vpc-test-liyk" cidr_block = "10.0.0.0/16"}Copy the code

Enabling the Cloud Server
vim cvm.tf // Create a cvm resource "tencentcloud_instance" "cvm_test" { instance_name = "cvm-test" availability_zone = "ap-hongkong-1" image_id = "img-pi0ii46r" instance_type = "S2.SMALL1" system_disk_type = "CLOUD_PREMIUM" security_groups  = [ "${tencentcloud_security_group.sg_test.id}" ] vpc_id = "${tencentcloud_vpc.vpc_test.id" subnet_id = "${tencentcloud_subnet.subnet_test.id}" internet_max_bandwidth_out = 10 count = 1 }Copy the code
$vim vpc.tf // Create a VPC resource "tencentcloud_vpc" "vpc_test" {name = "vpc-test-liyk" cidr_block = "10.0.0.0/16" }Copy the code
$ vim subnet.tf // Create a subnet resource "tencentcloud_subnet" "subnet_test" { name = "subnet-test" cidr_block = "10.0.0.0/24" availability_zone = "ap-HONGKONG -1" vpc_id = "${tencentCloud_vpc.vpc_test. id}" route_table_id = "${tencentcloud_route_table.rtb_test.id}" }Copy the code
$ vim route_table.tf // Create a route table resource "tencentcloud_route_table" "rtb_test" { name = "rtb-test" vpc_id =  "${tencentcloud_vpc.vpc_test.id}" }Copy the code
$ vim security_group.tf // Create a security group and rule resource "tencentcloud_security_group" "sg_test" { name = "sg-test" } resource "tencentcloud_security_group_rule" "sg_rule_test" { security_group_id = "${tencentcloud_security_group.sg_test.id}" type = "ingress" CIDr_ip = "0.0.0.0/0" ip_protocol = "TCP" port_range = "Policy = "accept"}Copy the code

Summary and Cases

Lifecycle management of infrastructure resources can be easily implemented using Terraform Scripting, Plan, Apply, and Destroy. The following uses the CVM, MySQl, VPC and Security Group services of Tencent Cloud as an example to build a simple infrastructure.

  • Scripting
Write resource choreography scripts using HashiCorp's own declarative language, HCL. Because it is a declarative language, some of the advanced features of procedural languages we are familiar with, such as "for" loops, are not supported by HCL.Copy the code
Provider info Provider "tencentCloud" {secret_id = "AsVv2va1CE5ipdx4" secret_key = "KQdafafrtJ" region = } #2, Create a VPC resource resource "tencentcloud_vpc" "main" {name = "demo-vpc" cidr_block = } #3, Create route tables for web and DB resource "tencentcloud_route_table" "web" {name = "demo-rt_web" vpc_id = "${tencentcloud_vpc.main.id}" } resource "tencentcloud_route_table" "db" { name = "demo-rt_db" vpc_id = ${tencentcloud_vpc.main.id}"} #4, CVM instances resource "tencentcloud_instance" "nginx" {instance_name = "demo-nginx"  availability_zone = "ap-shanghai-2" image_id = "img-pi0ii46r" instance_type = "S4.SMALL2" security_groups = [ "${tencentcloud_security_group.web.id}" ] vpc_id = "${tencentcloud_vpc.main.id}" subnet_id = ${tencentcloud_subnet.web.id}" internet_max_bandwidth_out = 10 count = 10} #5, Mysql instance resource "tencentcloud_mysql_instance" "demo-mysql" { instance_name = "demo-mysql" mem_size = 1000 root_password = "My_demo_mysql0001" volume_size = 50 availability_zone = "ap-shanghai-2" engine_version = "5.7" internet_service = 0 intranet_port = 3306 parameters = { max_connections = "1000" } security_groups = [ "${tencentcloud_security_group.db.id}" ] vpc_id = "${tencentcloud_vpc.main.id}" subnet_id = ${tencentCloud_subnet.db. id}" tags = {name ="demo-project"}} #6, Create subnets within the VPC resource "Tencentcloud_subnet" "web" {name = "demo-sn_web" cidr_block = "10.0.0.0/24" availability_zone = "ap-shanghai-2" vpc_id  = "${tencentcloud_vpc.main.id}" route_table_id = "${tencentcloud_route_table.web.id}" } resource "tencentcloud_subnet" "Db" {name = "demo-sn_db" cidr_block = "10.0.2.0/24" availability_zone = "ap-shanghai-2" vpc_id = "${tencentCloud_vpc.main. id}" route_table_id = "${tencentCloud_route_table.db. id}"} #7, Create security groups and rules  resource "tencentcloud_security_group" "web" { name = "demo-sg_web" description = "Accessible for both HTTP and SSH" } resource "tencentcloud_security_group" "db" { name = "demo-sg_db" description = "Accessible for both mysql and SSH from web" } resource "tencentcloud_security_group_rule" "web-from-public" { security_group_id = "${tencentcloud_security_group.web.id}" type = "ingress" cidr_ip = "0.0.0.0/0" ip_protocol = "TCP" port_range = "80,22" policy = "accept" } resource "tencentcloud_security_group_rule" "web-to-public" { security_group_id = "${tencentcloud_security_group.web.id}" type = "egress" ip_protocol = "TCP" cidr_ip = "0.0.0.0/0" port_range = "80,22" policy = "accept" } resource "tencentcloud_security_group_rule" "mysql-from-webtier" { security_group_id = "${tencentCloud_security_group.db. id}" type = "ingress" CIDr_ip = "10.0.0.1/24" ip_protocol = "TCP" port_range = "22,3306" policy = "accept"} resource "tencentcloud_security_group_rule" "mysql-to-webtier" {security_group_id = "${tencentcloud_security_group.db.id}" type = "egress" cidr_ip = "0.0.0.0/0" ip_protocol = "TCP" port_range = "22,3306" policy = "accept" }Copy the code
  • Plan
The Terraform Plan function supports checking and validation before Terraform scripts are executed. Terraform ensures the accuracy of execution results based on the consistency of scripts, local status files (terraform.TFState) and cloud platforms.Copy the code
  • Apply
Terraform Apply enables one-click deployment of the infrastructure. Note that Terraform still forces resource validation before apply, i.e., Terraform Plan. Terraform execution results are saved in the local status file (terraform.tfState).Copy the code
  • Destroy
Complex resource deployment can be achieved through the above simple three steps. Similarly, quick and efficient resource release can be achieved with a simple command.Copy the code
advantage
1. Higher deployment efficiency. IaC shortens the process from resource development requirements to resource deployment. In batch deployment and multi-cloud deployment scenarios, IaC greatly improves resource deployment efficiency. 2. Increased the consistency of basic resource configurations. With declarative language, resource configuration is easier to read, reducing the chance of human error; 3. Reduce enterprise costs. Traditional cloud migration is greatly simplified to improve resource utilization and reduce OPEX on enterprise cloud.Copy the code