阿里雲平臺下Terraform+Packer一鍵部署WordPress案例

子優發表於2018-07-10

前言

前面 雲生態下的基礎架構資源管理利器Terraform 一文對Terraform做了產品介紹,包括安裝、模板配置檔案編寫,資源構建與銷燬等。這裡通過介紹Terraform + Packer 在阿里雲平臺上一鍵部署WordPress的案例,以供大家使用參考,也歡迎一起參與討論。

該實現方案包括完成阿里雲資源購買建立,到應用部署,配置修改,啟動服務,最終交付一個WordPress的公網可訪問IP地址。並且通過簡單修改Terraform的模板配置檔案ECS資源count數可實現彈性擴容(自動新增掛載到SLB)。

Packer構建VM映象

Packer是一款面向雲生態非常便利的映象管理利器,通過一個模板配置可以快速的建立映象。這裡不做具體介紹,可閱讀前面寫的 雲生態下的映象管理利器Packer 一文了解整個VM映象構建的過程。

這裡我們先來看下該案例中一鍵構建WordPress的映象模板JSON檔案:

{
  "variables": {
    "access_key": "${your_access_key}",
    "secret_key": "${your_secret_key}"
  },
  "builders": [{
    "type":"alicloud-ecs",
    "access_key":"${your_access_key}",
    "secret_key":"${your_secret_key}",
    "region":"cn-beijing",
    "image_name":"packer_test_image",
    "source_image":"centos_7_03_64_20G_alibase_20170818.vhd",
    "ssh_username":"root",
    "instance_type":"ecs.n4.small",
    "internet_charge_type":"PayByTraffic",
    "io_optimized":"true"
  }],
  "provisioners": [{
    "type": "file",
    "source": "wordpress_init.sh",
    "destination": "/tmp/"
    },{
    "type": "shell",
    "inline": [
      "sleep 30",
      "cd /tmp",
      "sudo chmod 755 wordpress_init.sh",
      "./wordpress_init.sh"
    ]
  }]
}

這裡我們引用阿里雲的基礎映象:
"source_image":"centos_7_03_64_20G_alibase_20170818.vhd"
此外,還定義了一個WordPress應用環境初始化的shell指令碼wordpress_init.sh,這裡表示建立映象過程中,把本地的wordpress_init.sh遠端拷貝到臨時的VM上,並執行該指令碼,如下為wordpress_init.sh的內容:

#!/bin/bash

wordpress_url="https://cn.wordpress.org/wordpress-4.8.1-zh_CN.tar.gz"

