arrow

Use The Terraform To Create Cloud Resources

1. Experiment

1.1 Knowledge points

Terraform is used in this experiment. As a resource O&M tool running on the open source DevOps infrastructure, Terraform enables you to securely and efficiently build and change various service resources from multiple cloud vendors. In this experiment, Terraform is used to create and orchestrate Alibaba Cloud resources based on the configuration file, and directly build a WordPress website architecture that contains various Alibaba Cloud resources, including the Server Load Balancer, RDS, and ECS instances.

1.2 Experiment process

  • Ready
  • Use Terraform to create WordPress architecture resources

1.3 Scene architecture diagram

image desc

1.4 Cloud resources required

  • SLB
  • ECS
  • RDS
  • VPC

1.5 Prerequisites

  • Learn about ECS, Server Load Balancer, RDS, and VPC

2. Start the experiment environment

Click Start Lab in the upper right corner of the page to start the experiment.

image desc.

After the experiment environment is successfully started, the system has deployed resources required by this experiment in the background, including the ECS instance, RDS instance, Server Load Balancer instance, and OSS bucket. An account consisting of the username and password for logging on to the Web console of Alibaba Cloud is also provided.

image desc

After the experiment environment is started and related resources are properly deployed, the experiment starts a countdown. You have two hours to perform experimental operations. After the countdown ends, the experiment stops, and related resources are released. During the experiment, pay attention to the remaining time and arrange your time wisely. Next, use the username and password provided by the system to log on to the Web console of Alibaba Cloud and view related resources:

openCole

Go to the logon page of Alibaba Cloud console.

image desc

Fill in the sub-user account and click Next.

image desc

Fill in the sub-user password and click Log on.

image desc

After you successfully log on to the console, the following page is displayed.

image desc

3. Ready

3.1 Create an AccessKey

Refer back to the user’s home directory as shown below, click AccessKey Management.

image desc

Click Create AccessKey. After AccessKey has been created successfully, AccessKeyID and AccessKeySecret are displayed. AccessKeySecret is only displayed once. Click Download CSV FIle to save the AccessKeySecret

image desc

3.2 Log in to ECS

Click Elastic Compute Service, as shown in the following figure.

image desc

We can see one running ECS instance in Silicon Valley region.

image desc

Copy this ECS instance’s Internet IP address and remotely log on to this ECS (Ubuntu system) instance. For details of remote login, refer to login

image desc

The default account name and password of the ECS instance:

Account name: root

Password: nkYHG890..

4. Use Terraform to create resources

4.1 Install Terraform

Run the following command to update the apt installation source:

apt update

image desc

Run the following command to install the unpacking tool:

apt install -y unzip zip

image desc

Run the following command to download the Terraform installation package:

wget http://labex-ali-data.oss-us-west-1.aliyuncs.com/terraform/terraform_0.14.6_linux_amd64.zip

image desc

Run the following command to unpack the Terraform installation package to /usr/local/bin:

unzip terraform_0.14.6_linux_amd64.zip -d /usr/local/bin/

image desc

4.2 Create Configuration File

Run the following command to create a terra directory and switch to this directory:

mkdir -p terraform

cd terraform

image desc

input the command: vim provider.tf, Copy the following content to the file, save the modification, and exit the file. You must replace YOUR-ACCESS-KEY, YOUR-SECRET-KEY with your own settings.

provider "alicloud" {
  access_key = "YOUR-ACCESS-KEY"
  secret_key = "YOUR-SECRET-KEY"
  region     = "us-west-1"
}

image desc

input the command: vim vpc.tf, Copy the following content to the file, save the modification, and exit the file.

variable "vs_zone" {
  default = "us-west-1a"
}

# Create VPC
resource "alicloud_vpc" "labex_vpc" {
  vpc_name   = "labex_vpc"
  cidr_block = "172.16.0.0/12"
}

# Create Vswitch
resource "alicloud_vswitch" "labex_vs" {
  vpc_id            = alicloud_vpc.labex_vpc.id
  cidr_block        = "172.16.0.0/21"
  zone_id = var.vs_zone
}

# Create security group
resource "alicloud_security_group" "default" {
  name        = "terraform-default"
  description = "terraform-default"
  vpc_id      = alicloud_vpc.labex_vpc.id
}

