Kiến thức cơ bản về bộ công cụ Cloud Foundation

1. Giới thiệu về CFT 101

ea557448aaa1fffc.png

Lần cập nhật gần đây nhất: ngày 3 tháng 03 năm 2020

Bộ công cụ Cloud Foundation là gì?

Về cơ bản, CFT cung cấp các mẫu phương pháp hay nhất để nhanh chóng bắt đầu sử dụng Google Cloud Platform. Trong hướng dẫn này, bạn sẽ tìm hiểu cách đóng góp cho Cloud Foundation Toolkit.

Bạn cần có

  • Tài khoản GitHub.
  • Docker được cài đặt trên máy của bạn ( cài đặt trên máy Mac, cài đặt Windows)
  • Trình soạn thảo mã để chỉnh sửa mã (Ví dụ: Visual Studio Code)
  • Hiểu biết cơ bản về Git và GitHub
  • Có kinh nghiệm sử dụng Terraform và cơ sở hạ tầng dưới dạng mã nguồn
  • Quyền cấp vai trò Người tạo dự án cho Tài khoản dịch vụ

Sản phẩm bạn sẽ tạo ra

Trong lớp học lập trình này, bạn sẽ tìm hiểu cách đóng góp cho Bộ công cụ nền tảng đám mây (CFT).

Bạn sẽ:

  • Thiết lập môi trường nhà phát triển để đóng góp cho CFT
  • Thêm một tính năng vào mô-đun CFT
  • Thêm thử nghiệm cho tính năng đã thêm
  • Thực thi thử nghiệm tích hợp trong CFT
  • Thực thi kiểm thử tìm lỗi mã nguồn
  • Xác nhận mã với GitHub và gửi một Yêu cầu kéo (PR)

Bạn sẽ thực hiện tất cả các bước trên bằng cách thêm một tính năng mới vào mô-đun CFT của Google Cloud Storage. Bạn sẽ thêm một nhãn có tên là "silly_label". Nhãn này sẽ được tự động thêm vào tất cả các bộ chứa được tạo thông qua mô-đun CFT của GCS. Bạn cũng sẽ được viết bài kiểm thử để xác thực tính năng và đảm bảo tích hợp toàn diện.

2. Thiết lập môi trường phát triển

Nếu muốn, bạn có thể sử dụng Cloud Shell cho mục đích phát triển của mình. Nếu không muốn sử dụng Cloud Shell để đóng góp cho CFT, bạn có thể thiết lập môi trường phát triển trên máy của mình.

Thiết lập Git

GitHub dựa trên hệ thống quản lý phiên bản nguồn mở (VCS) có tên là Git. Git chịu trách nhiệm về mọi thứ liên quan đến GitHub diễn ra cục bộ trên máy hoặc Cloud Shell của bạn.

  1. Khi sử dụng Cloud Shell, bạn không cần cài đặt git vì nó được cài đặt sẵn.
$ git --version
# This will display the git version on the Cloud Shell.

Nếu bạn đang thiết lập môi trường nhà phát triển trên máy của mình, bạn cần cài đặt Git.

Đặt tên người dùng và email của bạn trong Git

Git sử dụng tên người dùng để liên kết các cam kết với một danh tính. Tên người dùng Git không giống với tên người dùng GitHub của bạn.

Bạn có thể thay đổi tên được liên kết với các cam kết Git của mình bằng cách sử dụng lệnh git config. Việc thay đổi tên liên kết với các cam kết Git của bạn bằng git config sẽ chỉ ảnh hưởng đến các cam kết trong tương lai và sẽ không thay đổi tên dùng cho các cam kết trước đó.

Bạn đã thiết lập Git thành công và bạn có thể phát triển nhánh, tạo và sao chép các nhánh. Chúng ta sẽ sử dụng Git một cách rộng rãi trong Lớp học lập trình này.

3. Kho lưu trữ GCS của Fork CFT

Phân nhánh kho lưu trữ CFT

Bạn thiết lập Git trên máy cục bộ hoặc Cloud Shell ở bước trước. Bây giờ, bạn cần chia tách kho lưu trữ CFT của Google Cloud Storage để bắt đầu đóng góp.

Nĩa là một bản sao của kho lưu trữ. Việc phân nhánh kho lưu trữ cho phép bạn thoải mái thử nghiệm các thay đổi mà không ảnh hưởng đến dự án gốc.

Thông thường, nhánh phát triển được dùng để đề xuất thay đổi đối với dự án của người khác hoặc sử dụng dự án của người khác làm điểm khởi đầu cho ý tưởng của riêng bạn.

Ví dụ: bạn có thể sử dụng nhánh phát triển để đề xuất thay đổi liên quan đến việc sửa lỗi. Để sửa lỗi, bạn có thể:

  • Phát triển nhánh kho lưu trữ.
  • Khắc phục vấn đề.
  • Gửi yêu cầu lấy dữ liệu (pull request) cho chủ sở hữu dự án.

Các bước để phân nhánh một kho lưu trữ CFT:

  1. Mở trình duyệt web rồi chuyển đến kho lưu trữ terraform-google-modules/terraform-google-cloud-storage. Chúng ta sẽ sử dụng kho lưu trữ này cho toàn bộ Lớp học lập trình.
  2. Ở góc trên cùng bên phải trang, hãy nhấp vào Nĩa.

