×
Community Blog Use Terraform to Quickly Deploy Magento by Alibaba Cloud ECS + RDS

Use Terraform to Quickly Deploy Magento by Alibaba Cloud ECS + RDS

This article focuses on using Terraform to quickly deploy Magento on Alibaba Cloud ECS + RDS.

Preface

This article is from Alibaba Cloud Advent Calendar 2023, focusing on launching services with Alibaba Cloud's Kubernetes and Serverless products like SAE.

I have been actively working on solutions, development techniques, and deployments by Alibaba Cloud, continuously striving to acquire cutting-edge technology from China and around the world.

The Advent Calendar serves as a platform to share these activities with the outside world. Through the articles written by each member, our goal is to generate interest in Alibaba Cloud among as many people as possible.

This article focuses on using Terraform to quickly deploy Magento on Alibaba Cloud ECS + RDS.

Magento is a popular open-source e-commerce platform with a strong track record. It is available as an open-source version, equipped with all necessary e-commerce features, making it easy to use for small startups and large-scale websites.

I recently wrote this article. Thinking about this more carefully, the whole system is installing and building websites and databases on Alibaba Cloud Container Service for Kubernetes (ACK). As such, it is not suitable for maintenance or expansion.

Therefore, the following steps will demonstrate how to build a Magento website based on an Elastic Compute Service (ECS) instance and an ApsaraDB RDS for MySQL instance. All necessary resources are used to quickly deploy common infrastructure configurations. However, to avoid the tedium of manual console work, we will use Terraform or Infrastructure as Code as the foundation for our deployment.

About This Tutorial

Intended Audience

This tutorial is intended for people who have basic knowledge about the following services:

Prerequisites

  • An Alibaba Cloud account is created.
  • ECS, ApsaraDB RDS, and VPC are activated.

Prepare Resources with Terraform

Refer to Alibaba Cloud Provider for Terraform and manage the relevant resources of Alibaba Cloud. This article follows the configuration diagram below.

1

Install Terraform in the Working Environment

Install the latest Terraform for the OS in use. For more information, see Install Terraform.

2

Prepare the Terraform Configuration File

Magento will be deployed as an Alibaba Cloud resource in Terraform, so define and set Alibaba Cloud resources and their dependencies based on Alibaba Cloud Provider, as shown in the following table.

3

Start preparing the related configuration files. main.tf defines resource information and dependencies.

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

data "alicloud_instance_types" "ecs_types" {
  availability_zone     = "${var.zone}"
  cpu_core_count        = "${var.cpu_core_count}"
  memory_size           = "${var.memory_size}"
}

resource "alicloud_vpc" "vpc" {
  vpc_name      = "${var.project_name}-vpc"
  cidr_block    = "${var.vpc_cidr}"
  description   = "Magento demo vpc"
}

resource "alicloud_vswitch" "vsw" {
  vswitch_name      = "${var.project_name}-vswitch"
  vpc_id            = "${alicloud_vpc.vpc.id}"
  cidr_block        = "${var.vswitch_cidr}"
  zone_id           = "${var.zone}"
  description       = "Magento demo vswitch"
}

resource "alicloud_security_group" "magento_server" {
  name          = "${var.project_name}-security-group"
  description   = "Enable HTTP access via port 80"
  vpc_id        = "${alicloud_vpc.vpc.id}"
}

resource "alicloud_security_group_rule" "allow_ssh" {
  type              = "ingress"
  ip_protocol       = "tcp"
  nic_type          = "intranet"
  policy            = "accept"
  port_range        = "22/22"
  priority          = 1
  security_group_id = "${alicloud_security_group.magento_server.id}"
  cidr_ip           = "${var.allow_ssh_ip}"
}

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.magento_server.id}"
  cidr_ip           = "0.0.0.0/0"
}

resource "alicloud_instance" "magento_instance" {
  availability_zone          = "${var.zone}"
  security_groups            = ["${alicloud_security_group.magento_server.id}"]
  instance_type              = "${data.alicloud_instance_types.ecs_types.instance_types.0.id}"
  system_disk_category       = "cloud_efficiency"
  image_id                   = "centos_7_9_x64_20G_alibase_20210824.vhd"
  instance_name              = "${var.project_name}-ecs"
  vswitch_id                 = "${alicloud_vswitch.vsw.id}"
  internet_max_bandwidth_out = 5
  instance_charge_type       = "PostPaid"
  key_name                   = "${var.ecs_key_name}"
  user_data                  = "${file("magento.sh")}"
}

