Initial commit

This commit is contained in:
2025-12-07 16:18:55 +01:00
commit 7f678cd999
20 changed files with 5911 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
.terraform
.terraform.lock.hcl

28
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,28 @@
# How to Contribute
We'd love to accept your patches and contributions to this project. There are
just a few small guidelines you need to follow.
## Contributor License Agreement
Contributions to this project must be accompanied by a Contributor License
Agreement. You (or your employer) retain the copyright to your contribution;
this simply gives us permission to use and redistribute your contributions as
part of the project. Head over to <https://cla.developers.google.com/> to see
your current agreements on file or to sign a new one.
You generally only need to submit a CLA once, so if you've already submitted one
(even if it was for a different project), you probably don't need to do it
again.
## Code Reviews
All submissions, including submissions by project members, require review. We
use GitHub pull requests for this purpose. Consult
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
information on using pull requests.
## Community Guidelines
This project follows [Google's Open Source Community
Guidelines](https://opensource.google/conduct/).

28
Dockerfile Normal file
View File

@@ -0,0 +1,28 @@
FROM moodlehq/moodle-php-apache:8.3-bullseye
# Install git to clone Moodle
RUN apt-get update && apt-get install -y git
# Clone Moodle
# Using MOODLE_501_STABLE as it's the latest stable branch found in research
RUN rm -rf /var/www/html/* && \
git clone -b MOODLE_501_STABLE git://git.moodle.org/moodle.git /var/www/html
# Configure Apache DocumentRoot for Moodle 5.1+
ENV APACHE_DOCUMENT_ROOT=/var/www/html/public
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf
# Fix git detected dubious ownership
RUN git config --global --add safe.directory /var/www/html
# Set permissions
RUN chown -R www-data:www-data /var/www/html
# Copy config.php
COPY config.php /var/www/html/config.php
# Create dataroot
RUN mkdir -p /var/www/moodledata && \
chown -R www-data:www-data /var/www/moodledata && \
chmod 777 /var/www/moodledata

201
LICENSE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

150
README.md Normal file
View File

@@ -0,0 +1,150 @@
[![GC Start](gcp_banner.png)](https://cloud.google.com/?utm_source=github&utm_medium=referral&utm_campaign=GCP&utm_content=packages_repository_banner)
# Host a Serverless Wordpress Site with Cloud Run
## Introduction
_This architecture uses click-to-deploy so you can spin up infrastructure in minutes using terraform!_
43% of the Web is built on Wordpress. Because of its simplicity and versatility, Wordpress can be used for internal websites and customer facing e-commerce platforms in small to large businesses, while still offering security. **Cloud Run automatically scales your WordPress application to handle any amount of traffic**, without requiring manual intervention. This means that your website can handle large traffic spikes, without worrying about capacity.
Cloud Run allows you to deploy your WordPress application quickly and easily, with a few clicks or commands. You can deploy your application from a container image stored in a container registry or directly from a Git repository. This click-to-deploy architecture leverages the serverless and scalability benefits of using Cloud Run to host a Wordpress Application connected to a PostgreSQL instance.
This repo is based on the Cloud Foundation Fabric blueprint available [here](https://github.com/GoogleCloudPlatform/cloud-foundation-fabric/tree/master/blueprints/third-party-solutions/wordpress/cloudrun).
## Use cases
These are some of the use cases you can build on top of this infrastructure:
* Business websites
* E-commerce websites
* Portfolios
* Non-profit websites
* Educational Websites
## Architecture
![Wordpress on Cloud Run](architecture.png "Wordpress on Cloud Run")
The main components that are deployed in this architecture are the following (you can learn about them by following the hyperlinks):
* [Cloud Run](https://cloud.google.com/run): serverless PaaS offering to host containers for web-oriented applications, while offering security, scalability and easy versioning
* [Cloud SQL](https://cloud.google.com/sql): Managed solution for SQL databases
* [VPC Serverless Connector](https://cloud.google.com/vpc/docs/serverless-vpc-access): Solution to access the CloudSQL VPC from Cloud Run, using only internal IP addresses
## Costs
Pricing Estimates - We have created a sample estimate based on some usage we see from new startups looking to scale. This estimate would give you an idea of how much this deployment would essentially cost per month at this scale and you extend it to the scale you further prefer. Here's the [link](https://cloud.google.com/products/calculator#id=8a7471c9-98df-4b71-97de-6222d22484c8).
## Setting up the project for the deployment
This example will deploy all its resources into the project defined by the `project_id` variable. Please note that we assume this project already exists. However, if you provide the appropriate values to the `project_create` variable, the project will be created as part of the deployment.
If `project_create` is set to null, the identity performing the deployment needs the `owner` role on the project defined by the `project_id` variable. Otherwise, the identity performing the deployment needs `resourcemanager.projectCreator` on the resource hierarchy node specified by `project_create.parent` and `billing.user` on the billing account specified by `project_create.billing_account_id`.
## Deploy the architecture
Before we deploy the architecture, you will need the following information:
* The __service project ID__.
* A __unique prefix__ that you want all the deployed resources to have (for example: awesomestartup). This must be a string with no spaces or tabs.
* A __Wordpress image__ if you want to use your own, otherwise you can use the provided standard image.
* A __list of Groups or Users__ with Service Account Token creator role on Service Accounts in IAM format, eg 'group:group@domain.com'.
**Notes**:
1. If you want to change your admin password later on, please note that you can only do so via the Wordpress user interface.
2. If you have the [domain restriction org. policy](https://cloud.google.com/resource-manager/docs/organization-policy/restricting-domains) on your organization, you have to edit the `cloud_run_invoker` variable and give it a value that will be accepted in accordance to your policy.
Click on the button below, sign in if required and when the prompt appears, click on “confirm”. It will walk you through setting up your architecture.
[![Open Cloud Shell](https://gstatic.com/cloudssh/images/open-btn.svg)](https://shell.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2FGoogleCloudPlatform%2Fdeploystack-wordpress-on-cloudrun&cloudshell_image=gcr.io%2Fds-artifacts-cloudshell%2Fdeploystack_custom_image&cloudshell_git_branch=main&cloudshell_tutorial=tutorial.md)
This is the startup screen that appears after clicking the button and confirming:
![cloud_shell](cloud_shell.png)
During the process, you will be asked for some user input. All necessary variables are explained at the bottom of this ReadMe file. In case of failure, you can simply click the button again.
<center>
<h4>🎉 Congratulations! 🎉 <br />
You have successfully deployed the foundation for running Wordpress using CloudRun on Google Cloud.</h4></center>
**Note**:
You might get the following error (or a similar one):
``` {shell}
│ Error: resource is in failed state "Ready:False", message: Revision '...' is not ready and cannot serve traffic.│
```
In case this happens, manually run
``` {shell}
deploystack install
```
to run the installation again.
## Using the Wordpress Installation
Upon completion, you will see the output with the values for the Cloud Run service and the user and password to access the `/admin` part of the website. You can also view it later with:
``` {shell}
terraform output
# or for the concrete variable:
terraform output cloud_run_service
```
When clicking on the Wordpress link, it will immediately prompt you to register as an administrator. The password will be pre-filled and can be changed after registration.
## Cleaning Up Your Environment
The easiest way to remove all deployed resources is to run the following command in Cloud Shell:
``` {shell}
deploystack uninstall
```
The above command will delete the associated resources so there will be no billable charges made afterwards.
<!-- BEGIN TFDOC -->
## Standalone deployment
Since the scripts are based on Terraform, it is possible to deploy this solution through `Terraform` directly, without having to go through `Deploystack`.
Just clone this repo, create a `terraform.tfvars` file with your own values and call the following commands:
``` {shell}
terraform init
terraform plan -out=execplan.out
terraform apply execplan.out
```
## Special Thanks
A special thank you goes out to Natalia Strelkova (skalolazka) and Grigory Movsesyan, the original developers of this example architecture.
## Variables
| name | description | type | default |
|---|---|:---:|:---:|
| [project_id](variables.tf#L78) | Project id, references existing project if `project_create` is null. | <code>string</code> | |
| [wordpress_image](variables.tf#L89) | Image to run with Cloud Run, starts with \"gcr.io\" | <code>string</code> | mirror.gcr.io/library/wordpress |
| [cloud_run_invoker](variables.tf#L18) | IAM member authorized to access the end-point (for example, 'user:YOUR_IAM_USER' for only you or 'allUsers' for everyone) | <code>string</code> | <code>&#34;allUsers&#34;</code> |
| [cloudsql_password](variables.tf#L24) | CloudSQL password (will be randomly generated by default) | <code>string</code> | <code>null</code> |
| [connector](variables.tf#L30) | Existing VPC serverless connector to use if not creating a new one | <code>string</code> | <code>null</code> |
| [create_connector](variables.tf#L36) | Should a VPC serverless connector be created or not | <code>bool</code> | <code>true</code> |
| [ip_ranges](variables.tf#L43) | CIDR blocks: VPC serverless connector, Private Service Access(PSA) for CloudSQL, CloudSQL VPC | <code title="object&#40;&#123;&#10; connector &#61; string&#10; psa &#61; string&#10; sql_vpc &#61; string&#10;&#125;&#41;">object&#40;&#123;&#8230;&#125;&#41;</code> | <code title="&#123;&#10; connector &#61; &#34;10.8.0.0&#47;28&#34;&#10; psa &#61; &#34;10.60.0.0&#47;24&#34;&#10; sql_vpc &#61; &#34;10.0.0.0&#47;20&#34;&#10;&#125;">&#123;&#8230;&#125;</code> |
| [prefix](variables.tf#L57) | Unique prefix used for resource names. Not used for project if 'project_create' is null. | <code>string</code> | <code>&#34;&#34;</code> |
| [principals](variables.tf#L63) | List of users to give rights to (CloudSQL admin, client and instanceUser, Logging admin, Service Account User and TokenCreator), eg 'user@domain.com'. | <code>list&#40;string&#41;</code> | <code>&#91;&#93;</code> |
| [project_create](variables.tf#L69) | Provide values if project creation is needed, uses existing project if null. Parent is in 'folders/nnn' or 'organizations/nnn' format. | <code title="object&#40;&#123;&#10; billing_account_id &#61; string&#10; parent &#61; string&#10;&#125;&#41;">object&#40;&#123;&#8230;&#125;&#41;</code> | <code>null</code> |
| [region](variables.tf#L83) | Region for the created resources | <code>string</code> | | <code>&#34;europe-west4&#34;</code> |
| [wordpress_password](variables.tf#L94) | Password for the Wordpress user (will be randomly generated by default) | <code>string</code> | <code>null</code> |
| [wordpress_port](variables.tf#L100) | Port for the Wordpress image | <code>number</code> | <code>8080</code> |
## Outputs
| name | description | sensitive |
|---|---|:---:|
| [cloud_run_service](outputs.tf#L17) | CloudRun service URL | ✓ |
| [cloudsql_password](outputs.tf#L23) | CloudSQL password | ✓ |
| [wp_password](outputs.tf#L29) | Wordpress user password | ✓ |
| [wp_user](outputs.tf#L35) | Wordpress username | |
<!-- END TFDOC -->

BIN
architecture.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

BIN
cloud_shell.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

5
cloudbuild-docker.yaml Normal file
View File

@@ -0,0 +1,5 @@
steps:
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', 'gcr.io/$PROJECT_ID/moodle:latest', '.']
images:
- 'gcr.io/$PROJECT_ID/moodle:latest'

10
cloudbuild.yaml Normal file
View File

@@ -0,0 +1,10 @@
steps:
- name: 'hashicorp/terraform'
args:
- 'init'
- name: 'hashicorp/terraform'
args: ['plan', '-var', 'project_id=$PROJECT_ID', '-var', 'prefix=deploystack']
- name: 'hashicorp/terraform'
args: ['apply', '-var', 'project_id=$PROJECT_ID', '-var', 'prefix=deploystack', '-auto-approve']
- name: 'hashicorp/terraform'
args: ['destroy', '-var', 'project_id=$PROJECT_ID', '-var', 'prefix=deploystack', '-auto-approve']

73
cloudsql.tf Normal file
View File

@@ -0,0 +1,73 @@
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
resource "random_password" "cloudsql_password" {
length = 8
}
# create a VPC for CloudSQL
module "vpc" {
source = "github.com/GoogleCloudPlatform/cloud-foundation-fabric//modules/net-vpc?ref=v34.1.0"
project_id = module.project.project_id
name = "${local.prefix}sql-vpc"
subnets = [
{
ip_cidr_range = var.ip_ranges.sql_vpc
name = "subnet"
region = var.region
}
]
psa_configs = [{
ranges = {
cloud-sql = var.ip_ranges.psa
}
}]
}
# create a VPC connector for the ClouSQL VPC
resource "google_vpc_access_connector" "connector" {
count = var.create_connector ? 1 : 0
project = module.project.project_id
name = "${local.prefix}wp-connector"
region = var.region
ip_cidr_range = var.ip_ranges.connector
network = module.vpc.self_link
}
# Set up CloudSQL
module "cloudsql" {
source = "github.com/GoogleCloudPlatform/cloud-foundation-fabric//modules/cloudsql-instance?ref=v34.1.0"
project_id = module.project.project_id
network_config = {
connectivity = {
psa_config = {
private_network = module.vpc.self_link
}
}
}
name = "${local.prefix}mysql"
region = var.region
database_version = local.cloudsql_conf.database_version
tier = local.cloudsql_conf.tier
databases = [local.cloudsql_conf.db]
gcp_deletion_protection = false
terraform_deletion_protection = false
users = {
"${local.cloudsql_conf.user}" = {
password = var.cloudsql_password
}
}
}

29
config.php Normal file
View File

@@ -0,0 +1,29 @@
<?php // Moodle configuration file
unset($CFG);
global $CFG;
$CFG = new stdClass();
$CFG->dbtype = getenv('MOODLE_DB_TYPE') ?: 'mysqli';
$CFG->dblibrary = 'native';
$CFG->dbhost = getenv('MOODLE_DB_HOST') ?: 'localhost';
$CFG->dbname = getenv('MOODLE_DB_NAME') ?: 'moodle';
$CFG->dbuser = getenv('MOODLE_DB_USER') ?: 'moodleuser';
$CFG->dbpass = getenv('MOODLE_DB_PASSWORD') ?: 'password';
$CFG->prefix = 'mdl_';
$CFG->dboptions = array (
'dbpersist' => 0,
'dbport' => getenv('MOODLE_DB_PORT') ?: '',
'dbsocket' => '',
);
$CFG->wwwroot = getenv('MOODLE_WWWROOT') ?: 'http://localhost';
$CFG->dataroot = getenv('MOODLE_DATAROOT') ?: '/var/www/moodledata';
$CFG->admin = 'admin';
$CFG->directorypermissions = 0777;
require_once(__DIR__ . '/lib/setup.php');
// There is no php closing tag in this file,
// it is intentional because it prevents trailing whitespace problems!

BIN
gcp_banner.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

109
main.tf Normal file
View File

@@ -0,0 +1,109 @@
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
locals {
all_principals_iam = [for k in var.principals : "user:${k}"]
cloudsql_conf = {
database_version = "MYSQL_8_4"
tier = "db-g1-small"
db = "wp-mysql"
user = "admin"
}
iam = {
# CloudSQL
"roles/cloudsql.admin" = local.all_principals_iam
"roles/cloudsql.client" = local.all_principals_iam
"roles/cloudsql.instanceUser" = local.all_principals_iam
# common roles
"roles/logging.admin" = local.all_principals_iam
"roles/iam.serviceAccountUser" = local.all_principals_iam
"roles/iam.serviceAccountTokenCreator" = local.all_principals_iam
"roles/owner" = local.all_principals_iam
}
connector = var.connector == null ? google_vpc_access_connector.connector.0.self_link : var.connector
prefix = var.prefix == null ? "" : "${var.prefix}-"
}
# either create a project or set up the given one
module "project" {
source = "github.com/GoogleCloudPlatform/cloud-foundation-fabric//modules/project?ref=v34.1.0"
name = var.project_id
parent = try(var.project_create.parent, null)
billing_account = try(var.project_create.billing_account_id, null)
project_create = var.project_create != null
prefix = var.project_create == null ? null : var.prefix
iam = var.project_create != null ? local.iam : {}
services = [
"run.googleapis.com",
"logging.googleapis.com",
"monitoring.googleapis.com",
"sqladmin.googleapis.com",
"sql-component.googleapis.com",
"vpcaccess.googleapis.com",
"servicenetworking.googleapis.com",
"cloudbuild.googleapis.com"
]
}
resource "random_password" "wp_password" {
length = 8
}
# create the Cloud Run service
module "cloud_run" {
source = "github.com/GoogleCloudPlatform/cloud-foundation-fabric//modules/cloud-run?ref=v34.1.0"
project_id = module.project.project_id
name = "${local.prefix}cr-wordpress"
region = var.region
containers = {
wordpress = {
image = var.wordpress_image
ports = {
http = {
container_port = var.wordpress_port
name = "http1"
protocol = null
}
}
# set up the database connection
env = {
"MOODLE_DB_HOST" : module.cloudsql.ip
"MOODLE_DB_NAME" : local.cloudsql_conf.db
"MOODLE_DB_USER" : local.cloudsql_conf.user
"MOODLE_DB_PASSWORD" : var.cloudsql_password == null ? module.cloudsql.user_passwords[local.cloudsql_conf.user] : var.cloudsql_password
}
}
}
iam = {
"roles/run.invoker" : [var.cloud_run_invoker]
}
revision_annotations = {
autoscaling = {
min_scale = 0
max_scale = 20
}
# connect to CloudSQL
cloudsql_instances = [module.cloudsql.connection_name]
vpcaccess_connector = null
# allow all traffic
vpcaccess_egress = "all-traffic"
vpcaccess_connector = local.connector
}
ingress_settings = "all"
}

30
outputs.tf Normal file
View File

@@ -0,0 +1,30 @@
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
output "cloud_run_service" {
description = "CloudRun service URL"
value = module.cloud_run.service.status[0].url
}
output "cloudsql_password" {
description = "CloudSQL password"
value = var.cloudsql_password == null ? module.cloudsql.user_passwords[local.cloudsql_conf.user] : var.cloudsql_password
sensitive = true
}
output "password" {
value = module.cloudsql.user_passwords[local.cloudsql_conf.user]
}

2512
terraform.tfstate Normal file

File diff suppressed because it is too large Load Diff

2512
terraform.tfstate.backup Normal file

File diff suppressed because it is too large Load Diff

9
terraform.tfvars Normal file
View File

@@ -0,0 +1,9 @@
prefix = "kvgd"
principals = [
"kovagoadi@gmail.com",
]
project_create = {
billing_account_id = "014C39-915447-320C74"
}
name = "wp"
project_id = "bevcloud-moodle"

82
tutorial.md Normal file
View File

@@ -0,0 +1,82 @@
# Host a Serverless Wordpress Site with Cloud Run
## Let's get started!
This example will deploy all its resources into the project defined by the `project_id` variable. Please note that we assume this project already exists.
However, if you provide the appropriate values to the `project_create` variable, the project will be created as part of the deployment.
If `project_create` is left to null, the identity performing the deployment needs the owner role on the project defined by the project_id variable.
Otherwise, the identity performing the deployment needs `resourcemanager.projectCreator` on the resource hierarchy node specified by `project_create.parent` and `billing.user` on the billing account specified by `project_create.billing_account_id`.
**Time to complete**: About 10 minutes
Click the **Start** button to move to the next step.
## Information required
Before we deploy the architecture, you will need the following information:
* __The service project ID__.
* A __unique prefix__ that you want all the deployed resources to have (for example: awesomestartup). This must be a string with no spaces or tabs.
* A __Wordpress image__ if you want to use your own, otherwise you can use the provided standard image.
* A __list of Groups or Users__ with Service Account Token creator role on Service Accounts in IAM format, eg 'group:group@domain.com'.
### Notes:
1. If you want to change your admin password later on, please note that you can only do so via the Wordpress user interface.
2. If you have the domain restriction org. policy on your organization, you have to edit the cloud_run_invoker variable and give it a value that will be accepted in accordance to your policy.
## Deploy the architecture
Congratulations! At this point you should have successfully deployed the foundations for running Wordpress using CloudRun on Google Cloud.
### Note:
*** You might get the following error (or a similar one): ***
```
Error: resource is in failed state "Ready:False", message: Revision '...' is not ready and cannot serve traffic.
```
In case this happens, manually run the following command to run the installation again
```bash
deploystack install
```
## Using the Wordpress Installation
Upon completion, you will see the output with the values for the Cloud Run service and the user and password to access the /admin part of the website. You can also view it later with:
``` bash
terraform output
```
or for the concrete variable:
``` bash
terraform output cloud_run_service
```
When clicking on the Wordpress link, it will immediately prompt you to register as an administrator.
The password will be pre-filled and can be changed after registration.
## Cleaning Up Your Environment
The easiest way to remove all deployed resources is to run the following command in Cloud Shell:
```bash
deploystack uninstall
```
The above command will delete the associated resources so there will be no billable charges made afterwards.
## Variables & Outputs
For full information on variables and outputs please refer to the [README](https://github.com/GoogleCloudPlatform/deploystack-wordpress-on-cloudrun/blob/main/README.md#variables) file
## Congratulations
<walkthrough-conclusion-trophy></walkthrough-conclusion-trophy>
Youre all set!

99
variables.tf Normal file
View File

@@ -0,0 +1,99 @@
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
# Documentation: https://cloud.google.com/run/docs/securing/managing-access#making_a_service_public
variable "cloud_run_invoker" {
type = string
description = "IAM member authorized to access the end-point (for example, 'user:YOUR_IAM_USER' for only you or 'allUsers' for everyone)"
default = "allUsers"
}
variable "cloudsql_password" {
type = string
description = "CloudSQL password (will be randomly generated by default)"
default = null
}
variable "connector" {
type = string
description = "Existing VPC serverless connector to use if not creating a new one"
default = null
}
variable "create_connector" {
type = bool
description = "Should a VPC serverless connector be created or not"
default = true
}
# PSA: documentation: https://cloud.google.com/vpc/docs/configure-private-services-access#allocating-range
variable "ip_ranges" {
description = "CIDR blocks: VPC serverless connector, Private Service Access(PSA) for CloudSQL, CloudSQL VPC"
type = object({
connector = string
psa = string
sql_vpc = string
})
default = {
connector = "10.8.0.0/28"
psa = "10.60.0.0/24"
sql_vpc = "10.0.0.0/20"
}
}
variable "prefix" {
description = "Unique prefix used for resource names. Not used for project if 'project_create' is null."
type = string
default = ""
}
variable "principals" {
description = "List of users to give rights to (CloudSQL admin, client and instanceUser, Logging admin, Service Account User and TokenCreator), eg 'user@domain.com'."
type = list(string)
default = []
}
variable "project_create" {
description = "Provide values if project creation is needed, uses existing project if null. Parent is in 'folders/nnn' or 'organizations/nnn' format."
type = object({
billing_account_id = string
parent = optional(string)
})
default = null
}
variable "project_id" {
description = "Project id, references existing project if `project_create` is null."
type = string
}
variable "region" {
type = string
description = "The region where resources will be deployed."
default = "europe-west1"
}
variable "wordpress_image" {
type = string
description = "Image to run with Cloud Run, starts with \"gcr.io\" or \"REGION-docker.pkg.dev\""
default = "moodlehq/moodle-php-apache:8.3-bullseye"
}
variable "wordpress_port" {
type = number
description = "Port for the Wordpress image"
default = 80
}

31
versions.tf Normal file
View File

@@ -0,0 +1,31 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
terraform {
required_version = ">= 1.4.4"
required_providers {
google = {
source = "hashicorp/google"
version = ">= 4.69.1" # tftest
}
google-beta = {
source = "hashicorp/google-beta"
version = ">= 4.69.1" # tftest
}
}
provider_meta "google" {
module_name = "cloud-solutions/wordpress-on-cloudrun-v1.0"
}
}