前言
前面 云生态下的基础架构资源管理利器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依赖的应用软件包,以及创建账号信息,最终我们想要获取的则为一个私有自定义镜像。
将模板配置文件和wordpress_init.sh脚本文件放置在同一个目录下,通过$ packer build ${template_json_file}
即可完成自定义镜像文件的创建:
Terraform 创建云资源
构建完预安装好WordPress依赖软件包的镜像后,我们就可以开始编写Terraform的资源构建模板文件里,如下的架构图:
这里将划分一个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\nsed -i 's/database_name_here/${var.database_name}/g' /var/www/html/wordpress/wp-config.php\nsed -i 's/username_here/${var.database_user_name}/g' /var/www/html/wordpress/wp-config.php\nsed -i 's/password_here/${var.database_user_password}/g' /var/www/html/wordpress/wp-config.php\nsed -i 's/localhost/${alicloud_db_instance.rds.connections.0.connection_string}/g' /var/www/html/wordpress/wp-config.php\nsed -i 's/utf8/utf8mb4/g' /var/www/html/wordpress/wp-config.php\nservice httpd stop\nservice 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
通过访问 http://47.95.95.152/wordpress 完成下基础配置,WordPress就搭建完成了。
总结
综上,为实现在阿里云平台下Terraform+Packer一键部署WordPress,除了定义Packer的镜像配置文件,还需要定义好Terraform 资源模板文件。这里所体现的就是Infrastructure as Code的思想,一次编写可多次运行,所有构建的资源都状态化,也方便我们对资源进行有效管理,比如资源扩容、资源销毁等。
回到这个案例,前面Packer 和 Terraform 配置文件的准备工作就绪,我们只需要做的,就是一条terraform apply指令则可轻松构建一个WordPress应用。