resource "alicloud_db_instance" "magento_db" {
  engine                    = "MySQL"
  engine_version            = "5.7"
  zone_id                   = "${var.zone}"
  instance_type             = "${var.db_instance_type}"
  instance_storage          = "30"
  instance_charge_type      = "Postpaid"
  instance_name             = "${var.project_name}-rds-mysql"
  vswitch_id                = "${alicloud_vswitch.vsw.id}"
  security_ips              = ["${alicloud_instance.magento_instance.private_ip}"]
  monitoring_period         = "60"
}

resource "alicloud_db_account" "account" {
  db_instance_id      = "${alicloud_db_instance.magento_db.id}"
  account_name        = "${var.db_account}"
  account_password    = "${var.db_password}"
  account_description = "Magento demo db account"
}

resource "alicloud_db_database" "db" {
  instance_id = "${alicloud_db_instance.magento_db.id}"
  name        = "${var.database_name}"
  description = "Magento demo database"
}

resource "alicloud_db_account_privilege" "privilege" {
  instance_id  = "${alicloud_db_instance.magento_db.id}"
  account_name = "${var.db_account}"
  db_names     = ["${var.database_name}"]
  privilege    = "ReadWrite"
}

variables.tf defines variables and their default values (if they exist).

variable "access_key" {

}

variable "secret_key" {

}

variable "region" {
    default = "ap-northeast-1"
}

variable "zone" {
    default = "ap-northeast-1a"
}

variable "cpu_core_count" {
    default = "2"
}

variable "memory_size" {
    default = "4"
}

variable "project_name" {
    default = "magento-demo"
}

variable "vpc_cidr" {
  default = "172.16.0.0/12"
}

variable "vswitch_cidr" {
  default = "172.16.0.0/21"
}

variable "allow_ssh_ip" {
    
}

variable "ecs_key_name" {

}

variable "db_instance_type" {
    default = "mysql.n2.medium.1"
}

variable "db_account" {
    default = "magento"
}

variable "db_password" {

}

variable "database_name" {
    default = "magento"
}

outputs.tf defines the values generated after the creation process is complete. To configure Magento manually, the following information is necessary:

  • Public IP address of the ECS instance
  • Private IP address of the ECS instance
  • Connection information of the ApsaraDB RDS for MySQL instance
output "Magento-Server-Public-IP" {
  value = "${alicloud_instance.magento_instance.public_ip}"
}

output "Magento-Server-Private-IP" {
  value = "${alicloud_instance.magento_instance.private_ip}"
}

output "Magento-DB-Connection-String" {
  value = "${alicloud_db_instance.magento_db.connection_string}"
}

versions.tf defines the version requirement for Terraform.

terraform {
  required_version = ">= 1.6.6"
}

config.tfvars defines specific values for the variables that do not have default values. If the information is unknown at this point, it can be filled in later, but it can be entered interactively.

access_key = "xxxxxxxxxxxxxx"
secret_key = "xxxxxxxxxxxxxx"
allow_ssh_ip = "xxxxxxxxxxxxxx"
ecs_key_name = "xxxxxxxxxxxxxx"
db_password = "xxxxxxxxxxxxxx"

4

In addition to these Terraform configuration files, a shell script file that defines the initial operation of the Magento working environment is needed when the ECS instance is ready.

Follow Magento Quick Installation to update the latest Magento as needed. Take Magento V2.1.0 as an example based on Alibaba Help Doc.

#!/bin/bash

# Install Apache
echo "Apache phase" > /root/test.log
yum install httpd -y
httpd -v >> /root/test.log

# Update Apache configuration file - httpd.conf
line=`sed -n '/conf.modules.d/=' /etc/httpd/conf/httpd.conf`
sed -i "${line}a LoadModule rewrite_module modules/mod_rewrite.so\n" /etc/httpd/conf/httpd.conf
sed -i "/\"\/var\/www\/html\">/,/<\/Directory>/ s/AllowOverride None/AllowOverride All/" /etc/httpd/conf/httpd.conf


# Start Apache service
systemctl start httpd
systemctl enable httpd

# Install PHP
echo "Php phase" >> /root/test.log
yum -y install https://repo.ius.io/ius-release-el7.rpm https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm unzip
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
yum -y install php70w php70w-pdo php70w-mysqlnd php70w-opcache php70w-xml php70w-gd php70w-mcrypt php70w-devel php70w-intl php70w-mbstring php70w-bcmath php70w-json php70w-iconv php70w-soap