# Create Security group rule
resource "alicloud_security_group_rule" "allow_all_tcp" {
  type              = "ingress"
  ip_protocol       = "tcp"
  nic_type          = "intranet"
  policy            = "accept"
  port_range        = "22/81"
  priority          = 1
  security_group_id = alicloud_security_group.default.id
  cidr_ip           = "0.0.0.0/0"
}

image desc

input the command: vim rds.tf, Copy the following content to the file, save the modification, and exit the file.

variable "db_name" {
  default = "labex"
}

variable "db_user_password" {
  default = "Aliyun-test"
}

variable "db_user_name" {
  default = "labex"
}

variable "rds_type" {
  default = "rds.mysql.s2.large"
}

resource "alicloud_db_instance" "labex" {
  engine               = "MySQL"
  engine_version       = "8.0"
  instance_type        = var.rds_type
  instance_storage     = "30"
  instance_charge_type = "Postpaid"
  instance_name        = "labex"
  vswitch_id           = alicloud_vswitch.labex_vs.id
  monitoring_period    = "60"
  security_ips         = ["0.0.0.0/0"]
}

resource "alicloud_db_account" "account" {
  db_instance_id = alicloud_db_instance.labex.id
  account_name        = var.db_user_name
  account_password    = var.db_user_password
}

resource "alicloud_db_database" "database" {
  instance_id = alicloud_db_instance.labex.id
  name        = var.db_name
}

resource "alicloud_db_connection" "conn" {
  instance_id       = alicloud_db_instance.labex.id
  #connection_prefix = "LabEx1982"
}

resource "alicloud_db_account_privilege" "privilege" {
  instance_id  = alicloud_db_instance.labex.id
  account_name = alicloud_db_account.account.name
  privilege    = "ReadWrite"
  db_names     = alicloud_db_database.database.*.name
}

image desc

input the command: vim ecs.tf, Copy the following content to the file, save the modification, and exit the file.

variable "ecs_type" {
  default = "ecs.hfc6.large"
}

variable "wordpress_image" {
  default = "m-rj9a5l541nbz5ugvlznu"
}

variable "ecs_password" {
  default = "Aliyun-test"
}

# Create a server
resource "alicloud_instance" "labex" {
  count                 = 2
  image_id              = var.wordpress_image
  internet_charge_type  = "PayByBandwidth"
  instance_type         = var.ecs_type
  system_disk_category  = "cloud_efficiency"
  security_groups       = [alicloud_security_group.default.id]
  instance_name         = "labex"
  vswitch_id            = alicloud_vswitch.labex_vs.id
  password              = var.ecs_password
  internet_max_bandwidth_out = 1
  user_data             = "#!/bin/bash\nsed -i 's/database_name_here/${var.db_name}/g' /var/www/wordpress/wp-config.php\nsed -i 's/username_here/${var.db_user_name}/g' /var/www/wordpress/wp-config.php\nsed -i 's/password_here/${var.db_user_password}/g' /var/www/wordpress/wp-config.php\nsed -i 's/localhost/${alicloud_db_connection.conn.connection_string}/g' /var/www/wordpress/wp-config.php\nsed -i 's/utf8/utf8mb4/g' /var/www/wordpress/wp-config.php\nservice nginx start\nservice php7.0-fpm start"
}

image desc

input the command: vim slb.tf, Copy the following content to the file, save the modification, and exit the file.

variable "slb_type" {
  default = "slb.s2.small"
}

resource "alicloud_slb" "labex_slb" {
  load_balancer_name = "labex_slb"
  load_balancer_spec = var.slb_type
  address_type  = "internet"
  #vswitch_id    = alicloud_vswitch.default.id
  payment_type = "PayAsYouGo"
  tags = {
    tag_a = 1
    tag_b = 2
  }
}

resource "alicloud_slb_listener" "default" {
  load_balancer_id          = alicloud_slb.labex_slb.id
  backend_port              = 80
  frontend_port             = 80
  protocol                  = "http"
  bandwidth                 = 10
  sticky_session            = "on"
  sticky_session_type       = "insert"
  cookie_timeout            = 86400
  health_check              = "on"
  health_check_timeout      = 8
  health_check_interval     = 5
  health_check_http_code    = "http_2xx,http_3xx"
  x_forwarded_for {
    retrive_slb_ip = true
    retrive_slb_id = true
  }
  request_timeout = 80
  idle_timeout    = 30
}