e3894c6de6a732b4.png

  1. Bạn sẽ thấy tuỳ chọn nơi bạn muốn dùng nhánh phát triển, chọn hồ sơ của mình và kho lưu trữ sẽ được phát triển nhánh.

Nhân bản nhánh phát triển trên thiết bị

Đĩa mà bạn đã tạo là một bản sao của kho lưu trữ mô-đun GCS. Bây giờ, bạn sẽ sao chép kho lưu trữ này vào môi trường cục bộ để thêm tính năng mới.

Các bước sao chép nhánh phát triển:

  1. Mở trình duyệt web và chuyển đến ngã ba của bạn trên terraform-google-modules/terraform-google-cloud-storage.
  2. Ở góc trên cùng bên phải, bạn sẽ thấy nút "Sao chép hoặc tải xuống" nhấp vào nút.

3bfa87b9f7f01f61.pngS

  1. Sau khi bạn nhấp vào nút "Sao chép hoặc tải xuống" hãy nhấp vào "Notepad" để sao chép URL của ngã ba. Bạn sẽ dùng URL này để sao chép nhánh phát triển của mình sang môi trường địa phương.

dbf3682d004e0ee0.png

  1. Chuyển đến một thiết bị đầu cuối trong VSCode hoặc máy của bạn rồi sao chép ngã ba.
$ git clone <url>
# This command will clone your fork locally.
# Paste the copied URL from the previous step.
  1. Bây giờ, sau khi đã sao chép nhánh phát triển cục bộ, bạn nên truy cập vào kho lưu trữ của mình, tạo một nhánh mới ngoài nhánh phát triển đó và thay đổi mã cho nhánh tạm thời.

Theo quy ước, bạn có thể đặt tên cho nhánh của mình như sau:

  • Đối với các yêu cầu về tính năng: feature/feature-name
  • Để cập nhật nội bộ, hãy internal/change-name
  • Để sửa lỗi: bugfix/issue-name

Vì bạn đang thêm một tính năng mới, nên bạn có thể gọi nhánh tạm thời feature/silly_label

$ cd terraform-google-cloud-storage
# This command takes you into the cloned directory on your local machine.

$ git branch
# This command tells your current branch
# When you run this for the first time after you have cloned, your 
# output should say "master", that is your fork.

$ git checkout -b feature/silly_label
# This command creates a new branch on your fork and switches your 
# branch to the newly created branch.

$ git branch
# This command will confirm your current branch to be "feature/silly_label"

Giờ đây, bạn đã thiết lập xong để bắt đầu làm việc trên Bộ công cụ nền tảng đám mây!

4. Tạo môi trường kiểm thử

Quy trình phát triển CFT tiêu chuẩn dựa trên việc sử dụng một dự án thử nghiệm tách biệt để kiểm thử. Bước này sẽ hướng dẫn bạn tạo dự án thử nghiệm (dựa trên cấu hình chuẩn) thông qua tài khoản dịch vụ.

0. Cài đặt Docker Engine

Nếu đang sử dụng máy cho mục đích phát triển, bạn cần cài đặt Docker Engine.

1. Cài đặt Google Cloud SDK

Bạn không cần cài đặt Google Cloud SDK nếu đang sử dụng GCP Cloud Shell.

Truy cập vào Google Cloud SDK và tải trình cài đặt tương tác xuống cho nền tảng của bạn.

2. Đặt cấu hình

Để tạo một môi trường thử nghiệm, bạn cần có một Tổ chức trên Google Cloud, một thư mục thử nghiệm và một tài khoản thanh toán. Bạn cần đặt các giá trị này thông qua các biến môi trường:

export TF_VAR_org_id="your_org_id"
export TF_VAR_folder_id="your_folder_id"
export TF_VAR_billing_account="your_billing_account_id"

3 Thiết lập tài khoản dịch vụ

Trước khi tạo môi trường thử nghiệm, bạn cần tải khoá tài khoản dịch vụ xuống môi trường thử nghiệm. Tài khoản dịch vụ này sẽ cần có các vai trò Người tạo dự án, Người dùng tài khoản thanh toánNgười xem tổ chức. Những bước này giúp bạn tạo một tài khoản dịch vụ mới, nhưng bạn cũng có thể sử dụng lại tài khoản hiện có.

3.1 Tạo hoặc chọn dự án GCP gốc

Trước khi tạo tài khoản dịch vụ, bạn cần chọn một dự án để lưu trữ tài khoản đó. Bạn cũng có thể tạo một dự án mới.

gcloud config set core/project YOUR_PROJECT_ID

3.2 Bật API Google Cloud

Bật các API Google Cloud sau đây trong dự án gốc của bạn:

gcloud services enable cloudresourcemanager.googleapis.com
gcloud services enable iam.googleapis.com
gcloud services enable cloudbilling.googleapis.com

3.3 Tạo tài khoản dịch vụ

Tạo một tài khoản dịch vụ mới để quản lý môi trường thử nghiệm:

# Creating a service account for CFT.
gcloud iam service-accounts create cft-onboarding \
  --description="CFT Onboarding Terraform Service Account" \
  --display-name="CFT Onboarding"