php -v >> /root/test.log

# Update PHP configuration file - php.ini
sed -i '$a\\nmemory_limit = 1024M\ndate.timezone = Asia\/Tokyo' /etc/php.ini

# Restart Apache
systemctl restart httpd

# Install Composer
echo "Composer phase" >> /root/test.log
wget https://getcomposer.org/download/latest-1.x/composer.phar
chmod +x composer.phar
cp composer.phar /usr/bin/composer

# Install Git
echo "Git phase" >> /root/test.log
yum -y install git

# Install Magento
echo "Magento phase" >> /root/test.log
cd /var/www/html/
git clone https://github.com/magento/magento2.git
cd magento2 &&  git checkout tags/2.1.0 -b 2.1.0
shopt -s dotglob nullglob && mv /var/www/html/magento2/* /var/www/html/ && cd ..
chown -R :apache /var/www/html
find /var/www/html -type f -print0 | xargs -r0 chmod 640
find /var/www/html -type d -print0 | xargs -r0 chmod 750
chmod -R g+w /var/www/html/{pub,var}
chmod -R g+w /var/www/html/{app/etc,vendor}
chmod 750 /var/www/html/bin/magento

# Check Apache service status
systemctl status httpd >> /root/test.log
echo "Done Successfully" >> /root/test.log
echo "Please run 'cd /var/www/html/ && composer install' manually to finish magento installation." >> /root/test.log

Run in Terraform

When all the files above are set up, you should have the following 6 files:

5

Run terraform init to download the required provider and initialize the working directory.

6

Generate an action plan with the following configuration: terraform plan -var-file="config.tfvars".

7

If the above terraform plan command is successful, run the action plan with the following configuration: terraform apply -var-file="config.tfvars".

8

If this runs successfully, the following message will be displayed:

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

Outputs:

Magento-DB-Connection-String = "rm-xxxxxxxxxxx.mysql.japan.rds.aliyuncs.com"
Magento-Server-Private-IP = "xxxxx"
Magento-Server-Public-IP = "xxxxx"

9

Check whether this Terraform execution is properly reflected in Alibaba Cloud-related resources one by one.

10
11
12
13
14
15
16
17

Alibaba Cloud-related resources have also been created properly.

Copy and paste the public IP address of the created ECS instance into the web browser and try to open it on port 80. The error message Autoload error Vendor autoload is not found. Please run 'composer install' under application root directory. is displayed, as shown in the following figure.

18

Log on to ECS from the allow_ssh_ip defined above. If a different IP address is used, you will be blocked by the security group. So, first check the log at /root/test.log in ECS.

19

The log says Please run 'cd /var/www/html/ && composer install' manually to finish magento installation. So, let's just run cd /var/www/html/ && composer install to finish the Magento installation process!

20

After Magento is installed, check the status with systemctl status httpd. If it is active (running), proceed to the next step.

21

When the public IP address of the created ECS instance is accessed on port 80 again, the Magento setup wizard appears.

22

Install the Magento Server

Click Agree and Setup Magento in the Magento setup wizard.

23

Step 1 is displayed. Clicking Start Readiness Check will kick off the preparation check.

24

Click Next to enter Step 2. In the Add a Database step, use Magento-DB-Connection-String in the output of the database server host to configure the database connection. If you don't remember the value, you can obtain it from the RDS instance management page. Database name, username, and password are defined as Terraform variables above, so enter them accordingly.

25

In Step 3, perform the web configuration, update the administrator address, and save the session information to a database. Also, expand Advanced Options and set Session Save to Db.

26

In Step 4, set the configuration based on your business requirements. The default values are used this time.

27

Create an administrator account in Step 5.

28

In Step 6, install Magento unless there's been a problem with the preceding configuration.

29

If the installation is successful, the screen will look like this:

30

Check the home page of the Magento store. Since it is not set up yet, the page would look like the following:

31

Check the Magento administrator management page and log in with the administrator account created in the preceding steps.

32

If you log in successfully, you will see a dashboard like this.

33

Conclusion

ECS and ApsaraDB RDS for MySQL were used for the deployment. However, SAE and PolarDB might be better for scalability, whereas SAE and serverless RDS might be more cost-effective. If you want to use Magento on Alibaba Cloud, you can refer to this article.


This article is translated from Qiita.

Disclaimer: The views expressed herein are for reference only and don't necessarily represent the official views of Alibaba Cloud.

0 1 0
Share on

H Ohara

12 posts | 0 followers

You may also like

Comments