├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── anthos-cm
└── static
│ ├── hello.yaml
│ └── microk8s.yaml
├── cleanup
└── 910-disable-anthos
├── img
├── .gitkeep
├── AnthosCMHighLevel.png
├── AnthosMicrok8sTitle.png
├── ClusterPostLogin.png
├── PostClone.png
├── PreRegister.png
└── SourceRepoPreClone.png
├── main.tf
├── modules
├── microk8s
│ ├── main.tf
│ ├── outputs.tf
│ └── variables.tf
└── serviceaccount
│ ├── main.tf
│ ├── outputs.tf
│ └── variables.tf
├── outputs.tf
├── setup
├── 110-enable-apis
├── 120-install-terraform
└── 130-install-nomos
├── terraform.tfvars
└── variables.tf
/.gitignore:
--------------------------------------------------------------------------------
1 | # Local .terraform directories
2 | **/.terraform/*
3 |
4 | # .tfstate files
5 | *.tfstate
6 | *.tfstate.*
7 |
8 |
9 | # Crash log files
10 | crash.log
11 |
12 | # Ignore any .tfvars files that are generated automatically for each Terraform run. Most
13 | # .tfvars files are managed as part of configuration and so should be included in
14 | # version control.
15 | #
16 | # example.tfvars
17 |
18 | # Ignore override files as they are usually used to override resources locally and so
19 | # are not checked in
20 | override.tf
21 | override.tf.json
22 | *_override.tf
23 | *_override.tf.json
24 |
25 | # Include override files you do wish to add to version control using negated pattern
26 | #
27 | # !example_override.tf
28 |
29 | # Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan
30 | # example: *tfplan*
31 | *.out
32 | *tfplan*
33 |
34 | *.doc
35 | *.docx
36 | *.xls
37 | *.xlsx
38 | *.pdf
39 |
40 | # Key files
41 |
42 | *.pem
43 | *.pub
44 | *.openssh
45 |
46 | # Vim backups
47 |
48 | *.swp
49 | *.swo
50 |
51 | # Anthos CM-related files that are generated dynamically
52 | anthos-cm/var/**
53 |
54 | # Miscellaneous git stuff
55 | **/.git/*
56 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to Contribute
2 |
3 | We'd love to accept your patches and contributions to this project. There are
4 | just a few small guidelines you need to follow.
5 |
6 | ## Contributor License Agreement
7 |
8 | Contributions to this project must be accompanied by a Contributor License
9 | Agreement. You (or your employer) retain the copyright to your contribution;
10 | this simply gives us permission to use and redistribute your contributions as
11 | part of the project. Head over to to see
12 | your current agreements on file or to sign a new one.
13 |
14 | You generally only need to submit a CLA once, so if you've already submitted one
15 | (even if it was for a different project), you probably don't need to do it
16 | again.
17 |
18 | ## Code reviews
19 |
20 | All submissions, including submissions by project members, require review. We
21 | use GitHub pull requests for this purpose. Consult
22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
23 | information on using pull requests.
24 |
25 | ## Community Guidelines
26 |
27 | This project follows [Google's Open Source Community
28 | Guidelines](https://opensource.google/conduct/).
29 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # Deploying to Microk8s with Anthos Config Management
4 |
5 | [Anthos Config Management](https://cloud.google.com/anthos/config-management) enables you to automate policy and security at scale for your hybrid and multi-cloud Kubernetes deployments. At a high level, you commit your Kubernetes code to a central Git repository and Anthos Config Management deploys the code to all of the registered clusters. In short, Anthos Config Management allows you to bring GitOps practices to multi-cloud container management.
6 |
7 | Anthos Config Management is supported on GKE-based clusters and on [Anthos attached clusters](https://cloud.google.com/anthos/docs/setup/attached-clusters), a deployment option that extends Anthos’ reach into Kubernetes clusters running in other environments including Amazon EKS and Azure AKS.
8 | In this overview, you will learn how to set up an Anthos attached cluster using
9 | [Microk8s](https://microk8s.io/), a Kubernetes platform that is sometimes used
10 | in IoT environments. While *Microk8s itself is not an officially [supported configuration](https://cloud.google.com/anthos/docs/version-and-upgrade-support)*, we will use Microk8s in an *experimental* capacity so you can learn more about Anthos Config Management and consider Anthos Config Management for your projects.
11 |
12 | We will use the following Google Cloud services:
13 |
14 | * Compute Engine will be used for our Microk8s cluster. We will just use a single node running Ubuntu. Ubuntu will use cloud-init to install Microk8s and generate shell scripts and other files to save time.
15 |
16 | * Cloud Source Repositories will provide the Git-based repository to which we will commit our workload.
17 |
18 | * Anthos Config Management will perform the deployment from the repository to the Microk8s cluster.
19 |
20 | You will use Terraform and shell scripts to build the lab infrastructure. I will point out important parts of the scripts. Feel free to read the scripts if you wish. You will type some commands directly, but my goal is to provide a working example you can refer to in the future. Sound good? I hope so! Let's get building.
21 |
22 | # Disclaimers
23 |
24 | * This article and the associated repository are not officially supported Google products.
25 |
26 | * Microk8s is not an officially supported configuration for Anthos attached
27 | clusters.
28 |
29 | # Assumptions and prerequisites
30 |
31 | Here are my assumptions and prerequisites going forward:
32 |
33 | * You have the ability to login to the Google Cloud console with an identity that has the Owner and Service Account User roles.
34 |
35 | * You have a Google Cloud project that you can use for labs that will not interfere with any projection work. If you do not have such a project, please see this link to learn how to create one.
36 |
37 | * You are familiar with core Google Cloud concepts such as projects.
38 |
39 | * You are comfortable with the use of the cloud console and the Cloud Shell.
40 |
41 | * You understand Git-related concepts such as cloning and committing code.
42 |
43 | # Let's start with a picture
44 |
45 | I'd like to start off with a picture of what we are going to build.
46 |
47 | 
48 |
49 | Here's how all of this fits together.
50 |
51 | * We will start by launching a workstation instance and then deploying four things: (a) an IAM service account, (b) a Google Compute Engine Instance with Microk8s using permissions provided by the service account, (c) a Kubernetes configuration repo provided by Cloud Source Repositories, and (4) a public/private key pair.
52 |
53 | * The GCE instance will use the service account key to register the Microk8s cluster with the GKE Hub. Even though we will be using Microk8s rather than GKE for this walkthrough, the GKE Hub serves as a registration point for making clusters available to Anthos.
54 |
55 | * The public key from the public/private key pair will be registered to the repository while the private key will be registered with the Microk8s cluster.
56 |
57 | * Anthos Config Management will be configured to point to the repository and branch to poll for updates.
58 | When a Kubernetes YAML document is pushed to the appropriate branch of the repository, Anthos Config Management will use the private key to connect to the repository, detect that a commit has been made against the branch, fetch the files and apply the document to the Microk8s cluster.
59 |
60 | Now that we know what we are going to build, let's get to work!
61 |
62 | # Create a workstation instance
63 |
64 | You will need a workstation in which to execute commands. The scripts used are based on Ubuntu. So let's create an Ubuntu instance.
65 |
66 | * Sign into the Google Cloud console and switch the project in which you wish to deploy this infrastructure.
67 |
68 | * Create a service account with the Owner and Service Account User roles.
69 |
70 | * Launch a Compute Engine Ubuntu 20.04 LTS instance with an e2-small instance type using the service account you just created. Make note of the instance name you use.
71 |
72 | # Clone the workshop repository
73 |
74 | * Ssh into the workstation instance you just created.
75 |
76 | * Clone the workshop repository using the command below.
77 |
78 | ```
79 | git clone https://github.com/google/anthos-microk8s.git
80 | ```
81 |
82 | * Change your working directory to that of the cloned workshop repository. Set the BASEDIR environment variable to that directory so you can go to it more easily.
83 |
84 | ```
85 | cd gcp-anthos-microk8s
86 | export BASEDIR=`pwd`
87 | ```
88 |
89 | # Explore the repository
90 |
91 | Let's examine the structure of the repository. Here's a diagram of the directory structure.
92 |
93 | ```
94 | gcp-anthos-microk8s/
95 | ├── CONTRIBUTING.md
96 | ├── LICENSE
97 | ├── README.md
98 | ├── anthos-cm
99 | │ └── static
100 | │ ├── hello.yaml
101 | │ └── microk8s.yaml
102 | ├── cleanup
103 | │ └── 910-disable-anthos
104 | ├── img
105 | │ ├── AnthosCMHighLevel.png
106 | │ ├── AnthosMicrok8sTitle.png
107 | │ ├── ClusterPostLogin.png
108 | │ ├── PostClone.png
109 | │ ├── PreRegister.png
110 | │ └── SourceRepoPreClone.png
111 | ├── main.tf
112 | ├── modules
113 | │ ├── microk8s
114 | │ │ ├── main.tf
115 | │ │ ├── outputs.tf
116 | │ │ └── variables.tf
117 | │ └── serviceaccount
118 | │ ├── main.tf
119 | │ ├── outputs.tf
120 | │ └── variables.tf
121 | ├── outputs.tf
122 | ├── setup
123 | │ ├── 110-enable-apis
124 | │ ├── 120-install-terraform
125 | │ └── 130-install-nomos
126 | ├── terraform.tfvars
127 | └── variables.tf
128 | ```
129 |
130 | * The setup directory contains shell scripts to set up the workstation instance.
131 |
132 | * There are three Terraform modules which can be identified by the presence of the *main.tf*, *variables.tf*, and *outputs.tf files*. The root module sits at the top of the tree and drives the overall deployment. The *microk8s* module creates the Ubuntu instance and installs microk8s. The *serviceaccount* module sets up the IAM service account that is used by the Ubuntu instance.
133 |
134 | # Prepare the workstation
135 |
136 | * Enable the appropriate APIs for your project using the command below. You will be asked to confirm the charges associated with the Anthos API.
137 |
138 | ```
139 | cd $BASEDIR/setup
140 | ./110-enable-apis
141 | ```
142 |
143 | * Install *Terraform* for deploying the infrastructure.
144 |
145 | ```
146 | ./120-install-terraform
147 | ```
148 |
149 | * Install *Nomos* which you will use to set up the Kubernetes configuration cluster and go back to the base directory.
150 |
151 | ```
152 | ./130-install-nomos
153 | cd $BASEDIR
154 | ```
155 |
156 | # Deploy the infrastructure
157 |
158 | * Enter the commands below to deploy the infrastructure with Terraform. The *terraform* init command downloads all external modules and validates the structure of the Terraform files. The *terraform plan* command creates a deployment plan. Substitute your Google Cloud project ID for *MY_PROJECT_ID*. The *terraform apply* command applies the deployment plan to create the infrastructure.
159 |
160 | ```
161 | terraform init
162 | terraform plan --out=plan.out -var="project=MY_PROJECT_ID"
163 | terraform apply plan.out
164 | ````
165 |
166 | * After you enter the terraform apply command, the Terraform code waits until the infrastructure fully deploys which can take up to five minutes. Terraform will create the service account and then launch an instance and deploy Microk8s on the instance. At the end of the build you should see output similar the figure below.
167 |
168 | ```
169 | Outputs:
170 |
171 | Output10_resource_suffix = plk4hs
172 | Output20_repository_name = microk8-anthos-config-plk4hs
173 | Output30_service_account_email = anthos-register-plk4hs@jslevine-anthos.iam.gserviceaccount.com
174 | Output40_instance_names = [
175 | "microk8s-us-central1-b-01-plk4hs",
176 | ]
177 | ```
178 |
179 | * The *resource_suffix* above is a random suffix which is appended to the names of the deployed Google Cloud resources as shown in the lines that follow. This enables you to deploy the code multiple times in the same Google Cloud project. It will also help you identify resources in the event that there is a problem with the cleanup scripts.
180 |
181 | * Open a scratch file on your system and copy the outputs from Terraform into the scratch file to make them easier to access later.
182 |
183 | # Configure the repository
184 |
185 | * The Terraform scripts created additional files on your workstation. The anthos-cm directory now has additional files that we will use to to prepare the repository for Anthos Config Management. The anthos-cm directory structure appears below.
186 |
187 | ```
188 | anthos-cm
189 | ├── static
190 | │ ├── hello.yaml
191 | │ └── microk8s.yaml
192 | └── var
193 | ├── 200-setup-repo
194 | └── acm-public-key.openssh
195 | ```
196 |
197 | * In the above diagram, the *static* directory contains YAML files that represent the application you will eventually commit to the Kubernetes configuration repository provided by Cloud Source Repositories which will in turn be deployed to the Microk8s cluster. The *var* directory contains files that will be used to configure the repository.
198 | In order for Anthos Config Management to check the repository for commits, you must install a public key in Cloud Source Repositories. A public key has been created for you. Display the key using the command below.
199 |
200 | ```
201 | cat $BASEDIR/anthos-cm/var/acm-public-key.openssh
202 | ```
203 |
204 | * From the Google Cloud console, select Source Repositories. Hover over the line and click the "+" icon as shown below. You will then see a window appear with additional information.
205 |
206 | 
207 |
208 | 
209 |
210 | * Click the Register the SSH key link. You may be asked to enter your account password. A new window will open. Pick a name for the key and then paste in the contents of the *acm-public-key.openssh* file you previously displayed and click *REGISTER*.
211 |
212 | * Go back to the window with the cloning information. In the field under *Clone with command line*, copy the URL beginning with ssh:// until the end of the line into your scratch file.
213 |
214 | * Use the following commands to initialize the repository.
215 |
216 | ```
217 | cd $BASEDIR/anthos-cm/var
218 | ./200-setup-repo
219 | ```
220 |
221 | * At the end of the setup process, notice that the branch microk8s has been created. The branch name will need to be specified when Anthos Config management is created.
222 |
223 | ```
224 | Branch 'microk8s' set up to track remote branch 'microk8s' from 'origin'.
225 | ```
226 |
227 | * You have completed the core configuration of the repository. You will now set up Anthos Config Management on the Microk8s cluster instance.
228 |
229 | # Set up Anthos Config Management
230 |
231 | You will now set up Anthos Config Management on the Microk8s cluster instance.
232 |
233 | * Ssh into the Microk8s cluster instance. The instance name contains the random suffix shown in the outputs of the Terraform run.
234 |
235 | * Confirm that Microk8s is installed by running the command below and examining
236 | the output.
237 |
238 | ```
239 | microk8s config
240 |
241 | apiVersion: v1
242 | clusters:
243 | - cluster:
244 | certificate-authority-data: LS0...
245 | server: https://10.128.0.29:16443
246 | name: microk8s-cluster
247 | contexts:
248 | - context:
249 | cluster: microk8s-cluster
250 | user: admin
251 | name: microk8s
252 | current-context: microk8s
253 | kind: Config
254 | preferences: {}
255 | users:
256 | - name: admin
257 | user:
258 | username: admin
259 | password: ZHV...
260 | ```
261 |
262 | * Go to the directory containing the installation scripts.
263 |
264 | ```
265 | cd /usr/local/etc/anthos
266 | ```
267 |
268 | * Register the Microk8s cluster with the Anthos/GKE Hub using the command on the below. The output is shown after that. This script makes the cluster available for use by Anthos. At the completion of the script, you will see a message indicating the cluster has been registered.
269 |
270 | ```
271 | ./110-register-cluster
272 |
273 | Registering cluster to hub...
274 | Waiting for membership to be created...done.
275 | Created a new membership [projects/jslevine-anthos/locations/global/memberships/microk8s-us-central1-b-01-plk4hs] for the cluster [microk8s-us-central1-b-01-plk4hs]
276 | Generating the Connect Agent manifest...
277 | Deploying the Connect Agent on cluster [microk8s-us-central1-b-01-plk4hs] in namespace [gke-connect]...
278 | Deployed the Connect Agent on cluster [microk8s-us-central1-b-01-plk4hs] in namespace [gke-connect].
279 | Finished registering the cluster [microk8s-us-central1-b-01-plk4hs] with the Hub.
280 | ```
281 |
282 | * In order to allow the Google Cloud console to view information about the cluster, you will first create a Kubernetes Service Account with the command below.
283 |
284 | ```
285 | ./120-create-ksa
286 |
287 | Creating Kubernetes service account anthos-ksa...
288 | serviceaccount/anthos-ksa created
289 | Creating console-reader-role cluster role...
290 | clusterrole.rbac.authorization.k8s.io/cloud-console-reader created
291 | Binding console-reader-role cluster role to cluster anthos-ksa...
292 | clusterrolebinding.rbac.authorization.k8s.io/cloud-console-reader-binding created
293 | Binding view cluster role to cluster anthos-ksa...
294 | clusterrolebinding.rbac.authorization.k8s.io/view-binding created
295 | ```
296 |
297 | * Now that you have created a Kubernetes Service Account, you will get a token for the service account to register with the Google Cloud console.
298 |
299 |
300 | ```
301 | ./130-get-ksa-bearer-token
302 | === The cluster token starts below this line. ===
303 | ey....
304 | === The cluster token ends above this line. ===
305 | ```
306 |
307 | * Copy the entire token between the start/end lines to your clipboard. You may find it easier to select from the end of the token back to the beginning. You must get all of the characters.
308 |
309 | * Go to the Google Cloud console and select the Anthos -> Clusters menu. You will see the Microk8s cluster and may see a warning indicator as well. Click on the cluster and you will see a LOGIN button on the right side of the screen as shown below. Also note that Config Management is available, but not enabled.
310 |
311 | 
312 |
313 | * Click *LOGIN*. Select the Token radio button and paste in the bearer token from your clipboard and click *LOGIN*. You should see a message saying the cluster is healthy as shown below. If it is not successful, copy and paste the bearer token again into your clipboard to ensure you have all of the characters.
314 |
315 | 
316 |
317 | * Click on the cluster. On the right side of the window, you will see a *Cluster features* section. If *Config Management* is not enabled, click on the *Manage features* and enable it.
318 |
319 | * On the Microk8s cluster instance, you will see the file */usr/local/etc/acm-private-key.pem*. This is the private key associated with the *acm-public-key.openssh* that you configured into Cloud Source Repositories. Anthos Config Management needs this private key in order to be able to poll the Kubernetes repo for commits. Register the key using the command below. This will store the secret into the Microk8s cluster.
320 |
321 | ```
322 | ./210-register-acm-private-key
323 | ```
324 |
325 | * You now need to configure Anthos Config Management and tell it the name of the repo and the branch to use. Edit the file */usr/local/etc/anthos/config-management.yaml*. Replace *INSERT_SSH_CLONE_HERE* with the ssh:// URL that you copied into your scratchfile from the Cloud Source Repositories page. Do not include "git clone." Also, make sure you retain the quotation marks ("). Save the file.
326 |
327 | * Deploy the configuration to Anthos Config Management with the command below.
328 |
329 | ```
330 | ./220-config-acm
331 | ```
332 | * Check the status by running the command below.
333 |
334 | ```
335 | ./230-check-acm-status
336 | ```
337 |
338 | The Status value will vary between *ERROR* and *NOT_CONFIGURED* until eventually becoming *PENDING*, and finally *SYNCED*. The process can take a few minutes to complete.
339 |
340 | * You have now configured Anthos Config Management. In the next section, you will deploy a Kubernetes application.
341 |
342 | # Deploy the application
343 |
344 | You will now create a Kubernetes namespace and deploy an application by committing files to the repository from your workstation instance and viewing the results on the Microk8s cluster instance.
345 |
346 | * Let's start by creating a namespace named microk8s. On your workstation instance, change your working directory to the cloned repository directory by entering the command below.
347 |
348 | ```
349 | cd $BASEDIR/anthos-cm/var/micro*
350 | ```
351 |
352 | * The *namespaces* directory contains one directory for each namespace you wish to deploy. Create the namespaces/microk8s directory.
353 |
354 | ```
355 | mkdir namespaces/microk8s
356 | ```
357 |
358 | * Copy the namespace configuration into the newly created directory.
359 |
360 |
361 | ```
362 | cp $BASEDIR/anthos-cm/static/microk8s.yaml namespaces/microk8s
363 | cat namespaces/microk8s/microk8s.yaml
364 | ```
365 |
366 | * Notice how the name of the directory under the *namespaces* directory, the name of the YAML file defining the namespace, and the metadata field are identical. This is a requirement.
367 |
368 | * Now commit the change to the repository. Note that you are committing to the *microk8s* branch. This is the branch name defined in the *config-management.yaml* file that was used to configure Anthos Config Management above.
369 |
370 | ```
371 | git add namespaces/microk8s/microk8s.yaml
372 | git commit -m "define namespace microk8s"
373 | git push -u origin microk8s
374 | ```
375 |
376 | * Go to your Microk8s cluster instance and run *microk8s kubectl* to check for the presence of the namespace. It may take a minute or two for it to be available.
377 |
378 | ```
379 | microk8s kubectl get namespaces
380 |
381 | NAME STATUS AGE
382 | config-management-system Active 139m
383 | default Active 23h
384 | gke-connect Active 8h
385 | kube-node-lease Active 23h
386 | kube-public Active 23h
387 | kube-system Active 23h
388 | microk8s Active 96s
389 | ```
390 |
391 | * You can see that a namespace was deployed. Run the following command to learn more about the namespace.
392 |
393 | ```
394 | microk8s kubectl describe namespace microk8s
395 | ```
396 |
397 | * In the output for the above command you can see labels and annotations that refer to *configmanagement.gke.io* which shows that the namespace was deployed with Anthos Config Management.
398 |
399 | * On your workstation instance, run the commands below to deploy the *hello* application.
400 |
401 | ```
402 | cd $BASEDIR/anthos-cm/var/micro*
403 | cp $BASEDIR/anthos-cm/static/hello.yaml namespaces/microk8s
404 | git add namespaces/microk8s/hello.yaml
405 | git commit -m "deploying hello.yaml"
406 | git push -u origin microk8s
407 | ```
408 |
409 | * On the Microk8s cluster instance, run the two *microk8s kubectl* commands below to view the deployments. Some output columns have been removed to improve the readability of the information.
410 |
411 | ```
412 | microk8s kubectl get deployments -n microk8s
413 |
414 | NAME READY UP-TO-DATE AVAILABLE AGE
415 | hello-app 1/1 1 1 13m
416 |
417 | mirok8s kubectl get services -n microk8s
418 |
419 | NAME TYPE CLUSTER-IP ... PORT(S) ...
420 | hello-nodeport NodePort 10.152.183.24 ... 80:31423/TCP ...
421 | ```
422 |
423 | * The output shows that there have been two deployments, an application named *hello-app* and a service named *hello-nodeport*. Note the *CLUSTER-IP* address for the *hello-nodeport* service.
424 | Use the *curl* command to communicate with the service and the backend application.
425 |
426 | ```
427 | curl 10.152.183.24
428 |
429 | Hello, world!
430 | Version: 1.0.0
431 | Hostname: hello-app-578d477bbd-gqxj6
432 | ```
433 |
434 | * You have now completed the deployment of the application and nodeport service. Rather than logging on to each instance running a cluster and using *kubectl* to manually deploy the code, Anthos Config Management allowed you to automate the process. You commited the code to a Git repository and Anthos Config Management detected the commit and deployed the code for you.
435 |
436 | Cleanup
437 |
438 | Here are the steps to follow on both the MicroK8s cluster instance and on the workstation instance.
439 |
440 | * On the Microk8s cluster instance, unregister the cluster using the command below.
441 |
442 | ```
443 | cd /usr/local/etc/anthos
444 | ./910-unregister-cluster
445 | ```
446 |
447 | * On the workstation instance, disable the Anthos API if you are no longer using so as not to incur Anthos API-related changes. *Note that this does not disable any of the other APIs that were previously enabled.*
448 |
449 |
450 | ```
451 | cd $BASEDIR/cleanup
452 | ./910-disable-anthos
453 | ```
454 |
455 | * Tear down the infrastructure provisioned by Terraform. Replace MY_PROJECT_ID in the command below with your Google Cloud project ID.
456 |
457 | ```
458 | cd $BASEDIR
459 | terraform destroy -var="project=MY_PROJECT_ID"
460 | ```
461 |
462 | * Delete the workstation instance if you no longer need it.
463 |
464 | # Other items of interest
465 |
466 | * You can specify the number of Microk8s instances and the regions in which they
467 | are deployed by modifying the *intanceInfo* variable in the *terraform.tfvars* file in the root Terraform
468 | module.
469 |
470 | * The Terraform code in *modules/microk8s/main.tf* uses
471 | *[cloud-init](https://cloudinit.readthedocs.io/en/latest/index.html)* to
472 | initialize the Ubuntu instance. Cloud-init provides a structure way to
473 | perform various tasks such as writing files and running scripts at various
474 | stages of the boot process. In the deployed infarstructure, cloud-init
475 | installs Microk8s and also sets up the */usr/local/etc/anthos* file structure.
476 |
477 | When using cloud-init in an instance being built by a framework such as
478 | Terraform or even shell scripts, it may be desirable to know when cloud-init's
479 | processing has completed. There are two parts to doing this. First, the
480 | cloud-init script adds a label to the instance after cloud-init's
481 | initialization has completed. Second, a *[null
482 | resource](https://registry.terraform.io/providers/hashicorp/null/latest/docs/resources/resource)*
483 | waits until a label has been created.
484 |
485 | # Let's review
486 |
487 | Anthos Config Management enables you to deploy code from a Git repository to Kubernetes clusters that have been registered with Anthos. Google Cloud currently supports GKE, AKS, and EKS clusters, but you can attach other conformant clusters as well.
488 | This example shows how to register a single Microk8s cluster to receive deployments from a repository provided by Cloud Source Repositories. You can scale this to larger numbers of clusters all of which can receive updates from commitments to the repository. In short, Anthos Config Management allows you to bring Git-ops practices to the world of Kubernetes deployments.
489 |
--------------------------------------------------------------------------------
/anthos-cm/static/hello.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Google LLC
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | # hello.yaml
16 | #
17 | # Create a "hello world" Kubernetes deployment including an application
18 | # container as well as a frontend load balancer
19 |
20 | apiVersion: v1
21 | kind: Service
22 | metadata:
23 | name: hello-nodeport
24 | spec:
25 | ports:
26 | - port: 80
27 | protocol: TCP
28 | targetPort: 8080
29 | selector:
30 | app: hello
31 | type: NodePort
32 | ---
33 | apiVersion: apps/v1
34 | kind: Deployment
35 | metadata:
36 | labels:
37 | app: hello
38 | name: hello-app
39 | spec:
40 | selector:
41 | matchLabels:
42 | app: hello
43 | template:
44 | metadata:
45 | labels:
46 | app: hello
47 | spec:
48 | containers:
49 | - image: gcr.io/google-samples/hello-app:1.0
50 | name: hello-app
51 | ports:
52 | - containerPort: 8080
53 |
--------------------------------------------------------------------------------
/anthos-cm/static/microk8s.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Google LLC
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | apiVersion: v1
16 | kind: Namespace
17 | metadata:
18 | name: microk8s
19 |
--------------------------------------------------------------------------------
/cleanup/910-disable-anthos:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | # disable-anthos
4 | #
5 | # Disable Anthos API to reduce charges
6 |
7 | echo Disabling Anthos...
8 |
9 | gcloud services disable anthos.googleapis.com
10 |
--------------------------------------------------------------------------------
/img/.gitkeep:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/img/AnthosCMHighLevel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/anthos-microk8s/b3f3ac02c7c9ab372ef176d36cd32c6eff6d6afa/img/AnthosCMHighLevel.png
--------------------------------------------------------------------------------
/img/AnthosMicrok8sTitle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/anthos-microk8s/b3f3ac02c7c9ab372ef176d36cd32c6eff6d6afa/img/AnthosMicrok8sTitle.png
--------------------------------------------------------------------------------
/img/ClusterPostLogin.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/anthos-microk8s/b3f3ac02c7c9ab372ef176d36cd32c6eff6d6afa/img/ClusterPostLogin.png
--------------------------------------------------------------------------------
/img/PostClone.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/anthos-microk8s/b3f3ac02c7c9ab372ef176d36cd32c6eff6d6afa/img/PostClone.png
--------------------------------------------------------------------------------
/img/PreRegister.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/anthos-microk8s/b3f3ac02c7c9ab372ef176d36cd32c6eff6d6afa/img/PreRegister.png
--------------------------------------------------------------------------------
/img/SourceRepoPreClone.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/anthos-microk8s/b3f3ac02c7c9ab372ef176d36cd32c6eff6d6afa/img/SourceRepoPreClone.png
--------------------------------------------------------------------------------
/main.tf:
--------------------------------------------------------------------------------
1 | # main.tf - entry point for the Terraform project.
2 |
3 | # Define and configure providers.
4 | #
5 | # provider google - The Google Cloud provider
6 | #
7 | # provider random - Generates random suffixes for resource names.
8 | # All resources are created with the same suffix for easier identification.
9 | #
10 | # provider null - For creating null resources not provided by Google Cloud.
11 | # One such resource is used in the microk8s module for waiting for cloud-init
12 | # to complete.
13 |
14 | terraform {
15 | required_providers {
16 | google = {
17 | source = "hashicorp/google"
18 | version = ">= 3.42.0"
19 | }
20 |
21 | local = {
22 | source = "hashicorp/local"
23 | version = "~> 2.0.0"
24 | }
25 |
26 | null = {
27 | source = "hashicorp/null"
28 | version = "~> 3.0.0"
29 | }
30 |
31 | random = {
32 | source = "hashicorp/random"
33 | version = "~> 3.0.0"
34 | }
35 |
36 | tls = {
37 | source = "hashicorp/tls"
38 | version = "~> 3.0.0"
39 | }
40 | }
41 | }
42 |
43 | provider "google" {
44 | project = var.project
45 | region = var.defaultRegion
46 | }
47 |
48 | # Generate a random suffix for Google Cloud resources. This is useful when
49 | # tearing down and building the environment again. Using the same name can
50 | # cause duplication errors due to the eventual consistency matters associated
51 | # with IAM clean up. Special and uppercase characters are not used because
52 | # they are not supported in certain Google Cloud resouirces.
53 |
54 | resource "random_string" "randomSuffix" {
55 | length = 6
56 | upper = false
57 | lower = true
58 | number = true
59 | special = false
60 | }
61 |
62 | # Create the Google Cloud Service Account that will be used to register
63 | # the cluster to the Anthos/GKE hub.
64 |
65 | module "service_account" {
66 | source = "./modules/serviceaccount"
67 |
68 | project = var.project
69 | SAName = var.anthosRegisterSA
70 | suffix = random_string.randomSuffix.result
71 | }
72 |
73 | # Generate a public/private key pair for setting up Anthos Config Mgmt.
74 | #
75 | # The public key will be stored in the Anthos Configuration Management
76 | # git repository that is provided by Cloud Source Repositories.
77 | #
78 | # The private key will be distributed to each microk8s cluster so it can
79 | # pull the configuration from the git repository provided by Cloud Source
80 | # Repositories.
81 |
82 | resource "tls_private_key" "cmRepoKey" {
83 | algorithm = "RSA"
84 | rsa_bits = 4096
85 | }
86 |
87 | # Create the repository on Cloud Source Repositories for the
88 | # Anthos Configuration Management part of this exercise.
89 |
90 | resource "google_sourcerepo_repository" "anthosConfigRepo" {
91 | name = "microk8-anthos-config-${random_string.randomSuffix.result}"
92 | }
93 |
94 | # Create the microk8s instances
95 | #
96 | # The Configuration Management repository private key (cmRepoKey) is encoded
97 | # with base64 to make it easier to process in the microk8s module with
98 | # cloud-init.
99 |
100 | module "microk8s" {
101 | source = "./modules/microk8s"
102 |
103 | initCompletedLabel = var.initCompletedLabel
104 | instanceInfo = var.instanceInfo
105 | microk8sRelease = var.microk8sRelease
106 | project = var.project
107 | SAemail = module.service_account.serviceAccountInfo.email
108 | SAprivateKey = module.service_account.serviceAccountKeyInfo.private_key
109 | CMprivateKey = base64encode(tls_private_key.cmRepoKey.private_key_pem)
110 | suffix = random_string.randomSuffix.result
111 | cmRepoName = google_sourcerepo_repository.anthosConfigRepo.name
112 | gitBranch = var.gitBranch
113 | }
114 |
115 | resource "local_file" "cmPublicKeyOpsenSsh" {
116 | content = tls_private_key.cmRepoKey.public_key_openssh
117 | filename = "${path.module}/anthos-cm/var/acm-public-key.openssh"
118 | file_permission = "0600"
119 | directory_permission = "0700"
120 | }
121 |
122 | resource "local_file" "setupRepo" {
123 | content = < inst
88 | }
89 |
90 | name = "${each.key}-${var.suffix}"
91 | machine_type = each.value.machineType
92 | zone = each.value.zone
93 |
94 | boot_disk {
95 | initialize_params {
96 | image = join("", [
97 | "projects/",
98 | each.value.imageProject,
99 | "/global/images/family/",
100 | each.value.imageFamily
101 | ])
102 | }
103 | }
104 |
105 | network_interface {
106 | network = each.value.network
107 |
108 | access_config {
109 | // Ephemeral IP
110 | }
111 | }
112 |
113 | service_account {
114 | email = var.SAemail
115 | scopes = [
116 | "cloud-platform"
117 | ]
118 | }
119 |
120 | metadata = {
121 | user-data = < ~/.kube/config
140 | fi
141 |
142 | # Turn of syntax highlighting - a personal preference.
143 |
144 | if [ ! -f ~/.vimrc ]
145 | then
146 | echo Creating ~/.vimrc...
147 | echo "syntax off" > ~/.vimrc
148 | fi
149 |
150 | echo All Anthos files are in /usr/local/etc/anthos.
151 | export CLUSTER_CONTEXT=`kubectl config current-context`
152 | export KUBECONFIG_PATH=~/.kube/config
153 | export SA_KEY_PATH=/usr/local/etc/anthos/cluster-reg-key.json
154 | append: true
155 |
156 | - path: /etc/security/group.conf
157 | content: |
158 | *;*;*;Al;microk8s
159 | append: true
160 |
161 | - path: /etc/pam.d/sshd
162 | content: |
163 | auth optional pam_group.so
164 | append: true
165 |
166 | - path: /usr/local/etc/anthos/cluster-reg-key.json
167 | content: ${var.SAprivateKey}
168 | encoding: base64
169 | permissions: "0664"
170 |
171 | - path: /usr/local/etc/anthos/acm-private-key.pem
172 | content: ${var.CMprivateKey}
173 | encoding: base64
174 | permissions: "0664"
175 |
176 | - path: /usr/local/etc/anthos/config-management.yaml
177 | content: |
178 | # config-management.yaml
179 |
180 | apiVersion: configmanagement.gke.io/v1
181 | kind: ConfigManagement
182 | metadata:
183 | name: config-management
184 | spec:
185 | git:
186 | syncRepo: "INSERT_SSH_CLONE_URL_HERE"
187 | syncBranch: ${var.gitBranch}
188 | secretType: ssh
189 | permissions: "0664"
190 |
191 | - path: /usr/local/etc/anthos/110-register-cluster
192 | content: |
193 | #!/bin/sh
194 |
195 | # register-cluster
196 | #
197 | # Register the cluster using the service account private key.
198 |
199 | echo Registering cluster to hub...
200 | gcloud container hub memberships register `hostname` \
201 | --context="$CLUSTER_CONTEXT" \
202 | --service-account-key-file=$SA_KEY_PATH \
203 | --kubeconfig=$KUBECONFIG_PATH \
204 | --project=${var.project}
205 | permissions: "0755"
206 |
207 | - path: /usr/local/etc/anthos/120-create-ksa
208 | content: |
209 | #!/bin/sh
210 |
211 | # create-ksa
212 | #
213 | # Create the Kubernetes Service Account (KSA) that will be used when
214 | # logging into the cluster from the cluster registration console page.
215 | #
216 | # Details:
217 | #
218 | # (1) Create the Kubernetes Service Account.
219 | # (2) Define the cloud-console-reader role.
220 | # (3) Bind the cloud-console-reader role to the KSA.
221 | # (4) Bind the view role to the KSA
222 |
223 | KSA_NAME=anthos-ksa
224 | echo Creating Kubernetes service account $KSA_NAME...
225 | kubectl create serviceaccount $KSA_NAME
226 |
227 | echo Creating console-reader-role cluster role...
228 | kubectl apply -f - <