# Assign SERVICE_ACCOUNT environment variable for later steps
export SERVICE_ACCOUNT=cft-onboarding@$(gcloud config get-value core/project).iam.gserviceaccount.com

Xác minh tài khoản dịch vụ của bạn đã được tạo:

gcloud iam service-accounts list --filter="EMAIL=${SERVICE_ACCOUNT}"

3.4 Cấp vai trò Người tạo dự án, Người dùng tài khoản thanh toán và Người xem của tổ chức cho Tài khoản dịch vụ:

gcloud resource-manager folders add-iam-policy-binding ${TF_VAR_folder_id} \
  --member="serviceAccount:${SERVICE_ACCOUNT}" \
  --role="roles/resourcemanager.projectCreator"
gcloud organizations add-iam-policy-binding ${TF_VAR_org_id} \
  --member="serviceAccount:${SERVICE_ACCOUNT}" \
  --role="roles/billing.user"
gcloud organizations add-iam-policy-binding ${TF_VAR_org_id} \
  --member="serviceAccount:${SERVICE_ACCOUNT}" \
  --role="roles/resourcemanager.organizationViewer"

Bây giờ, bạn đã có Tài khoản dịch vụ có thể dùng để quản lý môi trường thử nghiệm.

4. Chỉ định vai trò của Người dùng tài khoản thanh toán đối với tài nguyên tài khoản thanh toán

4.1 Tìm nạp chính sách IAM của tài khoản thanh toán

Tải các liên kết chính sách IAM hiện có trên tài khoản thanh toán xuống

gcloud beta billing accounts get-iam-policy ${TF_VAR_billing_account} | tee policy.yml

4.2 Cập nhật chính sách để thêm Tài khoản dịch vụ

Cập nhật tệp policy.yml để thêm một liên kết mới cho tài khoản dịch vụ có vai trò roles/billing.user

bindings:
- members:
  - serviceAccount:cft-onboarding@<YOUR_PROJECT_ID>.iam.gserviceaccount.com
  role: roles/billing.user

4.3 Cập nhật chính sách về tài khoản thanh toán

Áp dụng các thay đổi đối với tài khoản thanh toán

gcloud beta billing accounts set-iam-policy ${TF_VAR_billing_account} policy.yml

5. Chuẩn bị thông tin xác thực Terraform

Để tạo môi trường kiểm thử, bạn cần tải khoá tài khoản dịch vụ xuống shell.

5.1 Khoá tài khoản dịch vụ

Tạo và tải khoá tài khoản dịch vụ xuống Terraform

gcloud iam service-accounts keys create cft.json --iam-account=${SERVICE_ACCOUNT}

5.2 Thiết lập thông tin đăng nhập Terraform

Cung cấp khoá cho Terraform bằng biến môi trường SERVICE_ACCOUNT_JSON, đặt giá trị thành nội dung của khoá tài khoản dịch vụ.

export SERVICE_ACCOUNT_JSON=$(< cft.json)

6. Tạo dự án thử nghiệm để triển khai Terraform

Giờ thì mọi thứ đã sẵn sàng, bạn có thể tạo dự án kiểm thử bằng một lệnh duy nhất. Chạy lệnh này từ gốc của thư mục terraform-google-cloud-storage:

make docker_test_prepare

Bạn sẽ thấy kết quả bên dưới khi chạy make docker_test_prepare. Cuối cùng , bạn sẽ nhận được project_id kiểm thử đã được tạo để triển khai và kiểm thử mô-đun Cloud Storage bằng tính năng mới.

macbookpro3:terraform-google-cloud-storage user$ make docker_test_prepare
docker run --rm -it \
                -e SERVICE_ACCOUNT_JSON \
                -e TF_VAR_org_id \
                -e TF_VAR_folder_id \
                -e TF_VAR_billing_account \
                -v /Users/cft/terraform-google-cloud-storage:/workspace \
                gcr.io/cloud-foundation-cicd/cft/developer-tools:0.8.0 \
                /usr/local/bin/execute_with_credentials.sh prepare_environment
Activated service account credentials for: [cft-onboarding@<project_id>.iam.gserviceaccount.com]
Activated service account credentials for: [cft-onboarding@<project_id>.iam.gserviceaccount.com]
Initializing modules...

Initializing the backend...