resource "alicloud_slb_backend_server" "default" {
  load_balancer_id = alicloud_slb.labex_slb.id

  backend_servers {
    server_id = alicloud_instance.labex[0].id
    weight    = 100
  }
  backend_servers {
    server_id = alicloud_instance.labex[1].id
    weight    = 100
  }
}

image desc

input the command: vim output.tf, Copy the following content to the file, save the modification, and exit the file.

output "ecs_id0" {
  value = alicloud_instance.labex[0].id
}

output "ecs_id1" {
  value = alicloud_instance.labex[1].id
}

output "vpc_id" {
  value = alicloud_vpc.labex_vpc.id
}

output "rds_id" {
  value = alicloud_db_instance.labex.id
}

output "slb_id" {
  value = alicloud_slb.labex_slb.id
}

image desc

4.3 Create cloud resources based on the configuration file

Run the following command to initialize the added configuration file:

terraform init

image desc

Run the following command to generate an execution plan:

terraform plan

image desc

Run the following command to execute the plan and generate the resources based on the configuration file:

terraform apply

In the execution process, enter “yes” to confirm the creation operation.

image desc

The resources are being created. It takes about 7 minutes to create resources due to the large number of resources to be created. Wait in patient.

image desc

Sometimes during the resource creation process, the creation may be interrupted due to network timeout, but it does not matter. You can execute the terraform apply command again to continue creating the resource.

Resources creation is complete.

image desc

<font color='red'>The user can cut off the above result picture when doing the experiment and send it to the teacher, indicating that the part of the current chapter has been completed.</font>

Go to the SLB console of Alibaba Cloud.

image desc

You can see that there is a newly created SLB instance.

image desc

Enter the following hyperlink in the browser. You need replace YOUR-SLB-IP with your IP address output in the preceding figure

http://YOUR-SLB-IP/wp-admin/install.php

The WordPress installation interface is displayed, indicating that the WordPress website is properly built. You can refer to the following figure to set the user name and password of the WordPress website. For more information about user settings of the WordPress website, see the experiment “Deploying WordPress on Alibaba Cloud ECS”.

image desc

Go to the Alibaba Cloud ECS console,

image desc

The two new ECS instances are displayed.

image desc

Refer to the following figure to go to the RDS console.

image desc

The new RDS instance is displayed.

image desc

While creating an RDS resource, Terraform also creates other resources like the VPC instance, VSwitch, ECS security group, RDS account, and database. You can view these resources on the Web page. In addition, dependencies between these resources are also configured. For example, the backend of the Server Load Balancer instance automatically listens the ports of two ECS instances, and the configuration file on each ECS instance automatically records the intranet address of the RDS database.

At this point, the resource has been created, but if the user wants to modify the parameters of a resource, such as the password of the ECS instance, just modify the content of the configuration file in terraform, and the user does not need to manually go to the console to modify the relevant parameters of the instance Configuration.

Return to the command line terminal, Enter the command: vim ecs.tf, refer to the figure below to modify, save and exit.

image desc

Enter the following command to make the modification effective. At this time, terraform will automatically query whether the status of the related resources is the same as that defined in the configuration file according to the content of the configuration file. If they are not the same, modify the configuration of the related resources according to the content of the configuration file.

terraform apply

image desc

image desc

The modification is now complete.

Therefore, if users need to delete, update, or modify related cloud resources, they only need to maintain the terraform configuration file.

4.4 Release Resources

Return to the command line terminal, and run the following command to release all the resources created just now:

terraform destroy

Enter “yes” to release the resources.

image desc

Resources are being released.

image desc

The release is complete. Sometimes an error may be reported during the resource release process due to network failures, but it does not matter, just execute the terraform destroy command again to continue the release.

image desc

<font color='red'>Users can cut off the above result picture when they are doing the experiment and send it to the teacher, indicating that the current experiment has been completed.</font>

After resources are released, return to the Alibaba Cloud console to confirm the result.

Reminder:
Before you leave this lab, remember to log out your Alibaba RAM account before you click the ‘stop’ button of your lab. Otherwise you’ll encounter some issue when opening a new lab session in the same browser:

image desc image desc

5. Experiment summary

In this experiment, we first compile the Terraform configuration file, generate a series of resource objects (such as RDS, ECS, and Server Load Balancer) based on the Terraform configuration file, and finally destroy the resources. The most important step is compilation of the configuration file. Terraform defines all the resource types, quantities, specifications, and dependencies in the configuration file, and supports creating and destroying resources at a click. It is an excellent weapon for improving automation productivity of O&M.