<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Christopher Grant on Medium]]></title>
        <description><![CDATA[Stories by Christopher Grant on Medium]]></description>
        <link>https://medium.com/@cgrant?source=rss-60e881a91384------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bgu11BA5dQcGbjPGybWV_Q.jpeg</url>
            <title>Stories by Christopher Grant on Medium</title>
            <link>https://medium.com/@cgrant?source=rss-60e881a91384------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 02:48:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cgrant/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Navigating Tech Terrain Essential Advice for SaaS Startups]]></title>
            <link>https://cgrant.medium.com/navigating-tech-terrain-essential-advice-for-saas-startups-2fbd2d01b641?source=rss-60e881a91384------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fbd2d01b641</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Christopher Grant]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 01:14:11 GMT</pubDate>
            <atom:updated>2025-01-11T01:14:11.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gv7fJm3qgK7wHwqrsLNVPA.png" /><figcaption>Illustration: ‘Navigating Tech Terrain’ created with DALL·E</figcaption></figure><p>The SaaS world is brimming with opportunity, but navigating the technical landscape can be challenging. While focusing on building an exceptional product is crucial, overlooking key technical aspects can hinder growth, impact user experience, and even threaten the viability of a SaaS startup.</p><p>Let’s explore three common technical pitfalls that can significantly impact a SaaS startup’s trajectory, plus one often-overlooked strategy for long-term success. We’ll also outline effective strategies to avoid these issues.</p><h3>1. The Foundation Matters: Strategic Architecture Choices</h3><p>Imagine constructing a skyscraper, only to discover after completion that it leans precariously (true story <a href="https://www.youtube.com/watch?v=7QrvbUxOamo">161 Maiden Lane</a>). This scenario illustrates the criticality of a solid foundation in any structure, including your SaaS product. Choosing an inadequate architecture early on can lead to performance bottlenecks, scalability challenges, and hinder future development efforts.</p><p>Recommendation: Invest time in designing a robust and scalable architecture from the outset. Consider employing microservices, adopting cloud-native solutions, and consulting with experienced software architects to ensure a solid foundation.</p><p>Pro Tip: Think of your architecture like building with Lego blocks. You want to be able to add new features and scale things up easily without the whole thing falling apart.</p><h3>2. Scaling for the Future: Anticipating Growth</h3><p>Your MVP is a big hit! Users are flocking to your platform, but suddenly your servers crash. This scenario, unfortunately familiar to many startups, highlights the importance of scalability. Failing to anticipate and accommodate growth can result in downtime, frustrated customers, and damage to your reputation.</p><p>Recommendation: Design your application with scalability in mind. Always be thinking about the future! Design your application with scalability in mind. <a href="https://cloud.google.com/">Google Cloud Platform</a> (GCP) is fantastic for this, with its auto-scaling features that can handle those sudden bursts of traffic. Implement load balancing and caching mechanisms to optimize performance and manage traffic spikes effectively.</p><p>Anecdote: There’s a cautionary tale in the startup world about a company whose servers melted down after being featured on a popular website. They hadn’t prioritized scalability, and the sudden surge in traffic overwhelmed their system. It’s a classic example of why anticipating growth is so crucial.</p><h3>3. Security is Non-Negotiable: Protecting User Data</h3><p>Data breaches pose a significant threat to SaaS startups. Compromised user information can erode trust, lead to legal ramifications, and severely damage the company’s standing.</p><p>Recommendation: Security is your best friend! Make it a top priority from day one. Strong authentication and authorization are a must, and encrypting sensitive data is like locking it in a vault. Regular security audits and penetration testing? Consider them your security checkups — they help you find and fix any weak spots before the bad guys do. This guide from OWASP is a fantastic resource for building secure web applications: <a href="https://owasp.org/www-project-top-ten/](https://owasp.org/www-project-top-ten/)">https://owasp.org/www-project-top-ten/</a></p><p>Bonus Tip: Don’t forget about compliance! Regulations like GDPR <a href="https://gdpr.eu/">https://gdpr.eu/</a> and CCPA <a href="https://oag.ca.gov/privacy/ccpa">https://oag.ca.gov/privacy/ccpa</a> are there to protect user data, and you need to make sure you’re following the rules. Nobody wants a hefty fine, right? And check out Google Cloud’s compliance resources here: <a href="https://cloud.google.com/security/compliance](https://www.google.com/url?sa=E&amp;source=gmail&amp;q=https://cloud.google.com/security/compliance)">https://cloud.google.com/security/compliance</a></p><h3>4. Future-Proofing Your Product: Designing for Tomorrow’s Features</h3><p>Building a successful SaaS product isn’t just about meeting today’s needs; it’s about anticipating tomorrow’s. Failing to design for future features and iterative development can lead to a rigid architecture that’s difficult to adapt and scale.</p><p>Recommendation: Embrace agile development methodologies that prioritize flexibility and iteration. Choose technologies and frameworks that allow for easy modification and expansion. Consider modular design principles that enable you to add or remove components without disrupting the entire system.</p><p>Key Takeaway: By addressing these technical considerations early on, SaaS startups can build a strong foundation for sustainable growth and avoid potentially detrimental consequences. Investing in robust architecture, scalability, security, and future-proof design is an investment in the company’s future.</p><p>Let’s learn from each other! Share your own tech experiences in the comments below. What challenges have you faced, and how did you overcome them?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fbd2d01b641" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming the Cloud Beast: A CTO’s Guide to Strategic Cost Optimization on Google Cloud]]></title>
            <link>https://cgrant.medium.com/taming-the-cloud-beast-a-ctos-guide-to-strategic-cost-optimization-on-google-cloud-eca05521199c?source=rss-60e881a91384------2</link>
            <guid isPermaLink="false">https://medium.com/p/eca05521199c</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cto]]></category>
            <category><![CDATA[finops]]></category>
            <dc:creator><![CDATA[Christopher Grant]]></dc:creator>
            <pubDate>Tue, 21 May 2024 14:43:27 GMT</pubDate>
            <atom:updated>2024-05-21T14:43:27.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDoemt175p_MvJqOvgjnsg.png" /></figure><p>The allure of cloud computing, with its unparalleled scalability and on-demand resources, is transforming how businesses operate. However, the ease of provisioning resources can often lead to a “cloud cost beast” — spiraling expenses that erode value and catch leadership off guard. CTOs, as the stewards of technology strategy, must proactively tame this beast to ensure their organizations fully benefit from the cloud’s potential without financial strain.</p><p>I. The Cost Conundrum: A CTO’s Top Priority</p><p>Beneath the cloud’s promise of efficiency lies a complex web of costs. “Hidden” expenses like data egress fees, storage overages, and idle resources can quietly accumulate, catching finance teams off guard when the monthly invoice arrives. Research from McKinsey highlights that organizations often overspend by 40–85% on cloud resources due to a lack of visibility and management. <a href="https://www.mckinsey.com/capabilities/mckinsey-digital/our-insights/more-for-less-five-ways-to-lower-cloud-costs-without-destroying-value">McKinsey Research: How to Tame Your Cloud Costs</a></p><p>The financial repercussions of uncontrolled cloud spending reach far beyond the IT budget. Runaway costs directly impact profitability, diverting funds from critical initiatives like innovation, marketing, and talent acquisition. In today’s fiercely competitive landscape, the inability to manage cloud costs can stifle growth and threaten long-term viability. As Andreessen Horowitz aptly puts it, “Cloud is about agility and cost savings, but the latter is often an afterthought.”<a href="https://www.forbes.com/sites/forbestechcouncil/2023/01/23/the-top-three-things-you-dont-know-about-cloud-optimization/">Andreesen Horowitz on Cloud Costs</a></p><p>CTOs, with their unique vantage point at the intersection of technology and business strategy, are uniquely positioned to tackle this challenge head-on. By prioritizing cloud cost optimization as a strategic imperative, CTOs can drive initiatives that not only control spending but also unlock new avenues for efficiency and innovation. This proactive approach is a hallmark of successful CTOs, as evidenced by case studies from companies like Pinterest, which achieved substantial cost savings by optimizing their cloud infrastructure. <a href="https://www.theinformation.com/articles/how-pinterest-learned-to-control-cloud-costs">Pinterest’s Cloud Cost Optimization Success</a></p><p>II. Three Pillars of Effective Cloud Cost Optimization on Google Cloud</p><p>Taming the cloud cost beast requires a multi-faceted approach built on three fundamental pillars:</p><p>Visibility and Accountability: The first step towards optimization is understanding where and how money is being spent. Google Cloud’s Cost Management tools, such as Cloud Billing and Budgets &amp; Alerts, provide granular insights into spending patterns by project, team, or application. <a href="https://cloud.google.com/cost-management">Google Cloud Cost Management</a> By implementing detailed cost allocation and tagging, CTOs can uncover hidden costs and hold teams accountable for their cloud usage. This transparency not only drives cost awareness but also empowers teams to make informed decisions that align with both technical and financial goals. A study by 451 Research found that organizations with mature cost management practices achieve 20–30% cost savings compared to those with immature practices. <a href="https://go.451research.com/2020-mi-cloud-financial-management-cost-optimized-scalability.html?utm_source=covidms">451 Research: The State of Enterprise Cloud Cost Management</a></p><p>Rightsizing and Resource Efficiency: The cloud’s elasticity is a double-edged sword. While scaling on demand is a significant advantage, it can also lead to waste if not carefully managed. CTOs must proactively identify and eliminate unused or underutilized resources, leveraging Google Cloud’s Recommender API to pinpoint optimization opportunities. <a href="https://cloud.google.com/recommender/docs/reference/rest">Google Cloud Recommender API</a> Rightsizing virtual machines and storage options based on actual workload demands ensures that resources are neither overprovisioned nor underprovisioned. Furthermore, embracing Google Cloud’s autoscaling capabilities allows resources to dynamically adapt to fluctuating needs, maximizing efficiency and cost-effectiveness. Research from Gartner shows that rightsizing can lead to 30% savings on cloud infrastructure costs. <a href="https://www.gartner.com/en/infrastructure-and-it-operations-leaders/insights/manage-and-optimize-a-cloud-environment">Gartner: How to Right-Size Your Cloud Infrastructure</a></p><p>Strategic Cloud Provider Engagement: A successful cloud strategy involves more than just selecting the right provider; it requires a proactive and strategic partnership. CTOs should thoroughly understand Google Cloud’s pricing models, including sustained use discounts and committed use discounts, to maximize cost savings. <a href="https://cloud.google.com/products/calculator">Google Cloud Pricing</a> Negotiating volume discounts or custom pricing agreements can be highly beneficial, especially for organizations with long-term cloud commitments. Staying abreast of new Google Cloud services and features can also uncover opportunities to further reduce costs or enhance performance, ensuring the organization remains at the forefront of cloud innovation. A case study by Coca-Cola highlights how strategic engagement with their cloud provider led to significant cost reductions and operational efficiencies. <a href="https://medium.com/@chawalamona44/revolutionizing-growth-coca-colas-aws-cloud-journey-478af9d9e8b">Coca-Cola’s Strategic Cloud Partnership</a></p><p>III. Advanced Cost Optimization Techniques on Google Cloud</p><p>Beyond the foundational pillars, CTOs can leverage advanced techniques to achieve even greater cost optimization:</p><p>Modernizing Applications: Legacy applications, often designed for on-premises infrastructure, may not fully utilize the cloud’s potential for efficiency. Refactoring or containerizing these applications can significantly streamline resource utilization and improve performance on Google Cloud. This modernization effort not only reduces costs but also positions the organization to leverage cutting-edge cloud-native technologies like Kubernetes and Anthos. The Cloud Native Computing Foundation provides a wealth of resources on modernizing applications for the cloud. <a href="https://landscape.cncf.io/">CNCF Cloud Native Landscape</a></p><p>Intelligent Workload Management: Google Cloud’s AI and machine learning capabilities offer powerful tools for predicting demand patterns and optimizing resource allocation. <a href="https://cloud.google.com/products/ai">AI &amp; ML on Google Cloud</a> By analyzing historical usage data and real-time metrics, CTOs can anticipate spikes in demand and proactively scale resources to meet them. This intelligent workload management prevents overprovisioning and ensures that resources are available when needed, minimizing waste and maximizing cost efficiency.</p><p>Serverless Computing: For event-driven workloads, serverless computing on Google Cloud Functions or App Engine can be a game-changer. This model eliminates the need to manage servers, allowing organizations to pay only for the actual compute time consumed. <a href="https://cloud.google.com/functions">Google Cloud Functions</a> <a href="https://cloud.google.com/appengine">Google App Engine</a> By adopting serverless architectures, CTOs can drastically reduce operational overhead and achieve substantial cost savings, particularly for applications with unpredictable or sporadic usage patterns. A survey by Datadog found that organizations using serverless computing experienced a 40% reduction in cloud infrastructure costs. <a href="https://www.datadoghq.com/state-of-serverless/">Datadog: The State of Serverless</a></p><p>Additionally, for organizations leveraging Google Kubernetes Engine (GKE), Google Cloud provides a dedicated framework for FinOps and optimization, offering best practices and tools for cost-effective Kubernetes deployments. <a href="https://cloud.google.com/solutions/finops-optimize-gke">FinOps and optimization of GKE</a></p><p>Conclusion</p><p>In the dynamic world of cloud computing, cost optimization is not a one-time project but an ongoing journey. By embracing a proactive, data-driven approach and leveraging Google Cloud’s robust tools and services, CTOs can transform the “cloud beast” into a powerful engine for innovation and growth. The ability to tame cloud costs is not just a technical challenge but a strategic imperative that will shape the future of organizations in the digital age. As Gartner succinctly puts it, “Cloud cost optimization is not an option, it’s a necessity.” <a href="https://www.gartner.com/en/documents/3982411">Gartner: Cloud Cost Optimization</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eca05521199c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud Build for CICD]]></title>
            <link>https://cgrant.medium.com/cloud-build-for-cicd-c0e05e1a157e?source=rss-60e881a91384------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0e05e1a157e</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[cloud-build]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Christopher Grant]]></dc:creator>
            <pubDate>Mon, 28 Nov 2022 18:42:55 GMT</pubDate>
            <atom:updated>2022-11-28T18:42:55.315Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial you’ll walk through the steps needed to set up an end to end pipeline where GitHub triggers Cloud Build to process changes based on branches and deploy to GKE</p><p>What you’ll learn</p><ul><li>Enable services</li><li>Prepare source files</li><li>Build simple Dockerfile</li><li>Build with a config file</li><li>Connect to Git repository</li><li>Setup automated builds</li><li>Configure branch based deploys</li></ul><h3>Start Cloudshell Editor</h3><p>This lab was designed and tested for use with Google Cloud Shell Editor. To access the editor,</p><ul><li>Access your google project at <a href="https://console.cloud.google.com/">https://console.cloud.google.com</a>.</li><li>In the top right corner click on the cloud shell editor icon</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/0*AgssQVO0sS626Hjr" /></figure><ul><li>A new pane will open in the bottom of your window</li><li>You can toggle between the terminal and an editor by clicking the Open Editor button in the top bar</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/0*xCH-QMxowSlWlXxU" /></figure><ul><li>Then click Open Terminal to switch back to the terminal view</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/0*zCEmHsjMEQPsgFMH" /></figure><h3>Environment Setup</h3><p>In Cloud Shell, set your project ID and the project number for your project. Save them as PROJECT_ID and PROJECT_ID variables.</p><pre>export PROJECT_ID=$(gcloud config get-value project)<br>export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID \<br>    --format=&#39;value(projectNumber)&#39;)</pre><h3>Enable services</h3><p>Enable all necessary services:</p><pre>gcloud services enable \<br>  cloudbuild.googleapis.com \<br>  container.googleapis.com \<br>  containerregistry.googleapis.com \<br>  artifactregistry.googleapis.com \<br>  containerscanning.googleapis.com</pre><h3>Create a Docker repository in Artifact Registry</h3><p>Artifact Registry is a single place for your organization to manage container images and language packages (such as Maven and npm). In this lab, we will use artifact registry to manage container images.</p><p>Create a new Docker repository named quickstart-docker-repo in the location us-west2 with the description “Docker repository”:</p><pre>gcloud artifacts repositories create quickstart-docker-repo --repository-format=docker \<br>    --location=us-west2 --description=&quot;Docker repository&quot;</pre><p>Verify that your repository was created:</p><pre>gcloud artifacts repositories list</pre><p>You will see quickstart-docker-repo in the list of displayed repositories.</p><h3>Prepare source files</h3><p>Download the source code from github.</p><pre>git clone https://github.com/GoogleCloudPlatform/software-delivery-workshop.git<br><br>cd software-delivery-workshop &amp;&amp; rm -rf .git<br>cd labs/gke-progression</pre><p>In this section, you’ll build a simple Python app and Dockerfile. A Dockerfile is a text document that contains instructions for Docker to build an image.</p><p>Review the sample application located in src/app.py</p><pre>import os<br><br>from flask import Flask<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br>def hello_world():<br>    return &#39;Hello World v1.0&#39;<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(debug=True,host=&#39;0.0.0.0&#39;,port=8080)</pre><p>Review the file src/Dockerfile with the following contents:</p><pre>FROM python:3.7-slim<br><br>ENV APP_HOME /app<br>WORKDIR $APP_HOME<br>COPY . ./<br><br>RUN pip install Flask gunicorn<br><br>CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 app:app</pre><h3>Build simple Dockerfile</h3><p>Cloud Build allows you to build a Docker image using a Dockerfile. You don’t require a separate Cloud Build config file.</p><p>To build using a Dockerfile:</p><pre>gcloud builds submit --region=us-west2 --tag us-west2-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/quickstart-image:tag1 src/</pre><p>Note the value assigned to the tag parameter in the above command. You’ve just built a container image named quickstart-image using a Dockerfile and pushed the image to Artifact Registry into the docker repository created earlier.</p><h3>Build with a config file</h3><p>In this section you will use a Cloud Build config file to build the same container image as above. The build config file instructs Cloud Build to perform tasks based on your specifications.</p><p>In the same directory that contains quickstart.sh and the Dockerfile, create a file named cloudbuild.yaml with the following contents.</p><pre>cat &gt; ./cloudbuild.yaml &lt;&lt; EOF<br>steps:<br>- name: &#39;gcr.io/cloud-builders/docker&#39;<br>  args: [ &#39;build&#39;, &#39;-t&#39;, &#39;us-west2-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/quickstart-image:tag1&#39;, &#39;./src&#39; ]<br>images:<br>- &#39;us-west2-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/quickstart-image:tag1&#39;<br>EOF</pre><p>Start the build specifying the use of the cloudbuild.yaml by running the following command:</p><pre>gcloud builds submit --region=us-west2 --config cloudbuild.yaml</pre><p>You’ve just built an image using the build config file and pushed the image to Artifact Registry.</p><h3>Substitution Variables</h3><p>It’s often useful to provide variables to a build to configure specific parameters. In the cloudbuild.yaml file you just created, the region was hard coded to us-west2. In this step you will utilize <a href="https://cloud.google.com/build/docs/configuring-builds/substitute-variable-values">substitution variables</a> to provide the region dynamically</p><p>Built in Cloud Build Variables are accessible using the standard convention of ${VAR}, and user-defined substitutions must begin with an underscore (_) such as ${_VAR}</p><p>Rewrite the cloudbuild.yaml to use the build id variable provided by Cloud Build for the tag name and also use a user-defined variable for the region which will be passed in to the build.</p><pre>cat &gt; ./cloudbuild.yaml &lt;&lt; EOF<br>steps:<br>- name: &#39;gcr.io/cloud-builders/docker&#39;<br>  args: [ &#39;build&#39;, &#39;-t&#39;, &#39;\${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/quickstart-image:\${BUILD_ID}&#39;, &#39;./src&#39; ]<br>images:<br>- &#39;\${_REGION}-docker.pkg.dev/$PROJECT_ID/quickstart-docker-repo/quickstart-image:\${BUILD_ID}&#39;<br>EOF</pre><p>Start the build by running the following command that passes in the region variable:</p><pre>gcloud builds submit --region=us-west2 --config cloudbuild.yaml \<br>    --substitutions=_REGION=&quot;us-west2&quot;</pre><h3>Connect to Git repository</h3><p>If you don’t have one already, create an account on GitHub.</p><p>NOTE: If you have two-factor authentication set up on GitHub, create a <a href="https://github.com/settings/tokens/new">personal access token</a> with Repo permissions to use instead of a GitHub password with the command line. Save the token, you will use it multiple times in the future steps.</p><ul><li>Set your github username in an environment variable for later use</li></ul><pre>export GIT_USER=&lt;your user name&gt;</pre><ul><li>Set the git user name and email</li></ul><pre>git config --global user.email &quot;$(gcloud config list account --format &quot;value(core.account)&quot;)&quot;<br>git config --global user.name &quot;$(gcloud config list account --format &quot;value(core.account)&quot;)</pre><ul><li>Optionally store credentials so you don’t have to enter them multiple times</li></ul><pre>git config --global credential.helper store</pre><ul><li>Create a new public repository in GitHub called cloud-build-cicd</li><li>Initialize a local git repo and push the contents to Github</li></ul><p>Note: If using an access token, use the generated access token when prompted for password.</p><pre>git init &amp;&amp; git add . &amp;&amp; git commit -m &quot;initial commit&quot;<br>git remote add origin https://github.com/${GIT_USER}/cloud-build-cicd.git<br>git branch -M main<br>git push -u origin main</pre><p>To build source code from GitHub, you must first connect Cloud Build to your GitHub repository. In this section, you’ll use one way to connect your cloud-build-cicd repository to Cloud Build, but other mechanisms are also available.</p><ol><li>In the Google Cloud console navigation menu, click <strong>Cloud Build &gt; Triggers</strong>.<br><a href="https://console.cloud.google.com/cloud-build/triggers">Open Triggers page</a></li><li>At the bottom of the page, Click <strong>Connect repository</strong>.</li><li>Under <strong>Select source</strong>, select <strong>GitHub (Cloud Build GitHub App)</strong>.</li><li>Click <strong>Continue</strong>.</li><li>Authenticate your GitHub account.</li><li>Under <strong>Repository</strong>, select GITHUB_USERNAME<strong>/cloud-build-cicd</strong> as your repository.</li><li>Click the checkmark to agree to terms and conditions for trigger connection.</li><li>Click <strong>Connect</strong>.</li><li>Click <strong>Done</strong>.</li></ol><h3>Setup automated builds</h3><h3>Trigger</h3><p>Open the <strong>Triggers</strong> page in the Google Cloud console:<br><a href="https://console.cloud.google.com/cloud-build/triggers">Open Triggers page</a></p><p>At the bottom of the <strong>Triggers</strong> page, click <strong>Create trigger</strong>.</p><p>On the <strong>Create trigger</strong> page, enter the following settings:</p><ul><li><strong>Name</strong>: Enter sample-trigger as the name of your trigger.</li><li><strong>Event</strong>: Select <strong>Push to a branch</strong> as the repository event to invoke your trigger.</li><li><strong>Source</strong>: Select the GITHUB_USERNAME<strong>/cloud-build-cicd</strong> repository as your source, which contains your source code and your build config file.</li><li><strong>Configuration</strong>: Choose <strong>Cloud Build configuration file</strong> as your build config file.</li><li><strong>Cloud Build configuration file location</strong>: Specify the path to your Cloud Build configuration file as /cloudbuild.yaml</li></ul><p>Under Substitution variables click Add Variable and enter the following values:</p><ul><li>Variable 1 = <strong>_REGION</strong></li><li>Value = <strong>us-west2</strong></li></ul><p>Click <strong>Create</strong> to save your build trigger.</p><h3>Make a change</h3><p>In this section, you will commit a change to your cloud-build-cicd repository on your GitHub account.</p><p>Open the src/app.py file and update the line containing “Hello World v1.0” to “Hello World v1.1”</p><pre>@app.route(&#39;/&#39;)<br>def hello_world():<br>    return &#39;Hello World v1.1&#39;</pre><p>Commit your changes to GitHub by running the following commands:</p><pre>git add .<br>git commit -m &quot;update to v1.1&quot;<br>git push origin main</pre><p>You may be prompted to enter your credentials when pushing code to your repository. If prompted, enter your username and an authentication token.</p><p>You have now pushed a change to your repository. Your push will result in an automatic build by your trigger.</p><h3>Review build details</h3><p>In this section, you will view the build details associated with your invoked build after committing a change.</p><ol><li>In the Google Cloud console navigation menu, click <strong>Cloud Build &gt; History</strong>.<br><a href="https://console.cloud.google.com/cloud-build">Open the Cloud Build page</a></li><li>You will see the <strong>Build history</strong> page:</li><li>In the <strong>Build</strong> column, click the name of a build.</li><li>On the <strong>Build details</strong> page, click <strong>Build Artifacts</strong>.<br>Review the output locations of the assets build by this job</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*50DD71exJKKrtADh" /></figure><p>To view the build log, click the download icon and view the downloaded file.</p><p>You have successfully invoked a Cloud Build build using a trigger and viewed the build details.</p><h3>Delete the trigger</h3><p>You won’t use this trigger for the remainder of the lab so run the command below to delete it</p><pre>gcloud beta builds triggers delete sample-trigger</pre><h3>Capstone: Full CI/CD Pipeline</h3><p>In this section you will use what you’ve learned so far to build a typical developer workflow that incorporates dynamic branch based deployments for dev testing, Canary testing of commits to the main branch, and production rollout for tagged releases.</p><h3>Create a GKE Cluster</h3><p>This section will deploy to GKE so create a small cluster with the following commands</p><pre>export CLUSTER=mycluster<br>export ZONE=us-central1-c<br><br>gcloud container clusters create ${CLUSTER} --zone=${ZONE} --num-nodes &quot;2&quot;</pre><p>Give Cloud Build rights to your cluster.</p><p>Cloud Build will be deploying the application to your GKE Cluster and will need rights to do so.</p><pre>gcloud projects add-iam-policy-binding ${PROJECT_ID} \<br>    --member=serviceAccount:${@cloudbuild.gserviceaccount.com&quot;&gt;PROJECT_NUMBER}@cloudbuild.gserviceaccount.com \<br>    --role=roles/container.developer</pre><p>Replace placeholder values in the sample repository with your PROJECT_ID:<br>This command creates instances of the various config files unique to your current environment. It searches all the template files with extension tmpl, replaces the environment variables with the values and creates new files without tmpl extension.</p><pre><br>export APP_NAME=sample-app<br><br>for template in $(find . -name &#39;*.tmpl&#39;); do envsubst &#39;${PROJECT_ID} ${ZONE} ${CLUSTER} ${APP_NAME}&#39; &lt; ${template} &gt; ${template%.*}; done</pre><h3>Branch Triggers for developers</h3><p>Open the cloudshell editor in the current directory with the following command</p><pre>cloudshell workspace .</pre><p>Create a file called cloudbuild-branch.yaml with the following contents</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*dyMwgnaxuZTY6MRc" /></figure><pre>steps:<br><br>  ### Build<br>    - id: &#39;build&#39;<br>      name: &#39;gcr.io/cloud-builders/docker&#39;<br>      entrypoint: &#39;bash&#39;<br>      args: <br>        - &#39;-c&#39;<br>        - |<br>            docker build -t ${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:${BRANCH_NAME}-${SHORT_SHA} ./src<br>  <br>  ### Publish<br>    - id: &#39;publish&#39;<br>      name: &#39;gcr.io/cloud-builders/docker&#39;<br>      entrypoint: &#39;bash&#39;<br>      args: <br>        - &#39;-c&#39;<br>        - |<br>            docker push ${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:${BRANCH_NAME}-${SHORT_SHA}<br>  <br>  <br>  <br>  ### Deploy<br>    - id: &#39;deploy&#39;<br>      name: &#39;gcr.io/cloud-builders/gcloud&#39;<br>      env:<br>        - &#39;KUBECONFIG=/kube/config&#39;<br>      entrypoint: &#39;bash&#39;<br>      args:<br>        - &#39;-c&#39;<br>        - |<br>         <br>            PROJECT=$(gcloud config get-value core/project)<br>          <br>            <br>            gcloud container clusters get-credentials &quot;${_CLUSTER}&quot; \<br>              --project &quot;${PROJECT}&quot; \<br>              --zone &quot;${_ZONE}&quot;  <br>  <br>            sed -i &#39;s|gcr.io/$PROJECT_ID/$_APP_NAME:.*|${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:${BRANCH_NAME}-${SHORT_SHA}|&#39; ./k8s/deployments/dev/*.yaml<br>            <br>            kubectl get ns ${BRANCH_NAME} || kubectl create ns ${BRANCH_NAME}<br>            kubectl apply --namespace ${BRANCH_NAME} --recursive -f k8s/deployments/dev<br>            kubectl apply --namespace ${BRANCH_NAME} --recursive -f k8s/services<br>  <br>images:<br>  - &#39;${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:${BRANCH_NAME}-${SHORT_SHA}&#39;</pre><p>Toggle back to the terminal by clicking the Open Terminal button in the top nav bar</p><p>Create the trigger</p><pre>gcloud beta builds triggers create github \<br>    --name=&quot;branch-trigger&quot; \<br>    --repo-name=cloud-build-cicd \<br>    --repo-owner=${GIT_USER} \<br>    --branch-pattern=&quot;[^(.main)]&quot; \<br>    --build-config=cloudbuild-branch.yaml \<br>    --substitutions=_APP_NAME=&quot;sample-app&quot;,_CLUSTER=&quot;mycluster&quot;,_REGION=&quot;us-west2&quot;,_ZONE=&quot;us-central1-c&quot;</pre><p>You can view the newly create trigger on the <a href="https://console.cloud.google.com/cloud-build/triggers">Cloud Build Triggers</a> page</p><p>The trigger you just created will fire for commits to any branch that is not named main.</p><p>Create a branch</p><pre>git checkout -b mybranch</pre><p>Edit src/app.py change the output to v2.0</p><p>Commit the change and push to the repository</p><pre>git add .<br>git commit -m &quot;Updated to v2.0&quot;<br>git push origin mybranch</pre><ol><li>Review the build in progress on the build history page</li></ol><p><a href="https://console.cloud.google.com/cloud-build">Open the Cloud Build page</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*VkZO8cHpX93QpUMK" /></figure><p>Review GKE <a href="https://console.cloud.google.com/kubernetes/workload/overview">workloads</a>. A new namespace ‘mybranch’ was created that matches the name of the branch and a sample-app-dev application was deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WxowU88CIQVpkQK4" /></figure><h3>Main Triggers for Canary deploys</h3><p>Create a file called cloudbuild-main.yaml with the following contents</p><pre>steps:<br><br>  ### Build<br>  <br>    - id: &#39;build&#39;<br>      name: &#39;gcr.io/cloud-builders/docker&#39;<br>      entrypoint: &#39;bash&#39;<br>      args: <br>        - &#39;-c&#39;<br>        - |<br>            docker build -t ${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:${SHORT_SHA} ./src<br>  <br>  <br>  ### Test<br>  <br>  <br>  ### Publish<br>    - id: &#39;publish&#39;<br>      name: &#39;gcr.io/cloud-builders/docker&#39;<br>      entrypoint: &#39;bash&#39;<br>      args: <br>        - &#39;-c&#39;<br>        - |<br>            docker push ${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:${SHORT_SHA}<br>  <br>  <br>  <br>  ### Deploy<br>    - id: &#39;deploy&#39;<br>      name: &#39;gcr.io/cloud-builders/gcloud&#39;<br>      env:<br>        - &#39;KUBECONFIG=/kube/config&#39;<br>      entrypoint: &#39;bash&#39;<br>      args:<br>        - &#39;-c&#39;<br>        - |<br>            PROJECT=$$(gcloud config get-value core/project)          <br>  <br>            gcloud container clusters get-credentials &quot;${_CLUSTER}&quot; \<br>              --project &quot;$${PROJECT}&quot; \<br>              --zone &quot;${_ZONE}&quot;  <br>  <br>  <br>            sed -i &#39;s|gcr.io/$PROJECT_ID/$_APP_NAME:.*|${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:${SHORT_SHA}|&#39; ./k8s/deployments/canary/*.yaml<br>            <br>            kubectl get ns production || kubectl create ns production<br>            kubectl apply --namespace production --recursive -f k8s/deployments/canary<br>            kubectl apply --namespace production --recursive -f k8s/services<br>  <br>images:<br>  - &#39;${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:${SHORT_SHA}&#39;<br><br></pre><p>Add the new yaml you just created file to the repo</p><pre>git add . &amp;&amp; git commit -m &quot;Added Main Trigger&quot;</pre><p>Create the trigger for commits to the main branch</p><pre>gcloud beta builds triggers create github \<br>    --name=&quot;main-trigger&quot; \<br>    --repo-name=cloud-build-cicd \<br>    --repo-owner=${GIT_USER} \<br>    --branch-pattern=main \<br>    --build-config=cloudbuild-main.yaml \<br>    --substitutions=_APP_NAME=&quot;sample-app&quot;,_CLUSTER=&quot;mycluster&quot;,_REGION=&quot;us-west2&quot;,_ZONE=&quot;us-central1-c&quot;</pre><p>You can view the newly created trigger on the <a href="https://console.cloud.google.com/cloud-build/triggers">Cloud Build Triggers</a> page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UkJX6eSeqWB2uyAn" /></figure><p>Merge the branch into main</p><pre>git checkout main<br>git merge mybranch<br>git push origin main</pre><p>This will trigger the build job for the main branch</p><p>Review the build in progress on the build history page</p><p><a href="https://console.cloud.google.com/cloud-build">Open the Cloud Build page</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*6GAz6YI80AsASz-4" /></figure><p>Review GKE <a href="https://console.cloud.google.com/kubernetes/workload/overview">workloads</a>. Production name space was created and a sample-app-canary application was deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*Fa7lnOZlc2MZdHSR" /></figure><h3>Tag Triggers for production releases</h3><p>Create a file called cloudbuild-tag.yaml with the following contents</p><pre>steps:<br><br>  ### Add Tag<br>  <br>    - id: &#39;add-tag&#39;<br>      name: &#39;gcr.io/cloud-builders/gcloud&#39;<br>      entrypoint: &#39;bash&#39;<br>      args: <br>        - &#39;-c&#39;<br>        - |<br>            gcloud artifacts docker tags add ${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:${SHORT_SHA} \<br>              ${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:$TAG_NAME \<br>              --quiet<br>  <br>  <br>  <br>  ### Deploy<br>    - id: &#39;deploy&#39;<br>      name: &#39;gcr.io/cloud-builders/gcloud&#39;<br>      env:<br>        - &#39;KUBECONFIG=/kube/config&#39;<br>      entrypoint: &#39;bash&#39;<br>      args:<br>        - &#39;-c&#39;<br>        - |<br>            PROJECT=$$(gcloud config get-value core/project)          <br>  <br>            gcloud container clusters get-credentials &quot;${_CLUSTER}&quot; \<br>              --project &quot;$${PROJECT}&quot; \<br>              --zone &quot;${_ZONE}&quot;   <br>           <br>  <br>            sed -i &#39;s|gcr.io/$PROJECT_ID/$_APP_NAME:.*|${_REGION}-docker.pkg.dev/${PROJECT_ID}/quickstart-docker-repo/$_APP_NAME:$TAG_NAME|&#39; ./k8s/deployments/prod/*.yaml<br>            <br>            kubectl apply --namespace production --recursive -f k8s/deployments/prod<br>            kubectl apply --namespace production --recursive -f k8s/services<br><br></pre><p>Notice that in this configuration you’re not rebuilding the source, but reusing the previously built image.</p><p>Add the new yaml file to the repo so it’s available to the trigger</p><pre>git add . &amp;&amp; git commit -m &quot;Added Tag Trigger&quot; &amp;&amp; git push origin main</pre><p>Wait for the main build to finish</p><p><a href="https://console.cloud.google.com/cloud-build">Open the Cloud Build page</a></p><p>Create the trigger</p><pre>gcloud beta builds triggers create github \<br>    --name=&quot;tag-trigger&quot; \<br>    --repo-name=cloud-build-cicd \<br>    --repo-owner=${GIT_USER} \<br>    --tag-pattern=.* \<br>    --build-config=cloudbuild-tag.yaml \<br>    --substitutions=_APP_NAME=&quot;sample-app&quot;,_CLUSTER=&quot;mycluster&quot;,_REGION=&quot;us-west2&quot;,_ZONE=&quot;us-central1-c&quot;</pre><p>Exercise the trigger by pushing a tag to the repo</p><pre>git tag 2.0<br>git push origin 2.0</pre><p><a href="https://console.cloud.google.com/cloud-build">Open the Cloud Build page</a></p><p>Review GKE <a href="https://console.cloud.google.com/kubernetes/workload/overview">workloads</a>. Sample-app-production application was deployed to production namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-QJoRJUkvY5k6dkh" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0e05e1a157e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Bigtable on GCP]]></title>
            <link>https://medium.com/google-cloud/getting-started-with-bigtable-on-gcp-adfb896e0b26?source=rss-60e881a91384------2</link>
            <guid isPermaLink="false">https://medium.com/p/adfb896e0b26</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[nosql]]></category>
            <dc:creator><![CDATA[Christopher Grant]]></dc:creator>
            <pubDate>Sat, 11 Jul 2020 00:22:58 GMT</pubDate>
            <atom:updated>2020-07-13T21:24:25.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*NFkBGPrxSV0jM1-ga74I9g.png" /></figure><p>If you’ve never looked at it before Bigtable can seem a little unapproachable. In this tutorial we’ll get you past that and guide you through your first steps with Bigtable so you can start using this fully managed NoSQL database in your own projects.</p><p>Bigtable is designed for low latency data access, where scalability and reliability really matter. It’s actually the same technology behind the majority of Google products, including Gmail, Maps, YouTube; Each of which serves multi-billion users.</p><p>In this tutorial we’ll walk you through your first steps with Bigtable, how to use it and what you really need to know to get started including:</p><ul><li>Understanding the different types of NoSQL databases</li><li>How to setup and interact with Bigtable</li><li>How big table structures and manages data</li><li>Common ways to query and access data</li><li>Best practices around schema design</li></ul><h3>The 4 Types of NoSql Databases</h3><p>In the NoSql realm there are generally 4 types of databases. You’ve got your Column based, Document based, Key-Value based and Graph based databases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*N0TsKtWsWCFFz1I5HwBjHg.png" /></figure><p>Bigtable falls into the Wide-Column based family along with others like Cassandra, and Hbase. To understand Wide-Column it helps to look first at traditional Column based. When we say Column based Nosql, what does that actually mean? Well traditional Relational databases are row based, meaning they’re optimized for returning rows of data. Consider a User database for example, a relational database would organize first name, last name, and address all near each other.</p><p>If you wanted to access the state and zip of many users, the database would have to jump around to pull all the fields. A column based database on the other hand is optimized for accessing data by column instead of row. So in our Users database example it would store all the names together, all the states together, all the zip codes together and so on. This makes reads much more efficient. To scan all the states, the database can stay within the same area on disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8_9rwB2S9qR-BVFA" /></figure><p>A Wide-Column datastore looks similar however they often group the columns into Column Families, a set of columns that are typically used together. These Column Families are further optimized on disk to ensure fast access.</p><p>This will be good to keep in mind for later when we start designing our schemas. Alright, lets get on with it and get hands dirty</p><h3>Interacting with Bigtable</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*nj5RogAXIC9sInP5" /></figure><p>For this walkthrough I’ll be using the Bigtable command line tool, called <a href="https://cloud.google.com/bigtable/docs/cbt-overview">CBT</a>. All the concepts you see here can also be done programmatically in your language of choice by just pulling the right SDK. We’re just using the CLI for simplicity here.</p><h3>Accessing your instance with CBT</h3><p>With the Bigtable instance created and the CLI installed, this is a good point to access your instance from the CLI to ensure you’ve got everything setup.</p><p>Alright, to get started lets just list our instances</p><pre>cbt listinstances</pre><p>You should see the instance you just created in the output</p><pre>Instance Name    Info<br>— — — — — — —    — — <br>my-instance      my-instance</pre><p>And there’s the instance we created. Now if we try to list the tables with cbt ls we get an error</p><pre>cbt ls</pre><p>Error will read</p><pre>Missing -instance</pre><p>it’s telling us we need to specify the instance with a flag. We could do that, but it’s gonna get annoying adding that in every time so let’s write it to an rc file as a default</p><pre>echo instance = my-instance &gt;&gt; ~/.cbtrc</pre><p>Now when we run it, no errors, but no response either since we haven’t created any tables yet.</p><pre>cbt ls</pre><h3>Data structures &amp; schema basics</h3><h4><strong>Tables</strong></h4><p>For this example we’ll be creating a product catalog that might be used by a typical retailer. So in this step we’ll create a table called `catalog`</p><pre>cbt createtable catalog</pre><p>Calling `ls` one more time</p><pre>cbt ls</pre><p>and we see our table</p><pre>catalog</pre><h4>Column Family</h4><p>Earlier I mentioned that Bigtable stores data related to columns. To help organize the data and limit what you’re pulling back, columns are grouped into what’s called column families. These column families group the fields that are typically accessed in the same request to ensure more efficient access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2YwWHiOB94Df6uzn" /></figure><p>In our catalog example we may have product description fields and pricing or inventory fields. A listing of products may use data from the descriptors but not need all the store level inventory.</p><p>Lets go ahead and create a column family for those product descriptors</p><pre>cbt createfamily catalog descr</pre><p>And now we’ve got our column family in the table. Running the ls command again</p><pre>cbt ls catalog</pre><p>displays</p><pre>Family Name     GC Policy<br> — — — — — — —  — — — -<br>descr           &lt;never&gt;</pre><h4>Rows, Columns &amp; Cells</h4><p>Just like with relational databases we have a concept of rows columns and cells. Each row is identified by a unique key you provide. Cells are at the intersection of a row id and column id To access a specific cell you need to identify the location including Row Key, Column Family, and Column Qualifier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GkbSlSw5geCbqg_n" /></figure><p>In our case the rowID will be a unique product sku and we’ll add a title for it in the descriptors column family</p><p>The format will be</p><p><em>cbt set &lt;table&gt; &lt;rowID&gt; &lt;colFamily&gt;:&lt;colQualifier&gt;=&lt;value&gt;</em></p><pre>cbt set catalog sku123 descr:title=”Vintage Clock”</pre><p>Now if we read our catalog table</p><pre>cbt read catalog</pre><p>we’ll see the value</p><pre>sku123<br>  descr:title           @ 2020/03/19-16:08:47.765000<br>    &quot;Vintage Clock&quot;</pre><p>Notice that we didn’t explicitly create columns. With bigtable we have dynamic schemas that allow you to create columns on the fly.</p><p>Since Bigtable is what’s called a sparsely populated database, any empty fields don’t incur storage overhead, unlike relational databases.</p><h4>Cell Versions</h4><p>Big table has a concept of cell versions, allowing you to store multiple revisions of data in this same spot, indicated by time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*Za9sXGT444VjnuVI" /></figure><p>We just set the contents of the cell descr:title on row sku123 to “Vintage Clock”. Now run the command again with a different title.</p><pre>cbt set catalog sku123 descr:title=”Antique Clock”</pre><p>You may have expected a single record returned but run the command</p><pre>cbt read catalog</pre><p>you’ll see instead we have two records</p><pre>sku123<br>   descr:title   @ 2020/03/19–16:11:07.097000<br>      “Antique Clock”<br>   descr:title @ 2020/03/19–16:08:47.765000<br>      “Vintage Clock”</pre><p>You’ll see that the catalog contains 2 versions of the cell descr:title, our original one with “Vintage Clock” and the update with “Antique Clock” At first multiple rows might seem alarming but this can be really handy in your system designs and audits.</p><h4>Garbage Collection</h4><p>Given you may not want to store every version ever created, Bigtable offers the ability to trash cell versions with a feature called Garbage Collection. Earlier we listed the column families on our table and you may have noticed GC Policy set to never. Leaving this as is will collect every version of the cell ever created.</p><pre>cbt ls catalog</pre><pre>Family Name      GC Policy<br>— — — — — — —    — — — -<br>descr            &lt;never&gt;</pre><p>You can set the garbage collection policy based on the Time of the cell, Number of cells or a combination of the two. For example you could keep a month’s worth of changes, the last 5 versions or maybe up to 5 versions and within the last month.</p><p>For our example lets only keep one version</p><pre>cbt setgcpolicy catalog descr maxversions=1</pre><p>Now review the column families</p><pre>cbt ls catalog</pre><p>Notice the new policy listed</p><pre>Family Name     GC Policy</pre><pre>-----------     ---------</pre><pre>descr           versions() &gt; 1</pre><p>But when we read the table with no flags it still returns 2 cells, why is that?</p><pre>cbt read catalog</pre><pre>sku123<br>   descr:title @ 2020/03/19–16:11:07.097000<br>      “Antique Clock”<br>   descr:title @ 2020/03/19–16:08:47.765000<br>      “Vintage Clock”</pre><p>Garbage collection is a data storage technique, not for limiting querying results. In fact, it can take up to a week before data that is eligible for garbage collection is actually removed.</p><p>In practice you won’t be pulling back all revisions of a cell anyway. Instead you’ll be doing something like the following which pulls the latest cell entry</p><pre>cbt read catalog cells-per-column=1</pre><pre>sku123<br>   descr:title @ 2020/03/19–16:11:07.097000<br>      “Antique Clock”</pre><h4>Querying and accessing Data</h4><p>Bigtable has some fantastic lookup capabilities. To demonstrate them, lets first add some more data</p><pre>cbt set catalog sku124 descr:title=”Vintage Record Player”<br>cbt set catalog sku125 descr:title=”Antique Chair”<br>cbt set catalog sku942 descr:title=”New Wireless Headphones”<br>cbt set catalog svc024 descr:title=”Antique Repair Service”</pre><p>Let’s see what we have now.</p><p>We’ve added 3 more skus some sequential and one in the 900s. We’ve also added the last entry as a service rather than a product.</p><pre>cbt read</pre><h4>Retrieve Single Entry</h4><p>Previously we’ve been calling `cbt read` which returns a set of rows. Calling it now will return all the records we have in the system. If you know which row you’re interested specifically you can access it directly with `lookup`</p><pre>cbt lookup catalog sku123</pre><p>Additionally you can get even more specific indicating the exact columns you want</p><pre>cbt lookup catalog sku123 columns=descr:title</pre><h4>Reading All Rows</h4><p>Now let’s look at the <a href="https://cloud.google.com/bigtable/docs/cbt-reference#read_rows">readrows</a> command to understand some of the ways we can query the data.</p><p>We covered this previously but as a foundation calling `cbt read` with no additional qualifiers will return all the values</p><pre>cbt read catalog</pre><p>Clearly something we wouldn’t want in a normal system. Thankfully Bigtable provides a few ways to get only the data we’re interested in.</p><h4>Start &amp; End</h4><p>First it’s important to understand that Bigtable stores all its rows in ascending order based on the row id. Many of the features and patterns in bigtable revolve around this core concept. To see it in practice, the simplest way is to use `start` and `end` on the read command. Here we’re saying we want to start reading at sku124 and return all the rest of the rows.</p><pre>cbt read catalog start=sku124</pre><p>Or, read all the rows up to but excluding sku942</p><pre>cbt read catalog end=sku942</pre><p>You can combine them of course to get more targeted</p><pre>cbt read catalog start=sku124 end=sku942</pre><p>The values don’t need to be exact either, you can provide portions of the IDs</p><pre>cbt read catalog start=sku12 end=sku9</pre><p>This works because it’s comparing the lexical value of sku12 against the row ids in the database. Since sku12 comes before sku123 it will include 123. Since sku9 comes before sku942, it will exclude 942</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*vDhu4dLbH7EViPrs" /></figure><p>That’s pretty cool, but there’s more</p><h4>Prefix</h4><p>You can use the prefix flag to pull only a subset of rows. In our dataset we have entries starting with sku and svc. let’s pull them separately. First the product `sku` records</p><pre>cbt read catalog prefix=sku</pre><p>Now the service `svc` records</p><pre>cbt read catalog prefix=svc</pre><h4>Regex</h4><p>Of course if you want to get fancy you can use standard regex. Pull any row starting with `s` then 3 of any characters followed by `24`</p><pre>cbt read catalog regex=s.{3}24</pre><h4>Count</h4><p>Finally we have count. It’s pretty self explanatory, cont returns only X number of rows that you indicate. This comes in handy when dealing with time series data and other scenarios.</p><pre>cbt read catalog count=3</pre><h3>Schema Design</h3><h4><strong>Tall Narrow Tables</strong></h4><p>Now that you’ve worked with Bigtable it’s a good time to discuss the schema design. Typically with Bigtable data sets you’ll want to focus on tall narrow tables vs short wide tables.</p><p>Continuing with our retail theme, let’s assume we’re tracking shipments to our customers</p><p>If you were interested in tracking the location of the shipment over time you might be interested in some elements such as:</p><ul><li>OrderID</li><li>Shipping Company</li><li>Vehicle ID</li><li>Region</li><li>GPS Location</li><li>Timestamp</li></ul><p>A short wide table might have rows for each shipping company, then columns for each vehicle ID and vehicle location. This would result in fewer rows but more columns</p><p>Instead it’s better to store this data in tall narrow tables. For example you would have a row for each time a vehicle reports data. This would result in many rows and fewer columns.</p><h4>Avoid Hot Spots</h4><p>A common challenge while dealing with time series data is a concept called hotspotting. When there are a bunch of writes for row keys right next to each other (like with time series data) you can create hot spots in your clusters that slow things down. When a row key for a time series includes a timestamp, all of your writes will target a single node, fill that node, and then move onto the next node. Ideally the writes would spread across all the nodes evenly.</p><p>To combat this you’ll want to create row keys that are non-contiguous.</p><p>For our shipping data if we simply stored data with a row starting with `timestamp` all the records would be contiguous. Instead we use a tactic of field promotion to move the fields from columns into the actual row key. A better row key might be `vehicle_id_#timestamp`. Since many vehicles will be reporting in a short time span, prefacing with the unique vehicle id will help spread the data out over the cluster.</p><h4>Row Keys optimized for queries</h4><p>The common way to sort and filter data in Bigtable is through the row key so it’s important to consider your queries when designing row keys. With the shipping data you might be more concerned with querying on the shipping company and therefore would need to include `shipping_co` in your row key. `shipping_co#vehicle_id_#timestamp`</p><p>You could then query bus line `UPS` with the prefix query `cbt read catalog prefix=UPS`</p><p>Depending on the various queries you need, you might find many fields promoted to the row key. With our bus data you might see a row key with most of the fields such as `region#shipping_co#timestamp#vehicle_id`</p><h3>Cleanup</h3><p>OK that’s it for this session. Let’s delete our instance and clean things up.</p><p>Delete the table instance &amp; .cbtrc file</p><pre>cbt deletetable catalog<br>cbt deleteinstance my-instance<br>rm ~/.cbtrc</pre><p>So there you have it, a whirlwind tour of bigtable. I hope this gave you a little insight on how bigtable works and how you might use it in your next project. You can find more about it on <a href="https://cloud.google.com/bigtable">cloud.google.com/bigtable</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adfb896e0b26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/getting-started-with-bigtable-on-gcp-adfb896e0b26">Getting Started with Bigtable on GCP</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DIY Pool Chiller]]></title>
            <link>https://cgrant.medium.com/diy-pool-chiller-964fee9eac07?source=rss-60e881a91384------2</link>
            <guid isPermaLink="false">https://medium.com/p/964fee9eac07</guid>
            <category><![CDATA[3d-printing]]></category>
            <category><![CDATA[make]]></category>
            <dc:creator><![CDATA[Christopher Grant]]></dc:creator>
            <pubDate>Mon, 08 Jul 2019 02:00:58 GMT</pubDate>
            <atom:updated>2019-07-08T02:02:45.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hot as Bathwater</h3><p>When we first got our pool years ago I was considering installing a heater so we could enjoy swimming a bit longer. What no one told me was that here in Texas you really should consider a pool chiller. Come July and August the pool temperature rises into the 90s. It can get so hot it’s not refreshing at all.</p><p>This weekend my pool registered 95 degrees and we’re just getting into July. I decided to do something about it.</p><h3>The Fix</h3><p>The plan was to use the water jets in the pool to drive a fountain sprayer made from PVC pipe to cool the water.</p><p>The jets have a moveable nozzle to direct the flow of water.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nDpa3-X1qpTZ-r-Z.png" /></figure><p>After removing the nozzle I was able to measure the opening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S7jfMDGx2GJp2uYh.png" /></figure><p>Unfortunately, the opening was way too large for the ¾ inch PVC pipe so I needed an adapter. A few minutes in <a href="https://www.autodesk.com/products/fusion-360/overview">Fusion 360</a> and I was able to sketch out a part for the job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t4AraUBPcCLkohiV.png" /></figure><p>The adapter had an opening for the PVC pipe and a flare at the base to keep it from slipping out of the pool jet. If you’re interested, you can <a href="http://cgrant.io/tutorials/make/diy_pool_chiller/PoolVent-PVC-Adapter-34.stl">download the stl file here</a>.</p><p>Over to <a href="https://ultimaker.com/software/ultimaker-cura">Cura</a> to slice it up then over to my 3d printer to make it real. A half hour later the part was ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y5Zv4vyQ3-yxCcek.png" /></figure><p>It was a surprisingly perfect fit for the jet cap</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xUf27R-JhzjDROwQ.png" /></figure><p>The PVC pipe was a snug fit just enough to not need glue but still loose enough to remove when not needed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h0hAe5VAEAVQDl83.png" /></figure><p>Next, cut a length of pipe, cap it off and drill some holes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*ear_-prOSs5j0zOb.png" /></figure><h3>Some Assembly Required</h3><p>Install it and start the cooling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*5-sOlNsRfpvJAFa9.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*XWD-bkSuWnipB7O8.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*lP8wwUlacrleNzBQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=964fee9eac07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Container Deploys on Google Cloud Platform]]></title>
            <link>https://cgrant.medium.com/simple-container-deploys-on-google-cloud-platform-39cc46333508?source=rss-60e881a91384------2</link>
            <guid isPermaLink="false">https://medium.com/p/39cc46333508</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[google-compute-engine]]></category>
            <category><![CDATA[app-engagement]]></category>
            <category><![CDATA[gke]]></category>
            <dc:creator><![CDATA[Christopher Grant]]></dc:creator>
            <pubDate>Tue, 02 Jul 2019 23:35:16 GMT</pubDate>
            <atom:updated>2019-07-02T23:35:16.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y9MYsezjcqpA1iTj.png" /></figure><p>In the following demo we will walk through deploying the same sample container to the various Google Cloud compute platforms including Google Compute Engine, Google App Engine, Cloud Run, and Google Kubernetes Engine, with just a few commands.</p><p>Google has been working with containers internally since 2003. In 2006 they introduced cgroups to the linux kernel. Kubernetes and GKE are introduced to the world in 2014. Today Google deploys 4 billion containers every week. Containers are in Google’s DNA. Users of the Google Cloud Platform get access to this as well across GCP’s computing ecosystem.</p><p>Let’s jump in and do some deploys</p><h3>Before you begin</h3><h4>First time GCP setup</h4><p>If this is your first time using GCP you’ll need to get things setup before you jump into the demo. Setup a GCP Project Create a GCP project Download, install, and initialize the Cloud SDK. Acquire local credentials for authenticating with GCP services.</p><pre>gcloud auth application-default login</pre><p>Verify that your default project is correct.</p><pre>gcloud config list</pre><p>If the project ID listed in the output isn’t the project that you intended to use for this tutorial, set the project.</p><pre>gcloud config set project [YOUR_PROJECT_ID]</pre><p>where [YOUR_PROJECT_ID] is the ID of the project that you created or chose to use for this tutorial.</p><h4>Prepare the Demo</h4><p>Configure some defaults</p><pre>gcloud config set compute/zone us-central1-a<br>gcloud config set run/region us-central1</pre><p>Clone the sample repository.</p><pre>git clone https://github.com/cgrant/hello-python-container.git<br>cd hello-python-container</pre><p>Alternatively, you can download the sample as a zip file and extract it.</p><p>Build the sample app and push the container to the registry</p><pre>export PROJECT=$(gcloud config get-value project)<br>gcloud builds submit --tag gcr.io/${PROJECT}/hellopython</pre><h3>Containers on Compute Engine</h3><p>If you have any experience with Virtual Machines or Cloud IaaS this may seem obvious that you can install docker and run containers.</p><p>However it’s even easier than that on GCP. <a href="https://cloud.google.com/compute/">Google Compute Engine</a> allows you to deploy an image directly to a traditional VM with a single command.</p><p>Deploy a container to GCE in one command</p><pre>gcloud compute instances create-with-container hellopython \<br>     --container-image gcr.io/${PROJECT}/hellopython</pre><h3>Containers on GKE</h3><p>Google’s flagship managed kubernetes service <a href="https://cloud.google.com/kubernetes-engine/">GKE</a> has been around for nearly 4 years and of course can run containers simply and easily.</p><p>Create your cluster in less than 5 minutes with a simple command</p><pre>gcloud container clusters create mycluster</pre><p>Then deploy your container again with one command</p><pre>kubectl run hellopython --image gcr.io/${PROJECT}/hellopython</pre><h3>Containers on AppEngine</h3><p>The <a href="https://cloud.google.com/appengine/docs/flexible/">AppEngine Flex </a>runtime supports custom runtimes through the use of containers. Typically you would provide source code and a Dockerfile which would be built into an image for you and subsequently deployed.</p><p>However you may not know you can deploy images directly with app engine</p><p>We do need a very simple app.yaml</p><pre>cat &lt;&lt;EOF &gt;&gt; app.yaml<br>runtime: custom<br>env: flex<br>EOF</pre><p>Now deploy an image in one command</p><pre>gcloud app deploy \<br>    --image-url gcr.io/${PROJECT}/hellopython</pre><h3>Containers on Cloud Run</h3><p><a href="https://cloud.google.com/run/">Cloud Run</a> is a managed compute platform that enables you to run stateless containers invocable via HTTP requests. Cloud Run is serverless: it abstracts away all infrastructure management, so you can focus on what matters most — building great applications.</p><p>You have to try this demo for yourself it’s fantastic</p><p>Deploy your app to Cloud Run in one command</p><pre>gcloud beta run deploy hellopython \<br>    --image gcr.io/${PROJECT}/hellopython \<br>    --allow-unauthenticated</pre><p>In just a moment your service is up and running with a secured https endpoint.</p><p>Super fast super simple</p><h3>Summary</h3><p>Containers are becoming a staple of modern systems and migrating to containers is often a great choice. Taking advantage of the many runtime options available, you can deploy your containers to meet the unique workload needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39cc46333508" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Clusters with Cluster Registry]]></title>
            <link>https://cgrant.medium.com/managing-clusters-with-cluster-registry-aefb1205fe47?source=rss-60e881a91384------2</link>
            <guid isPermaLink="false">https://medium.com/p/aefb1205fe47</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[multi-cluster]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Christopher Grant]]></dc:creator>
            <pubDate>Wed, 06 Feb 2019 00:45:26 GMT</pubDate>
            <atom:updated>2019-02-06T00:46:03.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqjalbIW-vjqiqsx4yMReg.png" /></figure><h3>Managing Clusters w/ Cluster Registry</h3><p>The <a href="https://github.com/kubernetes/cluster-registry">Cluster Registry</a> is part of the kubernetes foundation but is not included in the distribution by default. It’s added through a simple kubectl apply command. The cluster registry provides a simple yet powerful feature in that it enables a new resource type of Cluster to be added to your api calls. This means you can make a request for kubectl get clusters to retrieve a list of cluster matching specific queries. Since these are presented as standard Kubernetes API requests and resources, you can combine them with other commands to more dynamically manage your ecosystem.</p><p>In this example we’ll install the registry, load some metadata then use the registry to act on multiple clusters.</p><p>While you can accomplish this on your laptop, I’ll be demonstrating through <a href="https://cloud.google.com/shell/">Google Cloud Shell</a>, which already includes many of the tools we’ll be using, as well as a standard environment we can all work from.</p><p>If you’re new to GCP, Google offers a free $300 credit as well as a generous <a href="https://cloud.google.com/free/">Free Tier</a> to get you started. So <a href="http://console.cloud.google.com/">create your project</a> and lets get started</p><h3>Set Variables</h3><p>To get started let’s create some variables and grab kubectx to manage our contexts easier</p><pre>export PROJECT=$(gcloud config get-value project)<br>gcloud config set project $PROJECT</pre><pre>export PROJECT_DIR=$HOME/clsRegistry<br>mkdir -p $PROJECT_DIR/bin<br>PATH=$PROJECT_DIR/bin/:$PATH</pre><h3>Get tooling</h3><p><a href="https://github.com/ahmetb/kubectx">Kubectx</a> is a fantastic tool that simplifies managing and switching cluster contexts.</p><pre>curl -LO <a href="https://raw.githubusercontent.com/ahmetb/kubectx/master/kubectx">https://raw.githubusercontent.com/ahmetb/kubectx/master/kubectx</a> &amp;&amp; \<br>chmod +x kubectx &amp;&amp; \<br>mv kubectx $PROJECT_DIR/bin/.</pre><h3>Create your control cluster</h3><p>For this example we’ll use a centralized control cluster to act as our administrative system. Since we’re just doing a small example we’ll also set the number of nodes to 1</p><pre>gcloud container clusters create central --zone us-central1-a --num-nodes=1<br>kubectx central=gke_${PROJECT}_us-central1-a_central</pre><h3>Install the cluster registry CRD</h3><p>Once the control cluster is up and running, it’s time to create the Cluster Registry resource definition.</p><pre>kubectl apply -f <a href="https://raw.githubusercontent.com/kubernetes/cluster-registry/master/cluster-registry-crd.yaml">https://raw.githubusercontent.com/kubernetes/cluster-registry/master/cluster-registry-crd.yaml</a></pre><h3>Generate Yaml Files describing your clusters</h3><p>In general it’s good practice to store your desired state in a source repository. We’ll create yaml files describing our clusters. While we’re not doing it here, you could actually use these definitions as the specs for creating the clusters themselves.</p><p>Create 3 files, one for each cluster. In these examples I’ve included labels for lifecycle as well as the zone in a custom data structure. You can add any data needed for your use case.</p><pre>cat &lt;&lt;EOF &gt;&gt;$PROJECT_DIR/central.yaml<br>kind: Cluster<br>apiVersion: <a href="http://clusterregistry.k8s.io/v1alpha1">clusterregistry.k8s.io/v1alpha1</a><br>metadata:<br>  name: central<br>  namespace: default<br>  labels:<br>    lifecycle: &quot;control&quot;<br>spec:<br>  kubernetesApiEndpoints:<br>    serverEndpoints:<br>      - clientCIDR: &quot;0.0.0.0/0&quot;<br>        serverAddress: &quot;100.0.0.0&quot;<br>  myCustomData:<br>    zone: &quot;us-central1-a&quot;<br>status: {}<br>EOF</pre><pre>cat &lt;&lt;EOF &gt;&gt;$PROJECT_DIR/east.yaml<br>kind: Cluster<br>apiVersion: <a href="http://clusterregistry.k8s.io/v1alpha1">clusterregistry.k8s.io/v1alpha1</a><br>metadata:<br>  name: east<br>  namespace: default<br>  labels:<br>    lifecycle: &quot;prod&quot;<br>spec:<br>  kubernetesApiEndpoints:<br>    serverEndpoints:<br>      - clientCIDR: &quot;0.0.0.0/0&quot;<br>        serverAddress: &quot;100.0.0.0&quot;<br>  myCustomData:<br>    zone: &quot;us-east1-b&quot;<br>status: {}<br>EOF<br></pre><pre>cat &lt;&lt;EOF &gt;&gt;$PROJECT_DIR/west.yaml<br>kind: Cluster<br>apiVersion: <a href="http://clusterregistry.k8s.io/v1alpha1">clusterregistry.k8s.io/v1alpha1</a><br>metadata:<br>  name: west<br>  namespace: default<br>  labels:<br>    lifecycle: &quot;prod&quot;<br>spec:<br>  kubernetesApiEndpoints:<br>    serverEndpoints:<br>      - clientCIDR: &quot;0.0.0.0/0&quot;<br>        serverAddress: &quot;100.0.0.0&quot;<br>  myCustomData:<br>    zone: &quot;us-west1-b&quot;<br>status: {}<br>EOF</pre><pre>kubectl apply -f $PROJECT_DIR/central.yaml --context central</pre><h3>Create your remote cluster</h3><p>OK lets spin up our clusters and load the registry. I’m also renaming the default context name here for easy use later on.</p><pre>gcloud container clusters create west --zone us-west1-b --num-nodes=1<br>kubectx west=gke_${PROJECT}_us-west1-b_west<br>kubectl apply -f $PROJECT_DIR/west.yaml --context central</pre><pre>gcloud container clusters create east --zone us-east1-b --num-nodes=1<br>kubectx east=gke_${PROJECT}_us-east1-b_east<br>kubectl apply -f $PROJECT_DIR/east.yaml --context central</pre><h3>Deploy to all Prod clusters</h3><p>In this section we’ll use the data in the registry along with a simple for loop to deploy an nginx image to all production clusters. We’re going to loop over the result of kubectl get clusters -l lifecycle=prodwhich selects resources labeled lifecycle=prod. Additionally we’re requesting the output to be a specific value in the json path located at .items[*].metadata.name</p><pre>kubectx central</pre><pre>for cluster in $( kubectl get clusters -l lifecycle=prod -o jsonpath=&#39;{.items[*].metadata.name}&#39; ); do</pre><pre>    kubectl run --image nginx myapp --context ${cluster}</pre><pre>done</pre><h3>List all deployments on all clusters</h3><p>Now let’s run a simpler command to list all the deployments from all the clusters. You’ll note myapp deployed to east and west with nothing on central</p><pre>for cluster in $( kubectl get clusters -o jsonpath=&#39;{.items[*].metadata.name}&#39; ); do<br>    kubectx $cluster<br>    kubectl get deploy <br>    echo <br>done</pre><h3>Recap</h3><p>So that about wraps it up. There’s really not much to setting up cluster registry but it provides a solid base for dynamically managing your fleet of kubernetes clusters.</p><h3>Cleanup</h3><p>Be sure to tear down your cluster to avoid additional costs</p><pre>delete_cluster() {<br> <br>        CLUSTER_NAME=$1<br>        CLUSTER_ZONE=$2</pre><pre>        # Delete the clusters <br>        gcloud container clusters delete ${CLUSTER_NAME} \<br>        --zone=${CLUSTER_ZONE} \<br>        -q --async</pre><pre>        # Delete <br>        kubectx -d ${CLUSTER_NAME}<br>}<br></pre><pre>delete_cluster central us-central1-a<br>delete_cluster west us-west1-b<br>delete_cluster east us-east1-b</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aefb1205fe47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multicluster Istio on GKE]]></title>
            <link>https://cgrant.medium.com/multicluster-istio-on-gke-b2d875a3712b?source=rss-60e881a91384------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2d875a3712b</guid>
            <category><![CDATA[istio]]></category>
            <category><![CDATA[multi-cluster]]></category>
            <category><![CDATA[istio-service-tutorial]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Christopher Grant]]></dc:creator>
            <pubDate>Wed, 06 Feb 2019 00:39:54 GMT</pubDate>
            <atom:updated>2019-02-06T00:39:54.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QT0hWJHupCVUl7o3_F221g.png" /></figure><h3>Overview</h3><p>In this example we’ll create a single Istio mesh across multiple regionally separated GKE clusters. Once setup, we’ll demonstrate the installation using <a href="https://istio.io/docs/examples/bookinfo/">Istio’s BookInfo</a> application.</p><p>While you can accomplish this on your laptop, I’ll be demonstrating through <a href="https://cloud.google.com/shell/">Google Cloud Shell</a>, which already includes many of the tools we’ll be using, as well as a standard environment we can all work from.</p><p>If you’re new to GCP, Google offers a free $300 credit as well as a generous <a href="https://cloud.google.com/free/">Free Tier</a> to get you started. So <a href="http://console.cloud.google.com/">create your project</a> and lets get started</p><h3>Environment Variables</h3><p>First things first, lets ensure we’ve set some key variables in our environment</p><pre>export PROJECT=$(gcloud config get-value project)<br>gcloud config set project $PROJECT</pre><h3>Get the Installs</h3><p>Next let’s pull down some of the tools we’ll be using throughout the process. Obviously we’ll need <a href="https://istio.io/">Istio</a>, but we’ll also pull down <a href="https://helm.sh/">Helm</a> to help with the install. Since we’re going to be working in multiple clusters we can use a tool called <a href="https://github.com/ahmetb/kubectx">kubectx</a>to make working with the contexts easier.</p><pre># Add a common bin to your path<br>export WORK_DIR=$HOME/mcIstio</pre><pre>mkdir -p $WORK_DIR/bin<br>PATH=$WORK_DIR/bin/:$PATH</pre><pre># Install Helm<br>curl <a href="https://raw.githubusercontent.com/kubernetes/helm/master/scripts/get">https://raw.githubusercontent.com/kubernetes/helm/master/scripts/get</a> &gt; get_helm.sh<br>chmod 700 get_helm.sh<br>./get_helm.sh &amp;&gt; /dev/null<br>cp /usr/local/bin/helm $WORK_DIR/bin/<br>rm ./get_helm.sh</pre><pre># Download Istio<br>export ISTIO_VERSION=1.0.2<br>curl -L <a href="https://git.io/getLatestIstio">https://git.io/getLatestIstio</a> | ISTIO_VERSION=$ISTIO_VERSION sh -<br>cp istio-$ISTIO_VERSION/bin/istioctl $WORK_DIR/bin/.<br>mv istio-$ISTIO_VERSION $WORK_DIR/istio</pre><pre>## Install kubectx<br>curl -LO <a href="https://raw.githubusercontent.com/ahmetb/kubectx/master/kubectx">https://raw.githubusercontent.com/ahmetb/kubectx/master/kubectx</a> <br>chmod +x kubectx <br>mv kubectx $WORK_DIR/bin/.</pre><h3>Provision the GKE Clusters</h3><p>Since we’ll be creating multiple clusters, we’ll simplify the setup by wrapping the command in a function, then call it with the name and location of the cluster we want to provision.</p><p>The provision cluster function will do a few things. Of course it will provision the GKE cluster in your project, but it will also setup the initial RBAC bindings, pull down the context credentials and rename the context for easier use.</p><p>The cluster create command includes a couple key things. We’re specifying num-nodes of 4 to ensure the control cluster has the initial capacity it needs. While the workers won’t need this, it’s simpler to apply the same to all clusters.</p><p>We’ve also added <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/alias-ips">enable-ip-alias</a>. This is an important flag for this demo. It essentially tells GKE to give each Pod it’s own routable IP. This will be important as we begin to make calls from one cluster to another with our service mesh.</p><p>While we’re talking about routing, it’s worthwhile noting a bit about the network structure here. You can customize the networking but we’ll be using the default network in this example. The GCP networks are global, however regions have different subnets and IP ranges within the default network. Also Since we’re using IP Aliasing we can be sure the pods from one cluster won’t be in the same IP range as a Pod from another cluster.</p><p>OK enough talk let’s get this spun up</p><pre>provision_cluster() {<br> <br>        CLUSTER_NAME=$1<br>        CLUSTER_ZONE=$2<br></pre><pre>        gcloud container clusters create ${CLUSTER_NAME} \<br>        --cluster-version=latest \<br>        --zone=${CLUSTER_ZONE} \<br>        --num-nodes &quot;4&quot; \<br>        --enable-ip-alias \<br>        --scopes cloud-platform,logging-write,monitoring-write,pubsub,trace \<br>        --enable-cloud-logging \<br>        --enable-cloud-monitoring<br>        <br>        gcloud container clusters get-credentials ${CLUSTER_NAME} \<br>        --zone ${CLUSTER_ZONE}</pre><pre>        kubectx ${CLUSTER_NAME}=gke_${PROJECT}_${CLUSTER_ZONE}_${CLUSTER_NAME}</pre><pre>        kubectx ${CLUSTER_NAME}</pre><pre>        kubectl create clusterrolebinding cluster-admin-binding \<br>        --clusterrole=cluster-admin \<br>        --user=$(gcloud config get-value core/account)<br>    <br>}<br></pre><pre>provision_cluster central us-central1-a<br>provision_cluster west us-west1-b<br>provision_cluster east us-east1-b</pre><h3>Create the firewall</h3><p>I noted in the previous section that the Pods will have their own routable IP addresses which will allow direct access from within the network. However we still need to configure a firewall to allow traffic between the clusters.</p><p>While it would be easy to just allow all traffic, we’ll want to be a bit more specific by identifying the source ranges of our cluster and pod IPs as well as providing specific target tags. To do this, we’ll pull those values and join them within their own variables before passing them into the firewall create command</p><pre># Simple Join Function<br>function join_by { local IFS=&quot;$1&quot;; shift; echo &quot;$*&quot;; }</pre><pre># Grab Cluster IP ranges<br>ALL_CLUSTER_CIDRS=$(gcloud container clusters list \<br>   --format=&#39;value(clusterIpv4Cidr)&#39; | sort | uniq)<br>ALL_CLUSTER_CIDRS=$(join_by , $(echo &quot;${ALL_CLUSTER_CIDRS}&quot;))</pre><pre># Grab all tags<br>ALL_CLUSTER_NETTAGS=$(gcloud compute instances list \<br>   --format=&#39;value(tags.items.[0])&#39; | sort | uniq)<br>ALL_CLUSTER_NETTAGS=$(join_by , $(echo &quot;${ALL_CLUSTER_NETTAGS}&quot;))</pre><pre># Create the firewall<br>gcloud compute firewall-rules create istio-multicluster-pod-fw \<br>  --allow=tcp,udp,icmp,esp,ah,sctp \<br>  --direction=INGRESS \<br>  --priority=900 \<br>  --quiet \<br>  --source-ranges=&quot;${ALL_CLUSTER_CIDRS}&quot; \<br>  --target-tags=&quot;${ALL_CLUSTER_NETTAGS}&quot;</pre><h3>Install Istio on Control Cluster</h3><p>Awesome, we’ve got the clusters up and running and ready to talk to each other. It’s time to focus on Istio.</p><p>For the multicluster Istio example there are two types of installs we will be performing, a standard Istio install for the control and a light weight install for the other clusters. The initial install here is the standard istio install, but it will act as our control plane in the final configuration.</p><pre># Ensure you’re on central<br>kubectx central<br></pre><pre># Install Helm on control plane<br>kubectl apply -f $WORK_DIR/istio/install/kubernetes/helm/helm-service-account.yaml<br>helm init --wait --service-account tiller<br></pre><pre>kubectl create ns istio-system<br>helm install $WORK_DIR/istio/install/kubernetes/helm/istio \<br>   --name istio \<br>   --namespace istio-system </pre><pre>kubectl label namespace default istio-injection=enabled</pre><h3>Install Istio on Remote Clusters</h3><p>Now let’s focus on the other remote clusters. While there seems to be a lot of code here really we’re only doing 3 things.</p><p><strong>Control Config Details</strong></p><p>We’re generating a config listing all the IP addresses for the control cluster components. This will be provided to the remote clusters so they know how to communicate with the central control plane.</p><p><strong>Install Istio Remote</strong></p><p>Next we’ll install Istio on the remote clusters. This is a scaled back version only containing Citadel for security and the Sidecar injector. These components use the values for the control plane provided in the earlier step.</p><p><strong>CA Data</strong></p><p>To enable secure communications between the clusters we need to share the certificate details with the control cluster. To do this we’ll first pull the remote cluster cert details, then switch to the control cluster and store that value as a secret.</p><p>Again since we’re doing the same thing for multiple clusters I’ve wrapped this into a function so we don’t have to repeat it over and over.</p><pre>#switch to control<br>kubectx  ${CONTROL_CLUSTER_NAME}</pre><pre># Get the control plane values<br>export PILOT_POD_IP=$(kubectl -n istio-system get pod -l istio=pilot -o jsonpath=&#39;{.items[0].status.podIP}&#39;)<br>export POLICY_POD_IP=$(kubectl -n istio-system get pod -l istio-mixer-type=policy -o jsonpath=&#39;{.items[0].status.podIP}&#39;)<br>export STATSD_POD_IP=$(kubectl -n istio-system get pod -l istio=statsd-prom-bridge -o jsonpath=&#39;{.items[0].status.podIP}&#39;)<br>export TELEMETRY_POD_IP=$(kubectl -n istio-system get pod -l istio-mixer-type=telemetry -o jsonpath=&#39;{.items[0].status.podIP}&#39;)<br>export ZIPKIN_POD_IP=$(kubectl -n istio-system get pod -l app=jaeger -o jsonpath=&#39;{range .items[*]}{.status.podIP}{end}&#39;)</pre><pre># Generate template pointing to control<br>helm template ${WORK_DIR}/istio/install/kubernetes/helm/istio-remote \<br>--namespace istio-system \<br>--name istio-remote \<br>--set global.remotePilotAddress=${PILOT_POD_IP} \<br>--set global.remotePolicyAddress=${POLICY_POD_IP} \<br>--set global.remoteTelemetryAddress=${TELEMETRY_POD_IP} \<br>--set global.proxy.envoyStatsd.enabled=true \<br>--set global.proxy.envoyStatsd.host=${STATSD_POD_IP} \<br>--set global.remoteZipkinAddress=${ZIPKIN_POD_IP} &gt; ${WORK_DIR}/istio-remote.yaml</pre><pre># Configure Remote Clusters<br>create_remote_cluster() {</pre><pre>        CLUSTER_NAME=$1</pre><pre>        kubectx  ${CLUSTER_NAME}</pre><pre>        # Install Istio Remote<br>        kubectl create ns istio-system<br>        kubectl apply -f ${WORK_DIR}/istio-remote.yaml<br>        kubectl label namespace default istio-injection=enabled<br>        </pre><pre>        # Get Cert details from Remote<br>        export KUBECFG_FILE=&quot;${WORK_DIR}/${CLUSTER_NAME}_secrets-file&quot;<br>        export SERVER=$(kubectl config view --minify=true -o &quot;jsonpath={.clusters[].cluster.server}&quot;)<br>        export NAMESPACE=istio-system<br>        export SERVICE_ACCOUNT=istio-multi<br>        export SECRET_NAME=$(kubectl get sa ${SERVICE_ACCOUNT} \<br>            -n ${NAMESPACE} -o jsonpath=&#39;{.secrets[].name}&#39;)<br>        export CA_DATA=$(kubectl get secret ${SECRET_NAME} \<br>            -n ${NAMESPACE} -o &quot;jsonpath={.data[&#39;ca\.crt&#39;]}&quot;)<br>        export TOKEN=$(kubectl get secret ${SECRET_NAME} \<br>            -n ${NAMESPACE} -o &quot;jsonpath={.data[&#39;token&#39;]}&quot; | base64 --decode)</pre><pre># create a Secrets file with the value we just pulled<br>cat &lt;&lt;EOF &gt; ${KUBECFG_FILE}<br>apiVersion: v1<br>clusters:<br>   - cluster:<br>       certificate-authority-data: ${CA_DATA}<br>       server: ${SERVER}<br>     name: ${CLUSTER_NAME}<br>contexts:<br>   - context:<br>       cluster: ${CLUSTER_NAME}<br>       user: ${CLUSTER_NAME}<br>     name: ${CLUSTER_NAME}<br>current-context: ${CLUSTER_NAME}<br>kind: Config<br>preferences: {}<br>users:<br>   - name: ${CLUSTER_NAME}<br>     user:<br>       token: ${TOKEN}<br>EOF</pre><pre>        # Store Remote Cert data on Control cluster<br>        kubectx  central</pre><pre>        kubectl create secret generic ${CLUSTER_NAME} \<br>            --from-file ${KUBECFG_FILE} -n ${NAMESPACE}<br>        kubectl label secret ${CLUSTER_NAME} istio/multiCluster=true \<br>            -n ${NAMESPACE} --overwrite=true<br>    <br>}<br></pre><pre>create_remote_cluster west<br>create_remote_cluster east</pre><h3>Deploy Apps</h3><p>Fantastic, you’ve got all the hard work done, now it’s time to play!</p><pre>cd $WORK_DIR<br>git clone <a href="https://github.com/cgrant/mcIstio-bookinfo">https://github.com/cgrant/mcIstio-bookinfo</a> bookinfo<br>cd bookinfo</pre><p><strong>Single Cluster Deploy</strong></p><p>Lets just deploy this all to the central cluster first to ensure the system is all set up</p><p>Deploy the Book Info App</p><pre>kubectx central</pre><pre>kubectl apply -f ./istio-manifests<br>kubectl apply -R -f ./kubernetes</pre><p>Wait for all services to come up then hit ctrl+c to escape back to the prompt</p><pre>watch istioctl proxy-status # ctrl+c to exit</pre><p>Review the app through the browser. Open the resulting URL in your browser window</p><pre># get the ingress endpoint<br>export INGRESS_HOST=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath=&#39;{.status.loadBalancer.ingress[0].ip}&#39;)</pre><pre># Open the web app<br>echo <a href="http://$ingress_host/productpage">http://$INGRESS_HOST/productpage</a></pre><p><strong>Deploy on multiple clusters</strong></p><p>Now that we’ve got it all running in central lets delete some pieces and move them to the other clusters</p><pre># Review whats currently running<br>kubectl get deployments  </pre><pre># Delete details and reviews-v3<br>kubectl delete deployments details-v1<br>kubectl delete deployments reviews-v3</pre><p>Verify details and reviews-v3 are no longer active</p><pre>watch istioctl proxy-status # ctrl+c to exit<br>echo <a href="http://$ingress_host/productpage">http://$INGRESS_HOST/productpage</a></pre><p>Deploy on East and West</p><pre>kubectx east<br>kubectl apply -f ./kubernetes/services<br>kubectl apply -f ./kubernetes/deployments/details-v1.yaml</pre><pre>kubectx west<br>kubectl apply -f ./kubernetes/services<br>kubectl apply -f ./kubernetes/deployments/reviews-v3.yaml</pre><p>Switch back to central and watch everything come up</p><pre>kubectx central<br>watch istioctl proxy-status<br>echo <a href="http://$ingress_host/productpage">http://$INGRESS_HOST/productpage</a></pre><p>Voila! You are a multicluster Master!!!!</p><h3>Clean Up</h3><p>Be sure to tear down your cluster to avoid additional costs</p><pre>delete_cluster() {<br> <br>        CLUSTER_NAME=$1<br>        CLUSTER_ZONE=$2</pre><pre>        # Delete the clusters <br>        gcloud container clusters delete ${CLUSTER_NAME} \<br>        --zone=${CLUSTER_ZONE} \<br>        -q --async</pre><pre>        # Delete <br>        kubectx -d ${CLUSTER_NAME}<br>}<br></pre><pre>delete_cluster central us-central1-a<br>delete_cluster west us-west1-b<br>delete_cluster east us-east1-b</pre><pre>gcloud compute firewall-rules delete istio-multicluster-pod-fw</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2d875a3712b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the ESP8266 WiFi Module with Arduino Uno publishing to ThingSpeak]]></title>
            <link>https://cgrant.medium.com/using-the-esp8266-wifi-module-with-arduino-uno-publishing-to-thingspeak-99fc77122e82?source=rss-60e881a91384------2</link>
            <guid isPermaLink="false">https://medium.com/p/99fc77122e82</guid>
            <category><![CDATA[thingspeak]]></category>
            <category><![CDATA[esp8266]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[makers]]></category>
            <dc:creator><![CDATA[Christopher Grant]]></dc:creator>
            <pubDate>Mon, 19 Feb 2018 23:24:46 GMT</pubDate>
            <atom:updated>2019-02-08T13:40:03.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9np6tJI3HogFrZmt-G3ZaA.jpeg" /></figure><p>I’ve got this <a href="https://amzn.to/2PspIen">ESP8266</a> WiFi module hanging around that I’ve never really used. I also have a few <a href="https://amzn.to/2rttsm6">Arduino UNOs</a> sitting here not getting any use at the moment. I thought this would be a great time to put the two together for a project I’m working on. It wasn’t easy. There was a ton of conflicting and confusing content that made it much more difficult. I’m writing this up in hopes it might help the next guy just a little bit.</p><p>Contents</p><ul><li>Understanding the <a href="https://amzn.to/2PspIen">ESP8266</a></li><li>Setting up ThingSpeak</li><li>Testing the <a href="https://amzn.to/2PspIen">ESP8266</a> Directly</li><li>Accessing <a href="https://amzn.to/2PspIen">ESP8266</a> from <a href="https://amzn.to/2rttsm6">Arduino Uno</a> code</li><li>Putting it all together</li></ul><h3>Understanding the ESP8266</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZSqkf-cT6NdQbj0I30l6g.jpeg" /></figure><p>First and foremost, a search for ESP8266 will turn up many references to an awesome tiny micro-controller that’s been all the rage until the new ESP32 recently came out. At first, you might think you searched for the wrong thing, but nope you didn’t. This little component is the original and it technically can be programmed just like it’s bigger siblings. It only has two GPIO pins though and isn’t really designed to be a micro-controller. Adding “Wifi Module” to your searches helps focus the results</p><blockquote>Search for “ESP8266 WiFI Module”</blockquote><p>Next, we have the Pinout connections. Depending on the article you’re looking at the connections will change. It’s important to understand the pins and how they’re used. In general, you have a VCC for power and your common GND. You also have TX and RX to transmit and Receive. You have two GPIO pins, a reset pin, and a CH_PD pin. This board is designed to be an add-on to another micro-controller and offers a feature for being able to turn it on or off by setting the CH_PD pin from High to Low. In my case, I’m going to leave it on all the time so I’m just pulling high all the time.</p><blockquote>CH_PD is a chip controlled power down and needs to pull high in order to run</blockquote><p>Speaking of voltage, all the articles I’ve seen warnings not to give it too much power, but mine seemed to need more than the 3.5v Arduino served up. In my tests, the module wouldn’t start up correctly with 3.5v which made it very difficult to debug early on. I ended up switching to the 5v pin and everything has been great.</p><h4>NOTE: The ESP8266 maximum working Voltage is 3.6V.</h4><p>It’s supposed to run with less but mine didn’t. The most common responses to this article scream not to use 5v. While it worked for me, use caution.</p><blockquote>If 3.5v is not enough, consider more</blockquote><p>Accessing the ESP8266 WiFi Module is also confusing. There are two main concepts here. In the first option, you’re using the Module as an add-on and writing code in the Arduino to talk to it. The other model is that you’re trying to work on the module directly to program it or upgrade it. For our final project here we will have code on the Arduino talking to the module, but to make sure everything is working we’ll be talking to the Module directly (kind of). More on that later.</p><blockquote>Understand if you’re accessing the Arduino Uno or the ESP8266 Module</blockquote><h3>Setting up ThingSpeak</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxA4dxPaJEr8julLO494kA.png" /></figure><p>Let’s take a moment to create an endpoint we can send some data to in our test.</p><ul><li>Create an account on ThingSpeak <a href="https://thingspeak.com/">https://thingspeak.com/</a></li><li>Create a new channel with one field label</li><li>Get the API Key</li><li>Review the “Update a Channel Feed” Url</li></ul><p>ThingSpeak is insanely easy to use. Once you have your channel and key you can simply make an HTTP request to <a href="https://api.thingspeak.com/update?api_key=YOUR_KEY_HERE&amp;field1=4">https://api.thingspeak.com/update?api_key=YOUR_KEY_HERE&amp;field1=4</a> to send the value 4 into field1. Try it in your browser, then review the data in the Private View of your channel.</p><blockquote>Make note of the channel’s API Key to use later in your code</blockquote><h3>Testing the ESP8266 Directly</h3><p>OK so now that we have something to test against, let’s get back to the ESP8266. Remember we left off noting that you can access the WiFi module with Arduino Code or directly. I’m a fan of reducing variables and since I didn’t trust the code samples I was finding, I thought it best to make sure my WiFi Module was working by itself before trying to tie it into the Arduino code. PROBLEM you need special adapters to connect it to your computer. A USB Serial TTY adapter might work, but I didn’t get the wiring right and almost fried the module. SOLUTION use the Arduino Uno as a Bridge, bypassing everything in the Uno and talking to the module directly.</p><p>So here’s how this works. You can connect the reset pin on the Uno to GND to bypass the Arduino bootloader. This allows you to connect to the Uno’s TX and RX from the Module. Since the Uno’s USB cable is properly hooked up to the Uno’s TR and RX, any signals put on those lines will pass right on to the module. Here’s the trick, in this case, we want the TX on the Uno to connect to the TX on the module and the RX from the Uno to the RX on the Module. Realize that all we’re doing here is extending the TX line into the module. The crossover, in this case, is already managed in the USB adapter. We’ll change this later. Only in this bridge model do you have TX to TX and RX to RX.</p><blockquote>Use the Uno as a bridge to talk to the module directly. Bypassing the Uno boot loader connecting RESET to GND, then connect TX to TX, RX to RX, GND to GND, VCC and CH_PD to 5v.</blockquote><p><strong>Wiring</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*IfHONRU0cWu3g9wnfI_GjQ.png" /></figure><pre>Esp8266 | Arduino <br>-----------------<br>     RX | RX <br>     TX | TX <br>    GND | GND<br>    VCC | 5v <br>  CH_PD | 5v <br> GPIO 0 | None <br> GPIO 2 | None</pre><pre>Arduino | Arduino<br>-----------------<br>  Reset | GND</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8WIZuPYMK4cdnuHR3fBkw.jpeg" /></figure><p>Once you have it wired up you should be able to use the Arduino Serial Monitor in the Arduino IDE to access the Module. Remember you’ll connect to the port the Arduino is on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*w0kCFmwS0CTWvA2BlQw2BQ.png" /></figure><p>Next, make sure you choose “Both NL &amp; CL” then adjust the Baud rate. My module was talking on 115200 baud but I’ve heard other models on 9600.</p><p>At this point, you should be able to send an “AT” command and get an “OK” response. WoHoo! you’re talking to the module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbeBmKApGbzREk7gpFFaGQ.png" /></figure><p>Let’s play more. For this section I found its easier to prep your commands in a text editor then just copy and paste into the Serial Monitor.</p><p>Connect to your wifi by sending</p><pre>AT+CWJAP=”WIFI_NAME”,”WIFI_PASSWORD”</pre><p>Be sure to put in your own wifi name and password</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnw7Qg9mpPiVVZtEEiBIww.png" /></figure><p>Connect to ThingSpeak</p><pre>AT+CIPSTART=”TCP”,”api.thingspeak.com”,80<br>AT+CIPSEND=51<br>GET /update?key=XXXXXXXXXXXXXXXX&amp;field1=55 \r\n<br>AT+CIPCLOSE</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2gXhn4LBgizqmLRkDOAjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slLPEz38ddDKUar5eKdZEw.png" /></figure><p>In this last image, I’ve highlighted the response from ThingSpeak. They return a counter and this was my 1761st message.</p><p>You should have received a response after the GET command. Check your ThingSpeak channel to see the data.</p><blockquote>Note: AT+CIPSEND needs to be 2 more than the size of your GET line. I believe this is related to the Serial Monitor sending NL &amp; CR.</blockquote><blockquote>Note: There needs to be a space after the URL in your GET and the new line characters, that tripped me up.</blockquote><h3>Accessing ESP8266 from Arduino Uno code</h3><p>Now we’re ready for the normal flow. We’re going to write code for the Arduino to talk to the module. The wiring here will have the TX of the Uno connected to the RX on the module and the RX on the Uno talking to the TX on the module, but don’t do it yet. PROBLEM there’s only one serial on the Uno but we need it for debugging and also for the module. We can’t use one Serial for both. Thankfully we can use some code called SoftwareSerial to make a Virtual Serial port on the Arduino. This means that instead of connecting to the TX/RX we’ll connect to another pin set and have SoftwareSerial send commands to those pins instead.</p><blockquote>Trying to wire into the Uno’s Serial TX/RX will block you from connecting the IDE to the UNO since it works over the USB Serial on the same pins.</blockquote><blockquote>Use SoftwareSerial library to connect the module through pins 10 &amp; 11. Move the Module wires and be sure to remove the jumper wire that was between RESET and GND</blockquote><pre>Esp8266 | Arduino <br> — — — — — — — — -<br>     RX | 11 <br>     TX | 10 <br>    GND | GND (same)<br>    VCC | 5v (same) <br>  CH_PD | 5v (same) <br> GPIO 0 | None (same) <br> GPIO 2 | None (same)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ba6XvjbrufKEN66Fe77tTg.jpeg" /></figure><p>Note that White TX is in pin 10 and Grey RX is in Pin 11</p><p>Ok let’s look at some code</p><p>First, we need to set up the virtual serial for the module. We’ll include the library and define the variable</p><pre>#include &lt;SoftwareSerial.h&gt;<br>#define RX 10<br>#define TX 11<br>SoftwareSerial esp8266(RX,TX);</pre><p>From here on we’ll talk to the Module through “esp8266” and we’ll talk to the IDE through “Serial”. Let’s try it in our setup function</p><pre>void setup() {<br> Serial.begin(9600);<br> esp8266.begin(115200);<br> …</pre><p>Note that we set the Serial connection to a 9600 baud rate and the esp8266 connection to a 115200 baud rate. Make sure to set your IDE Serial Monitor to the right baud and set the esp8266 value to the baud rate of the module you confirmed earlier.</p><p>Let’s add more and see if it’s working by passing in the same commands we did before</p><pre>void setup() {<br> Serial.begin(9600);<br> esp8266.begin(115200);<br> esp8266.println(command);<br> esp8266.println(“AT+CWMODE=1”);<br> esp8266.println(“AT+CWJAP=\”WIFI_NAME\”,\”WIFI_PASSWORD\””);<br>}</pre><p>Sweet so hopefully that worked. If it didn’t the command may have timed out or failed. I found <a href="http://www.instructables.com/id/ESP8266-IOT-Using-Arduino-and-ThingSpeak/">some code</a> to help deal with that. The rest of the example is patterned off that source.</p><p>Basically, there’s a helper function called “sendCommand” that takes a command, a timeout value and the expected result as input. I also extracted the sensor data to its own function called, surprisingly, getSensorData. This has a simple random value in it now but will be replaced by actual sensor data in the final implementation</p><h3>Putting it all together</h3><p>OK ready for the whole code base? Note that the setup function below differs from the one above, just in case you were copy/pasting and didn’t catch that.</p><pre>#include &lt;SoftwareSerial.h&gt;</pre><pre>#define RX 10<br>#define TX 11</pre><pre>String AP = &quot;WIFI_NAME&quot;;       // CHANGE ME<br>String PASS = &quot;WIFI_PASSWORD&quot;; // CHANGE ME</pre><pre>String API = &quot;YOUR_API_KEY&quot;;   // CHANGE ME<br>String HOST = &quot;api.thingspeak.com&quot;;<br>String PORT = &quot;80&quot;;<br>String field = &quot;field1&quot;;</pre><pre>int countTrueCommand;<br>int countTimeCommand; <br>boolean found = false; <br>int valSensor = 1;</pre><pre>SoftwareSerial esp8266(RX,TX); <br> <br>  <br>void setup() {<br>  Serial.begin(9600);<br>  esp8266.begin(115200);<br>  sendCommand(&quot;AT&quot;,5,&quot;OK&quot;);<br>  sendCommand(&quot;AT+CWMODE=1&quot;,5,&quot;OK&quot;);<br>  sendCommand(&quot;AT+CWJAP=\&quot;&quot;+ AP +&quot;\&quot;,\&quot;&quot;+ PASS +&quot;\&quot;&quot;,20,&quot;OK&quot;);<br>}</pre><pre>void loop() {<br> valSensor = getSensorData();<br> String getData = &quot;GET /update?api_key=&quot;+ API +&quot;&amp;&quot;+ field +&quot;=&quot;+String(valSensor);</pre><pre>sendCommand(&quot;AT+CIPMUX=1&quot;,5,&quot;OK&quot;);<br> sendCommand(&quot;AT+CIPSTART=0,\&quot;TCP\&quot;,\&quot;&quot;+ HOST +&quot;\&quot;,&quot;+ PORT,15,&quot;OK&quot;);<br> sendCommand(&quot;AT+CIPSEND=0,&quot; +String(getData.length()+4),4,&quot;&gt;&quot;);<br> esp8266.println(getData);delay(1500);countTrueCommand++;<br> sendCommand(&quot;AT+CIPCLOSE=0&quot;,5,&quot;OK&quot;);<br>}</pre><pre>int getSensorData(){<br>  return random(1000); // Replace with <br>}</pre><pre>void sendCommand(String command, int maxTime, char readReplay[]) {<br>  Serial.print(countTrueCommand);<br>  Serial.print(&quot;. at command =&gt; &quot;);<br>  Serial.print(command);<br>  Serial.print(&quot; &quot;);<br>  while(countTimeCommand &lt; (maxTime*1))<br>  {<br>    esp8266.println(command);//at+cipsend<br>    if(esp8266.find(readReplay))//ok<br>    {<br>      found = true;<br>      break;<br>    }<br>  <br>    countTimeCommand++;<br>  }<br>  <br>  if(found == true)<br>  {<br>    Serial.println(&quot;OYI&quot;);<br>    countTrueCommand++;<br>    countTimeCommand = 0;<br>  }<br>  <br>  if(found == false)<br>  {<br>    Serial.println(&quot;Fail&quot;);<br>    countTrueCommand = 0;<br>    countTimeCommand = 0;<br>  }<br>  <br>  found = false;<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DISWZOQtUYYn_JLef-xhbQ.png" /></figure><p>Head over to ThingSpeak to see your data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Id5YRBl0SIIIZcsaod6yRA.png" /></figure><p>There ya go, You’ve got WiFi on your Arduino. Happy IoT-ing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99fc77122e82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Global ingress in practice on Google Container Engine — Part 2: Demo]]></title>
            <link>https://medium.com/google-cloud/global-ingress-in-practice-on-google-container-engine-part-2-demo-cf587765702?source=rss-60e881a91384------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf587765702</guid>
            <category><![CDATA[google-container-engine]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[ingress]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Christopher Grant]]></dc:creator>
            <pubDate>Wed, 20 Sep 2017 18:00:28 GMT</pubDate>
            <atom:updated>2017-09-24T15:46:50.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OJVUtgtFOdUsoOF2." /></figure><p>This article is a follow up to a couple previous ones, <a href="https://medium.com/google-cloud/global-kubernetes-in-3-steps-on-gcp-8a3585ec8547">Global Kubernetes in 3 Steps on GCP</a> which walks through setting up a global cluster, and <a href="https://medium.com/@cgrant/global-ingress-in-practice-on-google-container-engine-part-1-discussion-ccc1e5b27bd0">Global ingress in practice on Google Container Engine — Part 1: Discussion</a> which discusses how you would use a Global cluster with a Google LoadBalancer for Ingress.</p><p><strong>Source Code</strong><br>The source code for this walkthrough can be <a href="https://github.com/cgrant/global-k8s-ingress-with-gce-controller">found on GitHub here</a></p><p>In there you’ll find:<br>- /app — the code for the apps used in the demo<br>- /cluster — a single script to provision a federated cluster<br>- /deploy — the k8s yaml files we’ll be using in the demo</p><h3>Setup the cluster</h3><p>I’ve covered this in detail in the <a href="https://medium.com/google-cloud/global-kubernetes-in-3-steps-on-gcp-8a3585ec8547">Global Kubernetes in 3 Steps</a> post and have provided it again in the <a href="https://github.com/cgrant/global-k8s-ingress-with-gce-controller/blob/master/README.md">README</a>. This article is more about how to use it so I won’t go into the setup process here.</p><h3>Deploy the Applications and Ingress</h3><p>First off, grab the repo and clone it locally</p><pre><br>git clone <a href="https://github.com/cgrant/global-k8s-ingress-with-gce-controller">https://github.com/cgrant/global-k8s-ingress-with-gce-controller</a><br>cd global-k8s-ingress-with-gce-controller<br></pre><p>For this example I’ve provided sample python applications in the /apps directory. I’ve prebuilt them and posted them to docker hub as well. You should be able to customize the code or swap in your own images.</p><p><strong>Deploy the apps</strong></p><pre>kubectl apply -f deploy/app-with-context.yaml<br>kubectl apply -f deploy/simple-echo.yaml</pre><p>As mentioned in Part 1, you’ll need to explicitly set the NodePort values on the Deployment. I’ve already set these for you to `30048` and `30050`</p><p>Review the workloads page in <a href="https://console.cloud.google.com/kubernetes/workload">Google Cloud Console</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tlHhuld_TogUG01R_mA_IA.png" /></figure><p><strong>Create a global IP</strong><br>Once the application pods are deployed we can look at sticking them together with an ingress.</p><p>First thing we need to do is create a global IP for the Global LoadBalancer.</p><blockquote>This is critical for ingress to work on multiple clusters. the default ephemeral IPs are only regional and won’t allow proper federation</blockquote><p>Create a global ip named ingress-ip</p><pre>gcloud compute addresses create ingress-ip — global</pre><p><strong>Deploy the Ingress</strong></p><p>Now deploy the Ingress itself</p><pre>kubectl apply -f deploy/ingress.yaml</pre><p>This will take awhile, 5 minutes or so, for the loadbalancers to be created worldwide and for all the health checks to pass.</p><p>You can review the progress on the <a href="https://console.cloud.google.com/kubernetes/discovery">Discovery &amp; load balancing page</a> in the Cloud Console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZ4sXIqHwICgDp91RcKtEA.png" /></figure><p>Once the load balancer is up you can access the following urls:</p><p>/<br>/foo<br>/foo/bar<br>/echo<br>/echo/anyString</p><p>From the <a href="https://console.cloud.google.com/kubernetes/discovery">Discovery &amp; load balancing page</a> in the Cloud Console, click on the Load Balancer name for details. Then scroll down to the backends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*FjQZYK5tpDWG7Uj1Ug48Mg.png" /></figure><p>There will be a backend for each service in your ingress yaml. Go ahead and click on one of the backends</p><p>As traffic flows to your new service, you can see the break down of location and other metrics on this page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBoxs_TTuOwWWOypq_k3kw.png" /></figure><p>Thats it, you’re good to go!</p><h3>On Your Own</h3><p>Thats the short and sweet of the demo. Be sure to explore the code to understand the mechanics. Also try updates on your own</p><p>Go ahead and deploy your own service, modify the ingress.yaml and run</p><pre>kubectl apply -f deploy/ingress.yaml</pre><p>New services on the load balancer take a few minutes to come up but changes to existing services is pretty quick</p><p>Try it by updating the image in the app Deployment to something new, for example maybe i update `simple-echo.yaml `</p><pre>spec:<br> containers:<br> — name: simple-echo<br> image: cgrant/simple-echo-server<br>```</pre><p>to</p><pre>spec:<br> containers:<br> — name: simple-echo<br> image: cgrant/simple-echo-server:version1<br></pre><p>Then apply</p><pre>kubectl apply -f deploy/simple-echo.yaml</pre><p>The containers will update promptly and you’re all set!</p><p>I really like the ability of using native Google Cloud products with Kubernetes. It takes much of the hassle out of the infrastructure while providing me with robust managed tools for my apps.</p><p>Hope you enjoyed. Please leave any comments or questions</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf587765702" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/global-ingress-in-practice-on-google-container-engine-part-2-demo-cf587765702">Global ingress in practice on Google Container Engine — Part 2: Demo</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>