Initializing provider plugins...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.google-beta: version = "~> 3.9"
* provider.null: version = "~> 2.1"
* provider.random: version = "~> 2.2"

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
module.project.module.project-factory.null_resource.preconditions: Refreshing state... [id=8723188031607443970]
module.project.module.project-factory.null_resource.shared_vpc_subnet_invalid_name[0]: Refreshing state... [id=5109975723938185892]
module.project.module.gsuite_group.data.google_organization.org[0]: Refreshing state...
module.project.module.project-factory.random_id.random_project_id_suffix: Refreshing state... [id=rnk]
module.project.module.project-factory.google_project.main: Refreshing state... [id=<project-id>]
module.project.module.project-factory.google_project_service.project_services[0]: Refreshing state... [id=<project-id>/storage-api.googleapis.com]
module.project.module.project-factory.google_project_service.project_services[1]: Refreshing state... [id=<project-id>/cloudresourcemanager.googleapis.com]
module.project.module.project-factory.google_project_service.project_services[2]: Refreshing state... [id=<project-id>/compute.googleapis.com]
module.project.module.project-factory.data.null_data_source.default_service_account: Refreshing state...
module.project.module.project-factory.google_service_account.default_service_account: Refreshing state... [id=projects/ci-cloud-storage-ae79/serviceAccounts/project-service-account@<project-id>.iam.gserv
iceaccount.com]
module.project.module.project-factory.google_project_service.project_services[3]: Refreshing state... [id=<project-id>/serviceusage.googleapis.com]
module.project.module.project-factory.null_resource.delete_default_compute_service_account[0]: Refreshing state... [id=3576396874950891283]
google_service_account.int_test: Refreshing state... [id=projects/<project-id>/serviceAccounts/cft-onboarding@<project-id>.iam.gserviceaccount.com]
google_service_account_key.int_test: Refreshing state... [id=projects/<project-id>/serviceAccounts/cft-onboarding@<project-id>.iam.gserviceaccount.com/keys/351009a1e011e88049ab2097994d1c627a61
6961]
google_project_iam_member.int_test[1]: Refreshing state... [id=<project-id>/roles/iam.serviceAccountUser/serviceaccount:cft-onboarding@<project-id>.iam.gserviceaccount.com]
google_project_iam_member.int_test[0]: Refreshing state... [id=<project-id>/roles/storage.admin/serviceaccount:cft-onboarding@<project-id>.iam.gserviceaccount.com]

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

Outputs:

project_id = <test-project-id>
sa_key = <sensitive>
Found test/setup/make_source.sh. Using it for additional explicit environment configuration.

Giờ đây, bạn đã tạo một dự án kiểm thử được project_id tham chiếu như có thể thấy trên kết quả của bảng điều khiển. Môi trường phát triển và kiểm thử của bạn đã được thiết lập.

5. Thêm tính năng mới vào mô-đun CFT

Bây giờ, môi trường phát triển và kiểm thử của bạn đã được thiết lập. Hãy bắt đầu thêm "silly_label" cho mô-đun CFT google-cloud-storage.

Đảm bảo bạn đang ở trong terraform-google-cloud-storage và mở tệp main.tf như bạn thấy dưới đây trong cấu trúc thư mục.

17f2d3b9893be853.pngS

Từ "silly_label" là một nhãn, bạn sẽ thêm tính năng ở dòng 27 trong biến "nhãn" trong main.tf, như bạn thấy dưới đây:

terraform-google-cloud-storage/main.tf