# install httpd & php & php-mysql & wget
if grep -Eqi "Ubuntu|Debian|Raspbian" /etc/issue || grep -Eq "Ubuntu|Debian|Raspbian" /etc/*-release; then
        sudo apt-get update -y
        sudo apt-get install -y httpd
        sudo apt-get install -y php
        sudo apt-get install -y php-mysql
        sudo apt-get install -y wget
elif grep -Eqi "CentOS|Fedora|Red Hat Enterprise Linux Server" /etc/issue || grep -Eq "CentOS|Fedora|Red Hat Enterprise Linux Server" /etc/*-release; then
        sudo yum update -y
        sudo yum install -y httpd
        sudo yum install -y php
        sudo yum install -y php-mysql
        sudo yum install -y wget
else
        echo "Unknown OS type."
fi

# download wordpress pkg & configure wordpress
cd /root/
wget ${wordpress_url}
mkdir -p /var/www/html/
tar zxf wordpress-4.8.1-zh_CN.tar.gz -C /var/www/html/
cd /var/www/html/wordpress/
cp wp-config-sample.php wp-config.php
useradd apache
chown apache:apache /var/www/html/wordpress/

該指令碼通過安裝WordPress依賴的應用軟體包,以及建立賬號資訊,最終我們想要獲取的則為一個私有自定義映象。
image.png
將模板配置檔案和wordpress_init.sh指令碼檔案放置在同一個目錄下,通過$ packer build ${template_json_file} 即可完成自定義映象檔案的建立:
image.png

Terraform 建立雲資源

構建完預安裝好WordPress依賴軟體包的映象後,我們就可以開始編寫Terraform的資源構建模板檔案裡,如下的架構圖:
image.png
這裡將劃分一個VPC私網,初始購買2臺VM,掛載在一個開放公網IP的SLB下,後端資料持久化到RDS,並配置SNAT出公網的路由,同時支援一鍵擴容無個數限制的VM。

對於Terraform模板配置檔案主要分3個:

  • 主配置檔案 (定義建立的resource)
  • 變數配置檔案 (定義主配置檔案中指定的variables)
  • 輸出配置檔案 (定義terraform build執行完輸出的資訊)

Terraform 主配置檔案

provider "alicloud" {
  access_key = "${var.access_key}"
  secret_key = "${var.secret_key}"
  region = "${var.region}"
}

resource "alicloud_security_group" "sg" {
  name   = "terraform-sg"
  vpc_id = "${alicloud_vpc.vpc.id}"
}

resource "alicloud_security_group_rule" "allow_http" {
  type              = "ingress"
  ip_protocol       = "tcp"
  nic_type          = "intranet"
  policy            = "accept"
  port_range        = "80/80"
  priority          = 1
  security_group_id = "${alicloud_security_group.sg.id}"
  cidr_ip           = "0.0.0.0/0"
}

resource "alicloud_security_group_rule" "allow_ssh" {
  type              = "ingress"
  ip_protocol       = "tcp"
  nic_type          = "intranet"
  policy            = "accept"
  port_range        = "22/22"
  priority          = 2
  security_group_id = "${alicloud_security_group.sg.id}"
  cidr_ip           = "0.0.0.0/0"
}

resource "alicloud_vpc" "vpc" {
  name = "terraform-vpc"
  cidr_block = "192.168.0.0/16"
}

resource "alicloud_vswitch" "vsw" {
  vpc_id            = "${alicloud_vpc.vpc.id}"
  cidr_block        = "192.168.1.0/24"
  availability_zone = "${var.zone}"
}

resource "alicloud_nat_gateway" "nat_gateway" {
  vpc_id = "${alicloud_vpc.vpc.id}"
  spec   = "Small"
  name   = "wordpress_nat_gateway"

  bandwidth_packages = [{
    ip_count  = 1
    bandwidth = 5
  }]

  depends_on = [
    "alicloud_vswitch.vsw",
  ]
}

resource "alicloud_snat_entry" "foo" {
  snat_table_id     = "${alicloud_nat_gateway.nat_gateway.snat_table_ids}"
  source_vswitch_id = "${alicloud_vswitch.vsw.id}"
  snat_ip           = "${alicloud_nat_gateway.nat_gateway.bandwidth_packages.0.public_ip_addresses}"
}

resource "alicloud_slb" "slb" {
  name       = "wordpress-slb-tf"
  internet   = true
  internet_charge_type = "paybytraffic"

  listener = [ 
    {   
      "instance_port" = "80"
      "lb_port"       = "80"
      "lb_protocol"   = "tcp"
      "bandwidth"     = "10"
      "sticky_session" = "on"
      "sticky_session_type" = "insert"
      "cookie_timeout" = "1" 
      "health_check"  = "on"
      "health_check_type" = "tcp"
      "health_check_connect_port" = "80"
    }   
  ]

}

resource "alicloud_slb_attachment" "slb_attachment" {
  slb_id    = "${alicloud_slb.slb.id}"
  instances = ["${alicloud_instance.web.*.id}"]
}

resource "alicloud_instance" "web" {
  count = "${var.count}"
  instance_name = "${var.short_name}-${var.role}-${format(var.count_format, count.index+1)}"
  host_name = "${var.short_name}-${var.role}-${format(var.count_format, count.index+1)}"
  password = "${var.ecs_password}"
  availability_zone = "${var.zone}"
  image_id = "${var.image_id}"
  instance_type = "ecs.n4.small"
  io_optimized = "optimized"
  system_disk_category = "cloud_efficiency"
  security_groups = ["${alicloud_security_group.sg.id}"]
  vswitch_id = "${alicloud_vswitch.vsw.id}"
  user_data = "#!/bin/bash
sed -i `s/database_name_here/${var.database_name}/g` /var/www/html/wordpress/wp-config.php
sed -i `s/username_here/${var.database_user_name}/g` /var/www/html/wordpress/wp-config.php
sed -i `s/password_here/${var.database_user_password}/g` /var/www/html/wordpress/wp-config.php
sed -i `s/localhost/${alicloud_db_instance.rds.connections.0.connection_string}/g` /var/www/html/wordpress/wp-config.php
sed -i `s/utf8/utf8mb4/g` /var/www/html/wordpress/wp-config.php
service httpd stop
service httpd start" 
  depends_on = ["alicloud_db_instance.rds"]
}

resource "alicloud_db_instance" "rds" {
    engine = "MySQL"
    engine_version = "5.6"
    db_instance_class = "rds.mysql.t1.small"
    db_instance_storage = "10"
    db_instance_net_type = "Intranet"
    vswitch_id = "${alicloud_vswitch.vsw.id}"
    security_ips  = ["192.168.1.0/24"]

    master_user_name = "${var.database_user_name}"
    master_user_password = "${var.database_user_password}"

    db_mappings = [{
      db_name = "${var.database_name}"
      character_set_name = "${var.database_character}"
      db_description = "terraform wordpress"
    }]
}

如上主配置檔案定義了VPC和VSwitch,ECS和安全組(帶規則),SLB和掛載節點、VM個數等資源資訊:

  + alicloud_db_instance.rds
  + alicloud_instance.web[0]
  + alicloud_instance.web[1]
  + alicloud_nat_gateway.nat_gateway
  + alicloud_security_group.sg
  + alicloud_security_group_rule.allow_http
  + alicloud_security_group_rule.allow_ssh
  + alicloud_slb.slb
  + alicloud_slb_attachment.slb_attachment
  + alicloud_snat_entry.foo
  + alicloud_vpc.vpc
  + alicloud_vswitch.vsw

其中user_data 部分對wordpresss資料庫連線資訊做了格式化,需要留意的地方是該resource依賴alicloud_db_instance.rds 資訊,故必須指定depends_on引數。

Terraform 變數配置檔案

variable "count" {
  default = "2"
}
variable "access_key" {
  default = "{your_access_key}"
}
variable "secret_key" {
  default = "{your_secret_key}"
}
variable "region" {
  default = "cn-beijing"
}
variable "zone" {
  default = "cn-beijing-a"
}
variable "ecs_password" {
  default = "${ecs_password}"
}
variable "database_user_name" {
  default = "wordpress"
}
variable "database_user_password" {
  default = "${database_user_password}"
}
variable "database_name" {
  default = "wordpress"
}
variable "database_character" {
  default = "utf8"
}
variable "count_format" {
  default = "%02d"
}
variable "image_id" {
  default = "m-2zeapruq86du81hz56kb"
}
variable "availability_zones" {
  default = ""
}
variable "role" {
  default = "web"
}
variable "datacenter" {
  default = "beijing"
}
variable "short_name" {
  default = "wordpress"
}
variable "ecs_type" {
  default = "ecs.n4.small"
}
variable "allocate_public_ip" {
  default = true
}
variable "internet_charge_type" {
  default = "PayByTraffic"
}
variable "internet_max_bandwidth_out" {
  default = 5
}
variable "disk_category" {
  default = "cloud_efficiency"
}
variable "disk_size" {
  default = "40"
}
variable "nic_type" {
  default = "internet"
}

如上變數配置資訊,關鍵需要把前面通過Packer建立的映象ID填寫進去:

variable "image_id" {
  default = "m-2zeapruq86du81hz56kb"
}

Terraform 輸出配置檔案

output "address" {
  value = "${alicloud_slb.slb.address}"
}

output "rds_connection_string" {
    value = "${alicloud_db_instance.rds.connections.0.connection_string}"
}

對於輸出資訊,主要需要獲取SLB的公網IP,通過該IP訪問WordPress應用。

執行建立和驗證

確保如上的三個Terraform配置檔案放置於同一個目錄下,通過執行$ terraform apply,等待個10分鐘則可建立完成。

wangzhipengs-MacBook-Pro:wordpress4_packer wangzhipeng$ terraform apply
alicloud_vpc.vpc: Creating...
  cidr_block:      "" => "192.168.0.0/16"
  name:            "" => "terraform-vpc"
  router_id:       "" => "<computed>"
  router_table_id: "" => "<computed>"
alicloud_slb.slb: Creating...
  address:                                       "" => "<computed>"
  bandwidth:                                     "" => "<computed>"
  internet:                                      "" => "true"
  internet_charge_type:                          "" => "paybytraffic"
  listener.#:                                    "" => "1"
  listener.3892906561.bandwidth:                 "" => "10"
...(中間省略部分輸出資訊)

alicloud_slb_attachment.slb_attachment: Creation complete after 1s (ID: lb-2zeh8m9c6okymqk6bb2xz)

Apply complete! Resources: 12 added, 0 changed, 0 destroyed.

Outputs:

address = 47.95.95.152
rds_connection_string = rm-2ze57t716g530c19r.mysql.rds.aliyuncs.com

image.png

通過訪問 http://47.95.95.152/wordpress 完成下基礎配置,WordPress就搭建完成了。

image.png

總結

綜上,為實現在阿里雲平臺下Terraform+Packer一鍵部署WordPress,除了定義Packer的映象配置檔案,還需要定義好Terraform 資源模板檔案。這裡所體現的就是Infrastructure as Code的思想,一次編寫可多次執行,所有構建的資源都狀態化,也方便我們對資源進行有效管理,比如資源擴容、資源銷燬等。

回到這個案例,前面Packer 和 Terraform 配置檔案的準備工作就緒,我們只需要做的,就是一條terraform apply指令則可輕鬆構建一個WordPress應用。


相關文章