resource "google_storage_bucket" "buckets" {
 <...>
 storage_class = var.storage_class
 // CODELAB:Add silly label in labels variable
 labels        = merge(var.labels, { name = replace("${local.prefix}${lower(element(var.names, count.index))}", ".", "-") }, { "silly" = var.silly_label })
 force_destroy = lookup(
 <...>
}

Bây giờ, bạn sẽ thêm biến silly_label trong các biến.tf mà bạn thấy trong cấu trúc thư mục ở trên.

Sao chép, dán mã bên dưới và thêm mã đó vào dòng 29 trong Variable.tf và đảm bảo bạn thêm một ký tự dòng mới ở phía trên và bên dưới khối biến mà bạn thêm.

terraform-google-cloud-storage/variables.tf

variable "names" {
 description = "Bucket name suffixes."
 type        = list(string)
}

// CODELAB: Add "silly_label" variable to variables.tf between "names" and "location"
variable "silly_label" {
 description = "Sample label for bucket."
 type        = string
}

variable "location" {
 description = "Bucket location."
 default     = "EU"
}

6. Thêm một tính năng mới vào ví dụ về bộ chứa lưu trữ

Bạn đã thêm tính năng vào main.tf của mô-đun và bây giờ, bạn sẽ kiểm tra tính năng đã thêm thông qua một ví dụ.

Thuộc tính "silly_label" sẽ cần được thêm vào ví dụ/nhiều bộ chứa/main.tf

Công cụ cố định sẽ sử dụng ví dụ này trong bước tiếp theo để tiến hành kiểm thử tích hợp.

Sao chép và dán dòng silly_label biến dưới đây vào dòng 27 trong main.tf tại terraform-google-cloud-storage/examples/multiple-buckets/ như trong cấu trúc thư mục:

408cb1365b2a0793.pngS

terraform-google-cloud-storage/examples/multiple-buckets/main.tf

module "cloud_storage" {
 <...>
 // CODELAB: Add "silly_label" as an example to main.tf.
 silly_label        = "awesome"

 <..>
}

7. Viết bài kiểm thử Inspec để kiểm tra tính năng

Bạn đã thêm tính năng vào main.tf của mô-đun, sau đó thêm tính năng vào ví dụ về nhiều_buckets để kiểm thử thông qua môi trường cố định. Bạn cần kiểm thử tính năng của mình thông qua kiểm thử tích hợp InSpec được viết bằng Ruby.

Bạn sẽ thêm các thử nghiệm mới trong tệp GCR.rb được tìm thấy trong cấu trúc thư mục bên dưới:

b2bfeb203477e0c8.png

Bạn đã thêm thuộc tính "silly_label" trên tất cả các bộ chứa được tạo thông qua mô-đun nhiều_buckets và bây giờ, bạn cần viết mã kiểm thử để kiểm thử tính năng mới.

Trong mã dưới đây, bạn sẽ nhận được nhãn của mỗi nhóm thông qua lệnh GCR, sau đó bạn kiểm tra kết quả được trả về từ lệnh.

terraform-google-cloud-storage/test/integration/multiple-buckets/controls/gsutil.rb

control "gsutil" do
 <..>

# CODELAB: Copy paste the below test in gsutil.rb to test silly_label feature.

# command to get the labels for bucket_1
describe command("gsutil label get gs://#{attribute("names_list")[0]}") do
   //check if the command gave a valid response
   its(:exit_status) { should eq 0 }
   its(:stderr) { should eq "" }

   //parse the command's output into JSON
   let!(:data) do
     if subject.exit_status == 0
         JSON.parse(subject.stdout)
     else
         {}
     end
   end

   # check if bucket_1 has the new "silly" label with the value "awesome"
   describe "bucket_1" do
   it "has label" do
       data.each do |bucket|
           expect(data["silly"]).to include("awesome")
       end
     end
   end
 end

8. Thực thi thử nghiệm tích hợp trong CFT

Kiểm thử tích hợp

Kiểm thử tích hợp được dùng để xác minh hành vi của mô-đun gốc, mô-đun con và mô-đun mẫu. Các hoạt động bổ sung, thay đổi và sửa lỗi phải được thực hiện cùng với bài kiểm thử.

Các thử nghiệm tích hợp được chạy bằng Kitchen, Kitchen-TerraformInSpec. Các công cụ này được đóng gói trong một hình ảnh Docker để thuận tiện.

Chiến lược chung cho những chương trình kiểm thử này là xác minh hành vi của các mô-đun mẫu, qua đó đảm bảo rằng mô-đun gốc, mô-đun con và mô-đun mẫu đều có chức năng chính xác.

Trong quá trình thực thi có tính tương tác, bạn sẽ thực thi từng bước thông qua nhiều lệnh.

  1. Chạy make docker_run để bắt đầu kiểm thử vùng chứa Docker ở chế độ tương tác.

Make là một công cụ tự động hoá bản dựng có thể tự động tạo các chương trình và thư viện có thể thực thi từ mã nguồn bằng cách đọc các tệp có tên Makefiles, chỉ định cách lấy chương trình mục tiêu. Khi bạn thay đổi tệp, vùng chứa Docker phải được cập nhật tự động.

Khi chạy make docker_run, bạn sẽ tạo một không gian làm việc trong vùng chứa Docker và kích hoạt thông tin đăng nhập cho tài khoản dịch vụ của bạn. Không gian làm việc này sẽ được dùng trong các bước tiếp theo để chạy kiểm thử.

Bạn sẽ thấy kết quả dưới đây trong dòng lệnh:

Activated service account credentials for: [cft@<PROJECT_ID>.iam.gserviceaccount.com]
  1. Chạy kitchen_do list để liệt kê tất cả thực thể trong không gian làm việc có chứa thử nghiệm tích hợp.
     You will see the below output in your terminal.
    
[root@<CONTAINER_ID> workspace]# kitchen_do list
Automatically setting inputs from outputs of test/setup
Found test/source.sh. Using it for additional explicit environment configuration.
Activated service account credentials for: [cft@<PROJECT_ID>.iam.gserviceaccount.com]
Instance                  Driver     Provisioner  Verifier   Transport  Last Action  Last Error
multiple-buckets-default  Terraform  Terraform    Terraform  Ssh        Verified     <None>
  1. Chạy kitchen_do create <EXAMPLE_NAME> để khởi tạo thư mục đang hoạt động cho một mô-đun mẫu.

Bước này khởi chạy nhà bếp và khởi chạy địa hình trong không gian làm việc.

Bạn sẽ thấy kết quả bên dưới trong dòng lệnh.

[root@<CONTAINER_ID> workspace]# kitchen_do create multiple-buckets-default
Automatically setting inputs from outputs of test/setup
Found test/source.sh. Using it for additional explicit environment configuration.
Activated service account credentials for: [cft@<PROJECT_ID>.iam.gserviceaccount.com]
-----> Starting Kitchen (v1.24.0)
-----> Creating <multiple-buckets-default>...
       Terraform v0.12.12
       + provider.google v3.10.0
       
       Your version of Terraform is out of date! The latest version
       is 0.12.21. You can update by downloading from www.terraform.io/downloads.html
$$$$$$ Running command `terraform init -input=false -lock=true -lock-timeout=0s  -upgrade -force-copy -backend=true  -get=true -get-plugins=true -verify-plugins=true` in directory /workspace/test/fi
xtures/multiple_buckets
       Upgrading modules...
       - example in ../../../examples/multiple_buckets
       - example.cloud_storage in ../../..
       
       Initializing the backend...
       
       Initializing provider plugins...
       - Checking for available provider plugins...
       - Downloading plugin for provider "google" (hashicorp/google) 2.18.1...
       - Downloading plugin for provider "random" (hashicorp/random) 2.2.1...
       
       Terraform has been successfully initialized!
$$$$$$ Running command `terraform workspace select kitchen-terraform-multiple-buckets-default` in directory /workspace/test/fixtures/multiple_buckets
       Finished creating <multiple-buckets-default> (0m11.01s).
-----> Kitchen is finished. (0m12.62s)
  1. Chạy kitchen_do converge <EXAMPLE_NAME> để áp dụng mô-đun ví dụ.

Bước này sẽ áp dụng không gian làm việc dạng địa hình đã tạo ở bước trước cho dự án GCP đã tạo trước đó trong Lớp học lập trình.

Bạn sẽ thấy kết quả bên dưới trong dòng lệnh.

[root@<CONTAINER_ID> workspace]# kitchen_do converge multiple-buckets-default
Automatically setting inputs from outputs of test/setup
Found test/source.sh. Using it for additional explicit environment configuration.
Activated service account credentials for: [cft@<YOUR_PROJECT_ID>.iam.gserviceaccount.com]
-----> Starting Kitchen (v1.24.0)
-----> Converging <multiple-buckets-default>...
       Terraform v0.12.20
       + provider.google v3.9.0
       
       Your version of Terraform is out of date! The latest version
       is 0.12.21. You can update by downloading from https://www.terraform.io/downloads.html
$$$$$$ Running command `terraform workspace select kitchen-terraform-multiple-buckets-default` in directory /workspace/test/fixtures/multiple_buckets
$$$$$$ Running command `terraform get -update` in directory /workspace/test/fixtures/multiple_buckets
       - example in ../../../examples/multiple_buckets
       - example.cloud_storage in ../../..
$$$$$$ Running command `terraform validate   ` in directory /workspace/test/fixtures/multiple_buckets
       Success! The configuration is valid.
       
$$$$$$ Running command `terraform apply -lock=true -lock-timeout=0s -input=false -auto-approve=true  -parallelism=10 -refresh=true  ` in directory /workspace/test/fixtures/multiple_buckets
       random_pet.main: Creating...
       random_pet.main: Creation complete after 0s [id=<BUCKET-ID>]
       module.example.module.cloud_storage.google_storage_bucket.buckets[0]: Creating...
       module.example.module.cloud_storage.google_storage_bucket.buckets[1]: Creating...
       module.example.module.cloud_storage.google_storage_bucket.buckets[1]: Creation complete after 3s [id=<BUCKET-ID-01>]
       module.example.module.cloud_storage.google_storage_bucket.buckets[0]: Creation complete after 3s [id=<BUCKET-ID-02>]
       
       Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
       
       Outputs:
       
       names = {
         "one" = "<BUCKET-ID-01>"
         "two" = "<BUCKET-ID-02>"
       }
       names_list = [
         "<BUCKET-NAME-01>",
         "<BUCKET-NAME-02>",
       ]
       project_id = ci-cloud-storage-ae79
       Finished converging <multiple-buckets-default> (0m7.17s).
-----> Kitchen is finished. (0m8.77s)
  1. Chạy kitchen_do verify <EXAMPLE_NAME> để kiểm thử mô-đun mẫu.

Bước này sẽ chạy thông qua tệp UIs.rb, tệp này có chứa các bài kiểm thử cho mô-đun multiple_buckets. Mỗi thử nghiệm có một lệnh Googlebot sẽ chạy dựa trên dự án thử nghiệm mà bạn đã tạo trước đó bằng cách thiết lập thông tin đăng nhập tài khoản dịch vụ.

Nếu gặp lỗi, bạn sẽ thấy kết quả dự kiến và kết quả kiểm thử mà lệnh đã nhận được.

Bạn sẽ thấy kết quả bên dưới trong dòng lệnh.

multiple_buckets local: Verifying

Profile: multiple_buckets
Version: (not specified)
Target:  local://

  ✔  gsutil: gsutil
     ✔  Command: `gsutil ls -p <PROJECT_ID>` exit_status should eq 0
     ✔  Command: `gsutil ls -p <PROJECT_ID>` stderr should eq ""
     ✔  Command: `gsutil ls -p <PROJECT_ID>` stdout should include "multiple-buckets-mzgy-eu-one"
     ✔  Command: `gsutil ls -p <PROJECT_ID>` stdout should include "<BUCKET-ID-01>"
     ✔  Command: `gsutil bucketpolicyonly get gs://<BUCKET-ID-01>` exit_status should eq 0
     ✔  Command: `gsutil bucketpolicyonly get gs://<BUCKET-ID-01>` stderr should eq ""
     ✔  Command: `gsutil bucketpolicyonly get gs://<BUCKET-ID-01>` stdout should include "Enabled: True"
     ✔  Command: `gsutil bucketpolicyonly get gs://<BUCKET-ID-02>` exit_status should eq 0
     ✔  Command: `gsutil bucketpolicyonly get gs://<BUCKET-ID-02>` stderr should eq ""
     ✔  Command: `gsutil bucketpolicyonly get gs://<BUCKET-ID-02>` stdout should include "Enabled: False"
     ✔  Command: `gsutil label get gs://<BUCKET-ID-01>` exit_status should eq 0
     ✔  Command: `gsutil label get gs://<BUCKET-ID-01>` stderr should eq ""
     ✔  Command: `gsutil label get gs://<BUCKET-ID-01>` bucket_1 has label
     ✔  Command: `gsutil label get gs://<BUCKET-ID-02>` exit_status should eq 0
     ✔  Command: `gsutil label get gs://<BUCKET-ID-02>` stderr should eq ""
     ✔  Command: `gsutil label get gs://<BUCKET-ID-02>` bucket_2 has label
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-01>` should eq "NEARLINE"
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-01>` should eq "SetStorageClass"
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-01>` should eq 10
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-01>` should eq false
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-01>` should eq ["MULTI_REGIONAL", "STANDARD", "DURABLE_REDUCED_AVAILABILITY"]
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-01>` exit_status should eq 0
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-01>` stderr should eq ""
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-02>` should eq "NEARLINE"
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-02>` should eq "SetStorageClass"
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-02>` should eq 10
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-02>` should eq false
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-02>` should eq ["MULTI_REGIONAL", "STANDARD", "DURABLE_REDUCED_AVAILABILITY"]
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-02>` exit_status should eq 0
     ✔  Command: `gsutil lifecycle get gs://<BUCKET-ID-02>` stderr should eq ""


Profile Summary: 1 successful control, 0 control failures, 0 controls skipped
Test Summary: 30 successful, 0 failures, 0 skipped
       Finished verifying <multiple-buckets-default> (0m8.83s).
-----> Kitchen is finished. (0m16.61s)
  1. Chạy kitchen_do destroy <EXAMPLE_NAME> để huỷ trạng thái của mô-đun mẫu.

Bước này sẽ huỷ không gian làm việc mà bạn đã tạo ở các bước ở trên. Bước này cũng sẽ huỷ bỏ các bộ chứa GCS đã được tạo trong dự án cùng với nhãn mà bạn đã thêm vào mô-đun GCS.

Bạn có thể xem kết quả bên dưới trong dòng lệnh.

[root@<CONTAINER_ID> workspace]# kitchen_do destroy multiple-buckets-default
Automatically setting inputs from outputs of test/setup
Found test/source.sh. Using it for additional explicit environment configuration.
Activated service account credentials for: [ci-cloud-storage@ci-cloud-storage-54ab.iam.gserviceaccount.com]
-----> Starting Kitchen (v1.24.0)
-----> Destroying <multiple-buckets-default>...
       Terraform v0.12.12
       + provider.google v3.10.0
       
       Your version of Terraform is out of date! The latest version
       is 0.12.21. You can update by downloading from www.terraform.io/downloads.html
$$$$$$ Running command `terraform init -input=false -lock=true -lock-timeout=0s  -force-copy -backend=true  -get=true -get-plugins=true -verify-plugins=true` in directory /workspace/test/fixtures/mu
ltiple_buckets
       Initializing modules...
       
       Initializing the backend...
       
       Initializing provider plugins...
       
       Terraform has been successfully initialized!
$$$$$$ Running command `terraform workspace select kitchen-terraform-multiple-buckets-default` in directory /workspace/test/fixtures/multiple_buckets
$$$$$$ Running command `terraform destroy -auto-approve -lock=true -lock-timeout=0s -input=false  -parallelism=10 -refresh=true  ` in directory /workspace/test/fixtures/multiple_buckets
       random_string.prefix: Refreshing state... [id=mzgy]
       module.example.module.cloud_storage.google_storage_bucket.buckets[0]: Refreshing state... [id=<BUCKET-ID-01>]
       module.example.module.cloud_storage.google_storage_bucket.buckets[1]: Refreshing state... [id=<BUCKET-ID-02>]
       module.example.module.cloud_storage.google_storage_bucket.buckets[0]: Destroying... [id=<BUCKET-ID-01>]
       module.example.module.cloud_storage.google_storage_bucket.buckets[1]: Destroying... [id=<BUCKET-ID-02>]
       module.example.module.cloud_storage.google_storage_bucket.buckets[0]: Destruction complete after 1s
       module.example.module.cloud_storage.google_storage_bucket.buckets[1]: Destruction complete after 2s
       random_string.prefix: Destroying... [id=mzgy]
       random_string.prefix: Destruction complete after 0s
       
       Destroy complete! Resources: 3 destroyed.
$$$$$$ Running command `terraform workspace select default` in directory /workspace/test/fixtures/multiple_buckets
       Switched to workspace "default".
$$$$$$ Running command `terraform workspace delete kitchen-terraform-multiple-buckets-default` in directory /workspace/test/fixtures/multiple_buckets
       Deleted workspace "kitchen-terraform-multiple-buckets-default"!
       Finished destroying <multiple-buckets-default> (0m6.49s).
-----> Kitchen is finished. (0m8.10s)

9. Tạo tài liệu cho đầu vào và đầu ra

Bảng Đầu vào và Đầu ra trong README của mô-đun gốc, mô-đun con và mô-đun mẫu được tạo tự động dựa trên variablesoutputs của các mô-đun tương ứng. Bạn phải làm mới các bảng này nếu giao diện mô-đun thay đổi.

Chạy:

make generate_docs
# This will generate new Inputs and Outputs tables

10. Thực thi kiểm thử tìm lỗi mã nguồn trong CFT

linter là một công cụ phân tích mã nguồn để gắn cờ các lỗi lập trình, lỗi, lỗi văn phong và những cấu trúc đáng ngờ.

Nhiều tệp trong kho lưu trữ có thể được tìm lỗi mã nguồn hoặc định dạng để duy trì tiêu chuẩn về chất lượng. Để đảm bảo chất lượng trong CFT, bạn sẽ dùng quy trình kiểm thử tìm lỗi mã nguồn.

Chạy:

make docker_test_lint
# This will run all lint tests on your repo

11. Gửi nội dung PR trên GitHub

Bây giờ, bạn đã thay đổi mã cục bộ và kiểm thử mã thông qua các bài kiểm thử tích hợp mà bạn muốn xuất bản mã này vào kho lưu trữ chính.

Để cung cấp mã trên kho lưu trữ chính, bạn cần xác nhận các thay đổi mã đối với nhánh và đẩy mã đó vào kho lưu trữ chính. Để thêm mã vào kho lưu trữ chính mà bạn đã phát triển nhánh ở đầu lớp học lập trình, bạn sẽ đưa ra Yêu cầu kéo (PR) trên kho lưu trữ chính sau khi chuyển mã cho kho lưu trữ đó.

Khi bạn gửi PR, quản trị viên kho lưu trữ sẽ được thông báo để xem xét các thay đổi mã được đề xuất. Ngoài ra, bạn cũng có thể thêm người dùng khác làm người đánh giá để nhận phản hồi về những thay đổi mã của bạn. PR sẽ kích hoạt một Cloud Build. Phiên bản này sẽ chạy các bài kiểm thử trên kho lưu trữ.

Dựa trên các thay đổi về mã của bạn, nhân viên đánh giá mã sẽ đưa ra nhận xét về mã và yêu cầu sửa đổi nếu cần thay đổi dựa trên tài liệu và các phương pháp hay nhất. Quản trị viên sẽ xem xét các thay đổi đối với mã của bạn, đảm bảo rằng mã của bạn tuân thủ repo và có thể lại yêu cầu bạn thực hiện một số thay đổi trước khi hợp nhất mã của bạn vào repo chính.

Thực thi các bước sau để xác nhận mã cho nhánh đã phát triển nhánh và đẩy mã đến nhánh đã phân nhánh của bạn:

  1. Bước đầu tiên là thêm các tệp đã thay đổi vào kho lưu trữ cục bộ.
$ git add main.tf
$ git add README.md
$ git add variables.tf
$ git add examples/multiple-buckets/main.tf
$ git add test/integration/multiple-buckets/controls/gsutil.rb
# The ‘git add' command adds the file in the local repository and 
# stages the file for commit. To unstage a file, use git reset HEAD YOUR-FILE
  1. Các tệp của bạn hiện đã được đưa vào giai đoạn, tiếp theo, bạn sẽ thực hiện các thay đổi.
$ git commit -m "First CFT commit"
# This will commit the staged changes and prepares them to be pushed 
# to a remote repository. To remove this commit and modify the file, 
# use 'git reset --soft HEAD~1' and commit and add the file again.
  1. Đẩy các thay đổi đã cam kết trong kho lưu trữ cục bộ lên GitHub để tạo một Yêu cầu kéo (PR).
$ git push -u origin master
# Pushes the changes in your local repository up to the remote
# repository you specified as the origin

Các thay đổi đối với mã của bạn hiện đã sẵn sàng cho Yêu cầu lấy dữ liệu!

Thực hiện các bước sau để tăng mức PR cho kho lưu trữ terraform-google-modules/terraform-google-cloud-storage :

  1. Trong trình duyệt web, hãy chuyển đến trang chính của kho lưu trữ.
  2. Trong trình đơn Nhánh, hãy chọn nhánh chứa các cam kết của bạn.
  3. Ở bên phải "Nhánh" hãy nhấp vào "Yêu cầu kéo mới".

40087ce52ee5ed35.pngS

  1. Dùng "cơ sở" cơ sở trình đơn thả xuống để chọn nhánh mà bạn muốn hợp nhất các thay đổi của mình vào, thường đây là nhánh "chính" vì bạn đã cam kết thay đổi mã cho nhánh phát triển của mình.
  2. Nhập tiêu đề và nội dung mô tả cho yêu cầu lấy dữ liệu để mô tả các thay đổi đối với mã của bạn. Hãy nêu càng cụ thể càng tốt nhưng vẫn súc tích.
  3. Để tạo một yêu cầu lấy dữ liệu đã sẵn sàng để xem xét, hãy nhấp vào "Tạo yêu cầu lấy dữ liệu".

a9e70a2ec9653cd7.png

  1. Bạn sẽ thấy các Trình kích hoạt bản dựng trên đám mây đang chạy. Các điều kiện kích hoạt này được kích hoạt do quan hệ công chúng.

Bạn đã đẩy thành công thay đổi mã đầu tiên sang nhánh đã nhánh và tăng PR CFT đầu tiên của mình so với nhánh chính!

12. Xin chúc mừng

Xin chúc mừng! Bạn đã thêm thành công một tính năng vào mô-đun CFT và gửi bản PR để được xem xét!

Bạn đã thêm một tính năng vào mô-đun CFT, kiểm thử cục bộ tính năng đó thông qua một ví dụ và thực hiện kiểm thử trước khi chuyển giao mã cho GitHub. Cuối cùng, bạn đã gửi một yêu cầu PR để xem xét và hợp nhất lần cuối vào CFT.

Giờ đây, bạn đã biết các bước quan trọng để bắt đầu sử dụng Bộ công cụ nền tảng đám mây.