<?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 Gwen Leigh on Medium]]></title>
        <description><![CDATA[Stories by Gwen Leigh on Medium]]></description>
        <link>https://medium.com/@gwenleigh?source=rss-e6c0ecbdd9d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8zXvVATixTe3jK9dbRlmsw.jpeg</url>
            <title>Stories by Gwen Leigh on Medium</title>
            <link>https://medium.com/@gwenleigh?source=rss-e6c0ecbdd9d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:05:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gwenleigh/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[Tech book writing #2: Multiverse of Madness — Terraform with Go (my first tech book)]]></title>
            <link>https://medium.com/@gwenleigh/tech-book-writing-2-multiverse-of-madness-terraform-with-go-my-first-tech-book-a035110a6ae5?source=rss-e6c0ecbdd9d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a035110a6ae5</guid>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Gwen Leigh]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 08:00:59 GMT</pubDate>
            <atom:updated>2023-10-26T08:00:59.908Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tech book writing #2: Multiverse of Madness — Terraform with Go (my first tech book)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W23sx2qXQ566seT06corcg.png" /></figure><p>I am currently learning Terraform using the <a href="https://www.exampro.co/ter-cpb-001">Terraform Bootcamp</a> learning contents developed by <a href="https://www.linkedin.com/in/andrew-wc-brown/">Andrew Brown</a> and <a href="https://www.linkedin.com/in/abayko/">Andrew Bayko</a> with <a href="https://www.linkedin.com/in/chrisfwilliams/">Chris Williams</a> and <a href="https://www.youtube.com/@GiftedLane">Shala</a>.</p><p>The bootcamp officially ended a few weeks ago, but I still felt that there were gaps in my head on what we’ve learnt so I decided to fill them by doing my own research.</p><p>Week 2’s intense “Go”ing got many of us confused, lost, tripped up and frustrated. So I organised my learnings into a short book called the Multiverse of Madness, which is now publicly accessible here below:</p><ul><li><a href="https://gwen-leigh.gitbook.io/multiverse-of-madness-terraform-with-go/"><strong>Multiverse of Madness — Terraform with Go</strong></a></li><li>My complete <a href="https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-complete-learning-journal-3640cebc74b5">Learning Journal</a> for this <a href="https://www.exampro.co/ter-cpb-001">Terraform Bootcamp</a></li><li><a href="https://www.buymeacoffee.com/gwenleigh">Buy me a coffee</a> ☕️</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pu4zTXZa9v-cl0ViCk1c7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a035110a6ae5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWSKRUG — AWS Korea User Group #Euljiro Meetup. Wednesday, 18 October 2023]]></title>
            <link>https://medium.com/@gwenleigh/awskrug-aws-korea-user-group-euljiro-meetup-wednesday-18-october-2023-8f9174da9e26?source=rss-e6c0ecbdd9d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f9174da9e26</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Gwen Leigh]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 08:53:49 GMT</pubDate>
            <atom:updated>2023-10-21T09:21:19.613Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWSKRUG — AWS Korea User Group #Euljiro Meetup. Wednesday, 18 October 2023: AWS Serverless Lambda with MSK</h3><p>Hello, world on Medium and the Internet! 👋 On 18th Thursday, I went to this amazing AWS user group meetup in Seoul and I thought I should share it with you!</p><h4><strong>📑 Notes</strong></h4><ul><li><strong>A bit about me</strong>: I’m an aspiring Cloud Computing / DevOps Engineer in the future. In preparation of this, I’m learning through <a href="https://www.linkedin.com/in/andrew-wc-brown/">Andrew</a> and <a href="https://www.linkedin.com/in/abayko/">Andrew</a>’s <a href="https://terraform.cloudprojectbootcamp.com/">bootcamps</a> and <a href="https://www.exampro.co/">education</a>.</li><li>I left some maple leaves (🍁) here and there throughout this article. The sentences or paragraphs marked with 🍁 are topics that were either covered during or overlap with <a href="https://www.exampro.co/">Andrews</a>’ teachings.</li><li>If you didn’t learn with <a href="https://www.exampro.co/">Andrews</a>, please note that some bits with 🍁 may or may not make sense to you.</li><li>This night’s talk was a real-world use case from a real company in Korea. Andrew often tells us stories about how things work in reality. Actively connecting the dots between what we learn in a learning environment and the bits and pieces we witness from the real world will help us bridge the gap.</li></ul><h3><strong>Table of Contents</strong></h3><ol><li><strong>A short story about Euljiro</strong></li><li><a href="#756f"><strong>The Talk</strong></a><strong>: Developing a Slackbot Gateway using AWS Lambda by </strong><a href="https://www.linkedin.com/in/sudosubin/"><strong>Subin Kim</strong></a></li></ol><ul><li>Before: the Slack bot</li><li><a href="#1046">The Problems</a></li><li>The Existing Architecture — What needs to be changed?</li><li>How can we do differently?</li><li><a href="#0b05">The New Architecture</a></li><li>Why MSK?</li><li><a href="#7a80">The New Architecture — What changed?</a></li><li>Development using AWS SAM CLI</li><li><a href="#efd1">Go code</a></li><li>Benefits and Limitations of using Go</li></ul><p><strong>3. </strong><a href="#40a1"><strong>Summary &amp; Conclusion</strong></a></p><h3>A short story about Euljiro</h3><p>The <a href="https://aws.amazon.com/developer/community/usergroups/">AWS User Group</a> is a <strong><em>huuuuuge!</em></strong> community of users that develop and build their services using AWS based across all around the world. Many countries that have AWS infrastructure in them usually have local user groups across different cities and locations.</p><p>Korea has a big AWS User Group community. Currently, there are <a href="https://aws.amazon.com/developer/community/usergroups/?community-user-groups-cards.sort-by=item.additionalFields.ugName&amp;community-user-groups-cards.sort-order=asc&amp;awsf.location=*all&amp;awsf.category=*all&amp;community-user-groups-cards.q=korea&amp;community-user-groups-cards.q_operator=AND">22 local groups listed</a> on <a href="https://aws.amazon.com/developer/community/usergroups/?community-user-groups-cards.sort-by=item.additionalFields.ugName&amp;community-user-groups-cards.sort-order=asc&amp;awsf.location=*all&amp;awsf.category=*all">AWS’ official User Group</a> page and more are being created. Korea’s user groups can be generally grouped into two categories — by location and subject. This night was the first meetup of this brand new group created for and by the AWS users of the Euljiro area. Euljiro is one of Seoul’s busiest CBDs (Central Business Districts) sitting on the “green circle”. Below is Seoul’s subway map, and the green circle passes through all the busiest, hottest and most popular areas and spots across the capital city.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3aRXUOcyt_KKxj0Ia6R9g.png" /><figcaption>Euljiro, one of Seoul’s CBDs.</figcaption></figure><h3>2. <strong>The Talk: Developing a Slackbot Gateway using AWS Lambda by Subin Kim</strong></h3><p><a href="https://github.com/sudosubin?tab=repositories">Subin</a> is an extremely talented server developer and is one of the organisers of AWS Korea User Group. He prepared this brilliant talk on the serverless Lambda and MSK use case for the members.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*826xdscqXCe7kH26zuVthg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26al0sgbxRpZS_PiQeAq7g.png" /><figcaption>The talk was amazing. He was highly knowledgeable in his areas and had excellent presentation skills. I wished many more people could attend the moment live.</figcaption></figure><h4>Before: the Slack bot</h4><ul><li>Subin’s company uses Slack and Slack bot to manage various internal tasks including the employee attendance records, vacation scheduling, the use of corporate credit cards, managing employee account permissions, legal matters and contracts and budget administration.</li><li>In the existing architecture, the bot🤖 would push the event requests (the data and attachment files) coming up on the Slack channels immediately to the database in real time. These requests would measure as heavy as 20k per minute.</li></ul><h4><strong>Th</strong>e Problems</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOjfs4N7P7ufaiIc6KkAZQ.png" /><figcaption>The old architecture. Image from <a href="https://github.com/sudosubin">Subin</a>’s presentation material</figcaption></figure><ul><li>As the number of Slack messages exponentially increased, the main processing Server (written in Python 🐍) would be often overloaded and wasn’t able to handle the Webhook requests in time, leading to a significant backlog in message handling.</li><li>Additionally, if the message is consumed once, it would be gone forever. But the team needed to use them multiple times for various purposes.</li></ul><h4>The Existing Architecture — What needs to be changed?</h4><ul><li>Slack Webhook request handling should be improved to improve the reliability of the event handling procses.</li><li>Slack event data need to be preprocessed.</li><li>Currently, requests are processed indiscriminately as they come in. Which results in database overloads and this need to be changed!</li><li>The team wants to reuse specific events across multiple services multiple times over.</li></ul><h4>How can we do differently?</h4><ul><li><strong>Go serverless</strong>: Subin’s team decided to implement a serverless function to ensure reliable handling of the request traffic while keeping the cost down.</li><li><strong>Data pre-processing</strong>: As the types of Slack webhook event data vary, the Team decided to include a data pre-processing function in the serverless implementation.</li><li><strong>Queueing: </strong>Lambda is flexible in scaling. The Team’s database behind it is RDS, though, meaning the RDS instances fixed capacity specifications (i.g. CPU, RAM, storage size) and it is not easy to scale them right away in the event of unpredictable request traffic spikes. On top of this, processing messages in the first-come first-served basis could lead to database overloads. The Team also wanted to reuse the messages multiple times over for different purposes, so they decide to introduce <strong>queueing</strong>.</li></ul><h4>The New Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkZMFEjZwT3Sds74zWTCrQ.png" /><figcaption>The new architecture. Image I created with the architecture from <a href="https://github.com/sudosubin">Subin</a>’s presentation material</figcaption></figure><ul><li>Place an API Gateway<strong> </strong>in front as the endpoint for Slack webhook requests.</li><li>The Lambda will pre-process the data to convert them into json-like key-value pairs and send them over to MSK.</li><li>MSK, which serves as the queue handler, will consume the events and send them to the main server for event handling.</li></ul><h4>Why MSK?</h4><p>AWS MSK stands for the Managed Streaming for Apache Kafka. The Team selected MSK because:</p><ul><li>🍁 The company system has been using Kafka as the enterprise queue handling solution. So the developers were familiar with Kafka.</li><li>🍁 The data platform team also found it easy to work with.</li><li>Kafka is widely used for implementing real-time data processing pipelines at scale. Kafka clusters facilitate reliable operations and scaling.</li><li>Additionally, Kafka allows you to readily reuse a single event multiple times, and to consume the event again even in the case the message handilng fails.</li></ul><h4><strong>The New Architecture — What changed?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5KC6tyqIhe5QRUtclpR7og.png" /><figcaption>The new architecture. Image I created with the architecture from <a href="https://github.com/sudosubin">Subin</a>’s presentation material</figcaption></figure><ul><li>The Slack webhook remained the same.</li><li>The AWS cloud infrastructure is fronted by the API gateway endpoints which receive the webhook requests.</li><li>Multiple consumer groups can processes a single event at the same time.</li><li>Most of the main python server’s code remained the same except for the minor changes made to consume the queues coming through the API gateway endpoint.</li></ul><p>⚠️Disclaimer. The size of the service logo or the Go Gopher does NOT represent the importance or composition of the architecture. It’s just my personal liking for silly billy goofy all things… 🐁</p><h4>Development using AWS SAM CLI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*Mj1x1hPcpGPwaqaZZw5Qdg.png" /><figcaption>AWS SAM code for the slack bot development, image from <a href="https://github.com/sudosubin">Subin Kim</a>’s presentation material</figcaption></figure><ul><li>The Team used SAM (AWS Serverless Application Model) as it was easy to do testing on the Lambda function during the local development stage such as invoking lambda and sending test data.</li><li>The building and deployment processes were almost automatic.</li></ul><h4>Deployment using containers</h4><p>In the deployment stage, however, they decided to do without SAM CLI as the process involves CloudFormation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*d4Rq7Gd20nAJktk3FkDlrQ.png" /></figure><p>(🍁 <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/blob/47-terratowns-provider/terraform-provider-terratowns/main.go">Terraform custom provider plugin</a> &amp; <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/blob/47-terratowns-provider/bin/build_provider">the build process</a>) When implementing the deployment, they built the code inside a container first, then copied the resulting binary to the host. Then the binary was zipped in the host machine then uploaded to Lambda.</p><h3>🍁 Go code</h3><p>The code below is part of Subin’s company’s lambda code. It was shared publicly upon the approval of the company.</p><ul><li>🍁 ctx context.Context is a context object from the standard library’s context package. It is used to pass around request-scoped values across APIs. We used it for <strong>configuring the </strong><strong>Provider()</strong> and <strong>implementing the CRUD functions</strong> in <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/blob/main/terraform-provider-terratowns/main.go">our custom terraform provider plugin</a>.</li><li>1) Create a producer client.</li><li>2) contentType determines the data pre-processing process.</li><li>2–1) If the request header’s content type is json, it will go straight to Kafka.</li><li>2–2) If it is Application/x-www-form-urlencoded, it will be converted into json-like key-value pairs, then passed to the Kafka clusters.</li><li>Although it is not shown in the code, some Slack webhook requests would be base64 so they also developed functions that pre-process such data.</li><li>As a result, the Kafka consumer clusters will receive the unified form of data, which increases the reliability of data handling process on the server side.</li></ul><pre>func handler(ctx context.Context, request events.APIGatewayProxyRequest) (<br> events.APIGatewayProxyResponse, error,<br>) {<br> config := sarama.NewConfig()<br> producer, err := sarama.NewAsyncProducer(..., config)    // 1) <br> if err != nil {<br>  return NewSimpleResponse(http.StatusBadRequest)<br> }<br><br> contentType, _ := request.Headers[&quot;content-type&quot;]         // 2)<br><br> if strings.HasPrefix(contentType, &quot;application/json&quot;) {   // 2-1)<br>  producer.Input() &lt;- &amp;sarama.ProducerMessage{<br>   Topic: &quot;...&quot;,<br>   Value: sarama.StringEncoder(request.Body),<br>  }<br> }<br><br> if strings.HasPrefix(contentType, &quot;Application/x-www-form-urlencoded&quot;) { // 2-2)<br>  if value, err := MarshalQuery(reqeust.Body); err = nil {<br>   producer.Input() &lt;- &amp;sarama.ProducerMessage {<br>    Topic: &quot;...&quot;, <br>    Value: sarama.StringEncoder(value),<br>   }<br>  }<br> }<br><br> producer.Close()<br> return NewSimpleResponse(http.StatusOK)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*evHrLpOgY8wMMA3F06B6Cw.png" /><figcaption>Part of the serverless Lambda code implemented in 🍁 Go 🐁</figcaption></figure><h4>Benefits and Limitations of using Go 🐁</h4><p>The following points are insights drawn from Subin’s experience. Please note that some points made here are not necessarily the intrinsic properties of Go.</p><ul><li><strong>Go is light</strong>: if your lambda code exceeds 50 MB, you will have to go through the hassle of uploading the source code to the S3 bucket, then get the bucket’s endpoint, put it to Lambda, and all that jazz. Subin’s lambda ended up being only 6.8 MB. So it was light, it was easy to upload, and it was quick to deploy. I mean, <a href="https://en.wikipedia.org/wiki/Gopher">a typical gopher weighs about 200 g</a>, so what did you expect? 🐭</li><li><strong>Go wasn’t as fast</strong>: the request time would take around 500 ms to 3000 ms. The request handling time through the whole Kafka process would vary from a request to another. Something that the Team can work on to improve in the future. (Any idea, fellows? 👀)</li></ul><h3>Summary &amp; Conclusion</h3><ul><li>Previously the main event handling server for Slack webhooks would receive and handle the event requests indiscriminately and immediately from the Slack bot.</li><li>They inserted the serverless Lambda and MSK queue handler between Slack and the Python server. This increased the reliability of the server’s event handling.</li><li>Additionally, the Team was able to lower the cost (which costs about $200 per month).</li></ul><h3>Resources</h3><h4>AWS</h4><ul><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-concurrency.html">Lambda Function Scaling</a></li><li><a href="https://pkg.go.dev/github.com/aws/aws-lambda-go/lambda">Lambda Go Package</a></li></ul><h4>Brilliant</h4><ul><li><a href="https://github.com/IBM/sarama">Sarama — the Go library for Kafka</a></li><li><a href="https://en.wikipedia.org/wiki/Gopher">How heavy is a gopher!?</a> 👀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f9174da9e26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Cloud Project Bootcamp with Andrew Brown — 
2.6.0 Terraform Cloud and Multi Homes]]></title>
            <link>https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-2-6-0-terraform-cloud-and-multi-homes-3d107a2b5e35?source=rss-e6c0ecbdd9d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d107a2b5e35</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[terraform-cloud]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Gwen Leigh]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 09:40:53 GMT</pubDate>
            <atom:updated>2023-10-17T09:40:53.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform Cloud Project Bootcamp with Andrew Brown — <br>2.6.0 Terraform Cloud and Multi Homes</h3><p>This article is part of my Terraform journey with <a href="https://www.exampro.co/ter-cpb-001">Terraform Bootcamp</a> by <a href="https://www.linkedin.com/in/andrew-wc-brown/">Andrew Brown</a> and <a href="https://www.linkedin.com/in/abayko/">Andrew Bayko</a> with <a href="https://www.linkedin.com/in/chrisfwilliams/">Chris Williams</a> and <a href="https://www.youtube.com/@GiftedLane">Shala</a>.</p><p>My wild career adventure into Cloud Computing continues with Andrews, and I highly, highly recommend you to come join us if you are interested. Check out <a href="https://www.youtube.com/@ExamProChannel">Andrews’ free youtube learning contents</a>. You can also <a href="https://www.exampro.co/">buy some paid courses here</a> to support their good cause.</p><h3>Agenda</h3><p>Video here: <a href="https://youtu.be/PswO3Tf8HDs">2 6 0 Terraform Cloud and Multi Homes</a></p><h4><a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/issues/51">Issue #51 Goals</a></h4><ul><li>✅ 1) Move our state back to Terraform Cloud with local execution</li><li>✅ 2) Provision more than one terra home</li></ul><h4>Workflow</h4><ul><li>✅ 1) Switch back to Terraform Cloud</li><li>✅ 2) Configure multi homes</li><li>✅ 3) Nested variables</li></ul><h3>1. Switch back to Terraform Cloud</h3><p>We have been developing and executing locally in Gitpod workspace. In this last episode, <a href="https://www.linkedin.com/in/andrew-wc-brown/">Andrew</a> and <a href="https://www.linkedin.com/in/abayko/">Andrew</a> walk us through the migration process to move back from the local environment to ‘Terraform Cloud while executing locally’.</p><p>First, we go to Terraform Cloud and set our Default Execution Mode as Local. At the project level (our terra-house), set the Execution Mode as Custom &gt; Local.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qaOXwBgl-vYZ5x1ntPG6OA.png" /></figure><p>We have to be able to connect to the remote <strong>Terraform Cloud </strong>from local Gitpod workspace. So let’s bring back the configuration. Uncomment the cloud block inside terraform{} in main.tf.</p><pre>terraform {<br>    ...<br>    cloud {<br>        organization = &quot;mariachiinajar&quot;<br>        workspaces {<br>          name = &quot;terra-house&quot;<br>        }<br>    }<br>}</pre><p>Andrew updates gitpod.yml.</p><pre>tasks:<br>  - name: terraform<br>    env: <br>      TF_LOG=DEBUG<br>    before: |<br>      cd $PROJECT_ROOT<br>      source ./bin/install_terraform_cli<br>      source ./bin/generate_tfrc_credentials<br>      source ./bin/set_tf_alias<br>+     source ./bin/build_provider</pre><p>Andrew runs terraform init and terraform apply and it works.</p><h3>2. Configure multi homes</h3><p>Andrew creates another terratowns_home using the same module (terrahome_aws). The configuration is the same as before. Now that we are deploying homes for real, you can change the town to the one you like amongst cooker-cove, gamers-grotto, the-nomad-pad, video-valley, and melomaniac-mansion. Interesting things to note are:</p><ul><li>module name can be anything. What matters is the path to the source.</li><li>As every resource has to have a unique name, the first home (home) and second home (home_voices)have different names.</li><li>There are better was to create multiple instances of the same resource. This could be a micro project to further our Terraform skills.</li></ul><pre>module &quot;home_nomadiachi_hosting&quot; {<br>  source          = &quot;./modules/terrahome_aws&quot;<br>  user_uuid       = var.teacherseat_user_uuid<br>  public_path     = var.nomadiachi.public_path<br>  content_version = var.nomadiachi.content_version<br>}<br><br>resource &quot;terratowns_home&quot; &quot;home&quot; {<br>  name            = &quot;Nomadiachi&#39;s nomadic life&quot;<br>  description     = &lt;&lt;DESCRIPTION<br>    Mariachi works nomadically so popping in and checking out here and there.<br>    Pictures of some memorable moments, quick snapshots of days in and days out. <br>    Come join my nomadinary journey? :D <br>DESCRIPTION<br>  domain_name     = module.home_nomadiachi_hosting.domain_name<br>  town            = &quot;the-nomad-pad&quot;<br>  content_version = var.nomadiachi.content_version<br>}<br><br>module &quot;home_voices_hosting&quot; {<br>  source          = &quot;./modules/terrahome_aws&quot;<br>  user_uuid       = var.teacherseat_user_uuid<br>  public_path     = var.voices.public_path<br>  content_version = var.voices.content_version<br>}<br><br>resource &quot;terratowns_home&quot; &quot;home_voices&quot; {<br>  name            = &quot;Voices that keep me going&quot;<br>  description     = &lt;&lt;DESCRIPTION<br>    Reading is a mental nomadism. Reading quotes is traveling through million different minds and angles.<br>    There were many moments and days I entertained quitting. <br>    But there were voices that give me nudges and pushes (and punches and smashes... and slaps and !@#$@$). <br>    I&#39;m still here and keep moving forward.<br>    Come have a look who are those with the badass voices. lol<br>DESCRIPTION<br>  domain_name     = module.home_voices_hosting.domain_name<br>  town            = &quot;the-nomad-pad&quot;<br>  content_version = var.voices.content_version<br>}</pre><p>Now Andrew reorganises the assets for homes. The folder structure is:</p><pre>public<br>├── home1<br>│   ├── assets<br>│   │   ├── ...<br>│   │   └── image.jpg<br>│   ├── index.html<br>│   └── error.html<br>├── home2<br>│   ├── assets<br>│   │   ├── ...<br>│   │   └── image.jpg<br>│   ├── index.html<br>└── └── error.html </pre><p>In modules/terrahome_aws/variables.tf, change the variable name as below.</p><pre>- variable &quot;index_html_filepath&quot; {<br>-   description = &quot;File path for index.html&quot;<br>+ variable &quot;public_path&quot; {<br>+   description = &quot;The file path for the public directory&quot;</pre><p>In modules/terrahome_aws/resource-storage.tf, modify the paths using the public_path variable both aws_s3_object.index_html and error_html.</p><pre># resource-storage.tf<br><br>resource &quot;aws_s3_object&quot; &quot;index_html&quot; {<br>  bucket = aws_s3_bucket.website_bucket.bucket<br>  key    = &quot;error.html&quot;<br>- source = &quot;${path.root}/public/index.html&quot;<br>+ source = &quot;${var.public_path}/index.html&quot;<br>  content_type = &quot;text/html&quot;<br><br>- etag   = filemd5(&quot;${path.root}/public/index.html&quot;)<br>+ etag   = filemd5(&quot;${var.public_path}/index.html&quot;)<br>} </pre><h3>3. Nested variables</h3><p>Andrew decides to reorganise the variables using the nested variable structure. In Terraform, we can achieve this using object or map.</p><pre>// variables.tf at root<br><br>variable &quot;nomadiachi&quot; {<br>  type = object({<br>    public_path     = string<br>    content_version = number<br>  })<br>}<br><br>variable &quot;voices&quot; {<br>  type = object({<br>    public_path     = string<br>    content_version = number<br>  })<br>}</pre><p>Now we can use the nested variables as below.</p><pre>// main.tf at root<br><br>module &quot;home_nomadiachi_hosting&quot; {<br>  source          = &quot;./modules/terrahome_aws&quot;<br>  user_uuid       = var.teacherseat_user_uuid<br>  public_path     = var.nomadiachi.public_path<br>  content_version = var.nomadiachi.content_version<br>}</pre><p>Andrew changes the module name to terrahome_aws so we make the changes accordingly across the files where the module is referenced.</p><pre>// outputs.tf<br><br>module &quot;home_nomadiachi_hosting&quot; {<br>-  source          = &quot;./modules/terrahouse_aws&quot;<br>+  source          = &quot;./modules/terrahome_aws&quot;<br>   user_uuid       = var.teacherseat_user_uuid<br>   public_path     = var.nomadiachi.public_path<br>   content_version = var.nomadiachi.content_version<br>}</pre><p>Andrew updates resourceHouseUpdate function in main.go. (<a href="https://youtu.be/PswO3Tf8HDs?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;t=2732">45:32</a>)</p><ul><li>Add</li></ul><pre> // parse response JSON<br> var responseData map[string]interface{}<br> if err := json.NewDecoder(resp.Body).Decode(&amp;responseData); err != nil {<br>  return diag.FromErr(err)<br> }</pre><ul><li>Replace</li></ul><pre><br> // StatusOK = 200 HTTP Response Code<br> if resp.StatusCode != http.StatusOK {<br>- return diag.FromErr(fmt.Errorf(&quot;failed to update home resource, status_code: %d, status: %s&quot;, resp.StatusCode, resp.Status))<br>+ return diag.FromErr(fmt.Errorf(&quot;failed to create home resource, status_code: %d, status: %s, body: %s&quot;, resp.StatusCode, resp.Status, responseData))<br> }</pre><p>Then run:</p><pre>./bin/build_provider<br>terraform init</pre><p>Andrew runs terraform init and terraform apply and the resources are running on TerraTowns. In case you run into error, compare your code against <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/tree/56-multi-home-terrafrom-cloud">Andrew’s source code here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_O-795jl-834WNpeoJ_K_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3SoY44sdojEtYuAv78MOxQ.png" /><figcaption>My homes are running in the Nomad Pad town!</figcaption></figure><h3>📑 Notes</h3><ul><li>With nested variables, we can organise the structure of variables more neatly.</li><li>The term “interpolation” means embedding variables within other strings.</li><li>If you are looking to further your terraform skills, you can try refactoring the multihomes using, for example, for_each or map function.</li></ul><h3>Resources</h3><h4>Bootcamp</h4><ul><li>Video: <a href="https://youtu.be/PswO3Tf8HDs">2 6 0 Terraform Cloud and Multi Homes</a></li><li>My feature branch:</li><li>My complete <a href="https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-complete-learning-journal-3640cebc74b5">Learning Journal</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d107a2b5e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Cloud Project Bootcamp with Andrew Brown — 2.5.0 Deploying to Terratowns]]></title>
            <link>https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-2-5-0-deploying-to-terratowns-b937e75641c9?source=rss-e6c0ecbdd9d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b937e75641c9</guid>
            <category><![CDATA[provisioning]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[provider]]></category>
            <dc:creator><![CDATA[Gwen Leigh]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 14:27:31 GMT</pubDate>
            <atom:updated>2023-10-16T14:27:31.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform Cloud Project Bootcamp with Andrew Brown — 2.5.0 Deploying to Terratowns</h3><p>This article is part of my Terraform journey with <a href="https://www.exampro.co/ter-cpb-001">Terraform Bootcamp</a> by <a href="https://www.linkedin.com/in/andrew-wc-brown/">Andrew Brown</a> and <a href="https://www.linkedin.com/in/abayko/">Andrew Bayko</a> with <a href="https://www.linkedin.com/in/chrisfwilliams/">Chris Williams</a> and <a href="https://www.youtube.com/@GiftedLane">Shala</a>.</p><p>My wild career adventure into Cloud Computing continues with Andrews, and I highly, highly recommend you to come join us if you are interested. Check out <a href="https://www.youtube.com/@ExamProChannel">Andrews’ free youtube learning contents</a>. You can also <a href="https://www.exampro.co/">buy some paid courses here</a> to support their good cause.</p><h3>Agenda</h3><p>Video here: <a href="https://youtu.be/fPYHmiM9r6Y">2 5 0 Deploying to Terratowns</a></p><h4><a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/issues/50">Issue #52 Goals</a></h4><ul><li>✅ 1) Test our custom provider, to work with the production server.</li></ul><h4>Workflow</h4><ul><li>✅ 1) Deploy to Missingo</li><li>✅ 2) <a href="#3e83">Serve the content</a></li><li>✅ 3) <a href="#695d">Bucket name and &amp; Security Best practices</a></li></ul><h3>1. Deploy to Missingo</h3><p>In the previous episode, we were testing the environment locally in Gitpod workspace. Now we want to deploy our terratown_homes to actual TerraTown. The town Missingo is a test town for campers to test-deploy our homes. Let’s do this.</p><p>The first thing we do is to update the URL endpoint for the terratowns provider in main.tf.</p><pre>provider &quot;terratowns&quot; {<br>-  endpoint  = &quot;http://localhost:4567/api&quot;<br>+  endpoint  = &quot;https://terratowns.cloud/api&quot;<br>   user_uuid = &quot;e328f4ab-b99f-421c-84c9-4ccea042c7d1&quot;<br>   token     = &quot;9b49b3fb-b8e9-483c-b703-97ba88eef8e0&quot;<br>}</pre><p>Then we replace the mock user_uuid and token with our own. You can find your own User UUID in the access token on <a href="https://www.exampro.co/">ExamPro.co</a> website.</p><ul><li><strong>user_uuid</strong>: click on your profile circle at the top-right corner.</li><li><strong>token</strong>: from that circle, you have the top-down menu. Click on Settings. Then you will have the Vending Machine option. There, you can generate your own access token.</li></ul><pre># main.tf<br><br>provider &quot;terratowns&quot; {<br>  endpoint  = &quot;https://terratowns.cloud/api&quot;<br>  user_uuid = &quot;your-own-uuid&quot;<br>  token     = &quot;your-own-token-from-vending-machine&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EToOO_FZMOidUJO_JsBDBQ.png" /><figcaption>Where to find your UUID</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtGqOJkFU_8SNZZUXEaZvQ.png" /><figcaption>Get a token from the vending machine</figcaption></figure><p>Then we are switching to the test town “missingo”.</p><pre>resource &quot;terratowns_home&quot; &quot;home&quot; {<br>  name        = &quot;Nomadiachi&#39;s nomadic life&quot;<br>  description = &lt;&lt;DESCRIPTION<br>    Mariachi works nomadically so popping in and checking out here and there.<br>    Pictures of some memorable moments, quick snapshots of days in and days out. <br>    Come join my nomadinary journey? :D <br>DESCRIPTION<br>  # domain_name = module.terrahouse_aws.cloudfront_url<br>  domain_name     = &quot;3fdq3gz.cloudfront.net&quot;<br>- town            = &quot;the-nomad-pad&quot;<br>+ town            = &quot;missingo&quot;<br>  content_version = 2<br>}</pre><p>We rebuild our custom provider then test it out. Now run:</p><pre>./bin/build_provider<br>terraform init<br>terraform apply</pre><p>Now it’s running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*pf0Ev9GFcJPac-KaugY_8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*29CHKVm9HBQyimSXf7VLGg.png" /></figure><h3>2. Serve the content</h3><p>If you click on the terratowns_home in Missingo, however, the content is not served. We have to do more configuration to get it served up. So we tear down the infrastructure. Run: terraform destroy (<a href="https://youtu.be/fPYHmiM9r6Y?t=379">6:19</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*Imf0xak-EPExB5Lc9l0_Tw.png" /></figure><p>First, we want to mask the environmental variables using terraform variables in provider in main.tf.</p><pre>provider &quot;terratowns&quot; {<br>-   endpoint  = &quot;http://localhost:4567/api&quot;<br>-   user_uuid = &quot;e328f4ab-b99f-421c-84c9-4ccea042c7d1&quot;<br>-   token     = &quot;9b49b3fb-b8e9-483c-b703-97ba88eef8e0&quot;<br>+   endpoint  = var.terratowns_endpoint<br>+   user_uuid = var.teacherseat_user_uuid<br>+   token     = var.terratowns_access_token<br>}</pre><p>Add the following to terraform.tfvars at root.</p><pre>terraform_endpoint=&quot;https://terratowns.cloud/api&quot;</pre><p>We take out the mock url and bring back the CloudFront domain_name in resource home.</p><pre>resource &quot;terratowns_home&quot; &quot;home&quot; {<br>  name        = &quot;Nomadiachi&#39;s nomadic life&quot;<br>  ...<br>+ domain_name = module.terrahouse_aws.cloudfront_url<br>- domain_name     = &quot;4fdq3gz.cloudfront.net&quot;<br>  town            = &quot;missingo&quot;<br>  content_version = 1<br>}</pre><p>For security best practices, we want to store the user_uuid and access_token as env variables and call them from main.tf. The way to let terraform know of the locally stored env variables is to name the env variables headed by “TF_VAR”.</p><pre>export TF_VAR_terratowns_access_token=&quot;access-token-from-vending&quot;<br>gp env TF_VAR_terratowns_access_token=&quot;access-token-from-vending&quot;<br>export TF_VAR_teacherseat_user_uuid=&quot;uuid-from-exampro&quot;<br>gp env TF_VAR_teacherseat_user_uuid=&quot;uuid-from-exampro&quot;</pre><p>Run terraform apply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Eo2lsqbV6Rh6cBH4W1XaTg.png" /></figure><p>Obviously, terraform doesn’t know where to find the values. We have to modify the terraform variable names identical to the exported variable names (excluding TF_VAR_ in front).</p><pre># variables.tf<br><br>- variable &quot;user_uuid&quot; {<br>+ variable &quot;teacherseat_user_uuid&quot; {<br>    type = string<br>  }</pre><p>In fact, we have to add all the variables that we are going to secure so add the following three to your variables.tf at root.</p><pre>provider &quot;terratowns&quot; {<br>  endpoint  = var.terratowns_endpoint<br>  user_uuid = var.teacherseat_user_uuid<br>  token     = var.terratowns_access_token<br>}</pre><pre># variables.tf<br><br>variable &quot;terratowns_endpoint&quot; {<br>  type = string<br>}<br><br>variable &quot;teacherseat_user_uuid&quot; {<br>  description = &quot;Your own user uuid from teacherseat.&quot;<br>  type = string<br>}<br><br>variable &quot;terratowns_access_token&quot; {<br>  description = &quot;Your own access token generated by the vending machine from teacherseat.&quot;<br>  type = string<br>}</pre><p>Andrew wants to see if referencing variables works correctly. We run terraform apply. If successful, destroy the infrastructure right after.</p><p>Now, bring back the old infrastructure module.terrahouse_aws.</p><pre>module &quot;terrahouse_aws&quot; {<br>  source              = &quot;./modules/terrahouse_aws&quot;<br>  user_uuid           = var.teacherseat_user_uuid<br>  bucket_name         = var.bucket_name<br>  index_html_filepath = var.index_html_filepath<br>  error_html_filepath = var.error_html_filepath<br>  content_version     = var.content_version<br>  assets_path         = var.assets_path<br>}</pre><p>Run terraform init and terraform apply. It’s not going to work as the value for assets_path is missing.</p><p>Add assets_path to the module terrahouse_aws.</p><pre>module &quot;terrahouse_aws&quot; {<br>  source              = &quot;./modules/terrahouse_aws&quot;<br>  user_uuid           = var.teacherseat_user_uuid<br>  bucket_name         = var.bucket_name<br>  index_html_filepath = var.index_html_filepath<br>  error_html_filepath = var.error_html_filepath<br>  content_version     = var.content_version<br>+ assets_path         = var.assets_path<br>}</pre><h3>3. Bucket name &amp; Security Best practices</h3><p>There are security concerns regarding the bucket_name. During our Terraform bootcamp, it happened that someone took Andrew’s bucket name which he had been using throughout the videos. As every AWS S3 bucket name has to be unique throughout the world, this causes problems on Andrew’s end. Now he wants to have the bucket_name randomly generated so this name conflict doesn’t happen again.</p><pre>module &quot;terrahouse_aws&quot; {<br>  source              = &quot;./modules/terrahouse_aws&quot;<br>  user_uuid           = var.teacherseat_user_uuid<br>- bucket_name         = var.bucket_name<br>  index_html_filepath = var.index_html_filepath<br>  error_html_filepath = var.error_html_filepath<br>  content_version     = var.content_version<br>  assets_path         = var.assets_path<br>}</pre><p>Then comment out the entire bucket_name variable in variables.tf.</p><pre># variable &quot;bucket_name&quot; {<br>#   description = &quot;The name of the S3 bucket&quot;<br>#   type        = string<br><br>#   validation {<br>#     condition = (<br>#       length(var.bucket_name) &gt;= 3 &amp;&amp; length(var.bucket_name) &lt;= 63 &amp;&amp;<br>#       can(regex(&quot;^[a-z0-9][a-z0-9-.]*[a-z0-9]$&quot;, var.bucket_name))<br>#     )<br>#     error_message = &quot;The bucket name must be between 3 and 63 characters, start and end with a lowercase letter or number, and can contain only lowercase letters, numbers, hyphens, and dots.&quot;<br>#   }<br># }</pre><p>Now that we removed the bucket_name variable, we have to change the parts where this variable is referenced.</p><pre>resource &quot;aws_cloudfront_origin_access_control&quot; &quot;default&quot; {<br>- name        = &quot;OAC ${var.bucket_name}&quot;<br>- description = &quot;Origin Access Controls for Static Website Hosting ${var.bucket_name}&quot;<br>+ name        = &quot;OAC ${aws_s3_bucket.website_bucket.bucket}&quot;<br>+ description = &quot;Origin Access Controls for Static Website Hosting ${aws_s3_bucket.website_bucket.bucket}&quot;<br>  origin_access_control_origin_type = &quot;s3&quot;<br>  signing_behavior                  = &quot;always&quot;<br>  signing_protocol                  = &quot;sigv4&quot;<br>}<br><br>resource &quot;aws_cloudfront_distribution&quot; &quot;s3_distribution&quot; {<br>  ...<br>  enabled             = true<br>  is_ipv6_enabled     = true<br>- comment             = &quot;Static website hosting for: ${var.bucket_name}&quot;<br>+ comment             = &quot;Static website hosting for: ${aws_s3_bucket.website_bucket.bucket}&quot;<br>  default_root_object = &quot;index.html&quot;</pre><p>Then terraform apply. My terrahome is up and running on the test town Missingo!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDbwv1M8nDi_p2OlVzMkOA.png" /></figure><h3>📑 Notes</h3><ul><li>Every bucket name in AWS S3 must be globally unique. Otherwise this will lead to a bucket name conflict.</li></ul><h3>Resources</h3><h4>Bootcamp</h4><ul><li>Video: <a href="https://youtu.be/fPYHmiM9r6Y">2 5 0 Deploying to Terratowns</a></li><li>My feature branch: <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/tree/52-terratown-test">52-terratown-test</a></li><li>My complete <a href="https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-complete-learning-journal-3640cebc74b5">Learning Journal</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b937e75641c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Cloud Project Bootcamp with Andrew Brown — 2.4.0 CRUD Resource]]></title>
            <link>https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-2-4-0-crud-resource-80890f8c9604?source=rss-e6c0ecbdd9d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/80890f8c9604</guid>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[terraform-modules]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[bootcamp]]></category>
            <dc:creator><![CDATA[Gwen Leigh]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 11:10:58 GMT</pubDate>
            <atom:updated>2023-10-16T11:10:58.815Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform Cloud Project Bootcamp with Andrew Brown — 2.4.0 CRUD Resource</h3><p>This article is part of my Terraform journey with <a href="https://www.exampro.co/ter-cpb-001">Terraform Bootcamp</a> by <a href="https://www.linkedin.com/in/andrew-wc-brown/">Andrew Brown</a> and <a href="https://www.linkedin.com/in/abayko/">Andrew Bayko</a> with <a href="https://www.linkedin.com/in/chrisfwilliams/">Chris Williams</a> and <a href="https://www.youtube.com/@GiftedLane">Shala</a>.</p><p>My wild career adventure into Cloud Computing continues with Andrews, and I highly, highly recommend you to come join us if you are interested. Check out <a href="https://www.youtube.com/@ExamProChannel">Andrews’ free youtube learning contents</a>. You can also <a href="https://www.exampro.co/">buy some paid courses here</a> to support their good cause.</p><h3>Agenda</h3><p>Video here: <a href="https://www.youtube.com/watch?v=aeJCV-VIWiw&amp;list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;index=55&amp;ab_channel=ExamPro">2 4 0 CRUD Resource</a></p><h4><a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/pull/49">Issue #49 Goals</a></h4><ul><li>✅ 1) Finish the implementation of Provider Plugin by</li><li>✅ 2) implementing the CRUD functions.</li><li>✅ 3) Test the Plugin and troubleshoot.</li></ul><h4>Workflow</h4><ul><li>✅ 1) Update Resource() function in main.go</li><li>✅ 2) Create resource in main.tf</li><li>✅ 2–1) Troubleshooting: Failed to query available provider packages</li><li>✅ 3) <a href="#3f6d">Implement CRUD functions</a></li><li>✅ 4) <a href="#f52d">Go troubleshootiong</a></li></ul><p>Faithful campers follow Andrew along every step of his way! Andrew’s been craving for payday bars and this is the closest I can find where I’m based in. Our SCT (Standard Camping Time ⛺) is usually the wee morning hours for me (Canada and Korea) but whatever. I’ll burn it at the gym later🏃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fVvGgFcqiM84poKPt8GiwQ.jpeg" /></figure><h3>1. Update Resource() function in main.go</h3><p>In reality, it is the best if we can break down every resource we implement into atomic building blocks. In Andrews’ bootcamp, however, we just put everything into the single Resource() for simplicity and learning purposes.</p><p>Define the details of Resource() as below. The major updates to Resource() in this episode are:</p><ul><li>Define Schema, which will be used as the attributes of the resource block in HCL later in the main.tf file.</li></ul><pre>func Resource() *schema.Resource {<br> log.Print(&quot;Resource:start&quot;)<br> resource := &amp;schema.Resource{<br>  CreateContext: resourceHouseCreate,<br>  ReadContext:   resourceHouseRead,<br>  UpdateContext: resourceHouseUpdate,<br>  DeleteContext: resourceHouseDelete,<br>  Schema: map[string]*schema.Schema{<br>   &quot;name&quot;: {<br>    Type: schema.TypeString,<br>    Required: true,<br>    Description: &quot;Name of home&quot;,<br>   },<br>   &quot;description&quot;: {<br>    Type: schema.TypeString,<br>    Required: true,<br>    Description: &quot;Description of home&quot;,<br>   },<br>   &quot;domain_name&quot;: {<br>    Type: schema.TypeString,<br>    Required: true,<br>    Description: &quot;Domain name of home eg. *.cloudfornt.net&quot;,<br>   },<br>   &quot;town&quot;: {<br>    Type: schema.TypeString,<br>    Required: true,<br>    Description: &quot;The town to which the home will belong to&quot;,<br>   },<br>   &quot;content_version&quot;: {<br>    Type: schema.TypeInt,<br>    Required: true,<br>    Description: &quot;The content version of home&quot;,<br>   },<br>  }<br> }<br> log.Print(&quot;Resource:end&quot;)<br> return resource<br>}</pre><p>Then run ./bin/build_provider to update the plugin.</p><h3>2. Create resource in main.tf</h3><p>Now that our Plugin’s Resource is updated, we can use the updated feature immediately:</p><ul><li>Create a resource block in HCL in main.tf.</li><li>Provide values to Schema’s attributes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIo2ArGlKpG2eSYfbQPAvA.png" /></figure><pre>resource &quot;terratown_home&quot; &quot;home&quot; {<br>  name        = &quot;Nomadiachi&#39;s nomadic life&quot;<br>  description = &lt;&lt;DESCRIPTION<br>    Mariachi works nomadically so popping in and checking out here and there.<br>    Pictures of some memorable moments, quick snapshots of days that pass by. <br>    Come join my nomadinary journey? :D <br>DESCRIPTION<br>  # domain_name = module.terrahouse_aws.cloudfront_url<br>  domain_name     = &quot;3fdq3gz.cloudfront.net&quot; // mock url<br>  town            = &quot;the-nomad-pad&quot;<br>  content_version = 1<br>}</pre><h4>2–1. Troubleshooting: Failed to query available provider packages</h4><p>Then we run terraform init and run into the below error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAyUBgWPAQjVUQUlXh1Dnw.png" /></figure><p>Andrew decides to keep implementing the code to see if the problem persists.</p><h3>3. Implement CRUD functions</h3><p>For below walkthrough, I will be using only the Create function as an example. What I explain below is the common flow of the HTTP requests using CRUD functions. Please note that all the four CRUD functions must be updated, and they are slightly different from each other as each function performs different tasks. If you run into trouble executing the code later, feel free to copy <a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/blob/2.4.0/terraform-provider-terratowns/main.go">Andrew’s entire source code</a>.</p><h4>Add config</h4><ul><li>Config contains three attributes: user_uuid, token, and endpoint.</li><li>Config is used in the payload for HTTP request (the data that’s passed to manipulate the TerraTowns database) which requires credential data.</li></ul><h4>Make HTTP request</h4><ul><li>In the req, err block below, see how config is used. HTTP request is sending a request to an endpoint, so we always need a URL.</li></ul><h4>Set request headers</h4><ul><li>Headers are used to provide additional information about the message being sent or received.</li><li>We include the config.Token data for authentication at the TerraTowns website.</li></ul><pre>func resourceHouseCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {<br> var diags diag.Diagnostics<br><br>  // Add config<br>  config := m.(*Config) <br><br>  // Make HTTP request<br>  req, err := http.NewRequest(&quot;POST&quot;, config.Endpoint + &quot;/u/&quot; + config.UserUuid + &quot;/homes&quot;, bytes.NewBuffer(payloadBytes))<br>    if err != nil {<br>      return diag.FromErr(err)<br>    }<br><br>  // Set headers<br>  req.Header.Set(&quot;Authorization&quot;, &quot;Bearer &quot;+config.Token)<br>  req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  req.Header.Set(&quot;Accept&quot;, &quot;application/json&quot;)<br><br>  // Get response<br>  client := http.Client{}<br>  resp, err := client.Do(req)<br>  if err != nil {<br>  return diag.FromErr(err)<br>  }<br>  defer resp.Body.Close()<br><br> return diags<br>}</pre><h4>Payload</h4><ul><li>We create payload which is a map of string key — value pairs.</li><li>Payload is used only in the Create and Update functions.</li><li>json.Marshal() function handles the conversion of Go data structures into a valid JSON format.</li><li>Note that the payload and its marshaling happens prior to making the HTTP request. The json-formatted payload will be included in the http request (req) down the code to the <a href="https://terratowns.cloud/">TerraTowns</a> website.</li></ul><pre> payload := map[string]interface{}{<br>  &quot;name&quot;:            d.Get(&quot;name&quot;).(string),<br>  &quot;description&quot;:     d.Get(&quot;description&quot;).(string),<br>  &quot;domain_name&quot;:     d.Get(&quot;domain_name&quot;).(string),<br>  &quot;town&quot;:            d.Get(&quot;town&quot;).(string),<br>  &quot;content_version&quot;: d.Get(&quot;content_version&quot;).(int),<br> }<br><br> payloadBytes, err := json.Marshal(payload)<br> if err != nil {<br>  return diag.FromErr(err)<br> }</pre><h4>Parse response JSON</h4><ul><li>responseData is a map of interface{}, which is a type that can hold values of any type. It will hold the parsed Json data.</li><li>Just like we converted Go into Json (marshaled) when sending HTTP request, we have to convert the response Json back for Go (parse).</li><li>json.NewDecoder(resp.Body) will do the job.</li><li>The json.NewDecoder(resp.Body) will .Decode the &amp;responseData.</li><li>if any error occurs while decoding, the error will be stored in err.</li><li>if there is no error (nil)</li></ul><h4>StatusOK = 200 HTTP Response Code</h4><ul><li>To check if Status is OK, we are actually checking if it’s not okay.</li><li>If it’s not okay, the plugin will tell us the status code that it received from the TerraTowns server.</li></ul><pre>// parse response JSON<br> var responseData map[string]interface{}<br> if err := json.NewDecoder(resp.Body).Decode(&amp;responseData); err != nil {<br>  return diag.FromErr(err)<br> }<br><br> // StatusOK = 200 HTTP Response Code<br> if resp.StatusCode != http.StatusOK {<br>  return diag.FromErr(fmt.Errorf(&quot;failed to create home resource, status_code: %d, status: %s, body: %s&quot;, resp.StatusCode, resp.Status, responseData))<br> }</pre><p>The CRUD implementation is completed at <a href="https://youtu.be/aeJCV-VIWiw?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;t=2743">45:45</a>. The complete code is found in Andrew’s <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/blob/47-terratowns-provider/main.tf">main.tf</a>.</p><h3>4. Go troubleshootiong</h3><p>Now that the CRUD functions are complete, we want to test our plugin package. Run ./bin/build_provider.</p><p>We run into the following errors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*JfIGlB6fJWtsy-nlX5VH7A.png" /></figure><ul><li>Some if err statements were missing nil.</li><li>Import libraries if missing: “encoding/json”, “net/http”</li><li>client := http.Client{}: Client plus curly, not parenthesis.</li><li>For undefined: responseData: compare your code against <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/blob/2.4.0/terraform-provider-terratowns/main.go">Andrew’s</a>. responseData is used in Create and Read only.</li><li>Add library “bytes”.</li><li>Correct diag.FrontErr to diag.FromErr</li><li>For undefined: responseData, add interface{} with curlies:</li></ul><pre>var responseData map[string]interface{}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muUtHeSsW77R9CEWSbWN8w.png" /></figure><h3>4. Test out our custom provider</h3><p>Run terraform init to test if the provider is compiled correctly. And we are still stuck with the same error:</p><ul><li>Failed to query available provider packages</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TcOP2W0dXnlVAdWBWqt0bg.png" /></figure><p>In our ./terraform-provider-terratowns/, check main.go file and correct terratown_home(singluar) to terratowns_home(plural).</p><pre>func Provider() *schema.Provider {<br> var p *schema.Provider<br> p = &amp;schema.Provider{<br>  ResourcesMap: map[string]*schema.Resource{<br>   &quot;terratowns_home&quot;: Resource(), // terratown should be plural <br>  },</pre><p>Build the plugin again, then run terraform plan to see if: terraform is creating any resource! It works and you can hear <a href="https://youtu.be/aeJCV-VIWiw?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;t=3367">Andrew</a>’s excitement (56:14)! This is why we learn to code!!! 😃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*lSbQSttd9MYWQvngcay0Tg.png" /><figcaption>“It is showing us… our resource!!! So we just made our custom resource. and it’s showing what is going to change.”</figcaption></figure><p>According to Andrew’s words,</p><blockquote>I remember that our mock server is not real, so it will not work exactly correctly. But we can play a little bit around before trying it on the real TerraTowns.</blockquote><p>Now let’s run terraform apply.</p><h4>Troubleshooting: Plugin did not respond.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XDxQuHAd8BEH4bwgtb_IQ.png" /><figcaption>It wasn’t going to be all too easy, was it? It’s not all sunshine and roses!</figcaption></figure><p>In resourceHouseCreate.payload, check if content_version type is int or string.</p><pre> payload := map[string]interface{}{<br>  &quot;name&quot;:            d.Get(&quot;name&quot;).(string),<br>  &quot;description&quot;:     d.Get(&quot;description&quot;).(string),<br>  &quot;domain_name&quot;:     d.Get(&quot;domain_name&quot;).(string),<br>  &quot;town&quot;:            d.Get(&quot;town&quot;).(string),<br>  &quot;content_version&quot;: d.Get(&quot;content_version&quot;).(int),<br> }</pre><h4>Troubleshooting: failed to create home resource, status_code: 401 Unauthorized</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5VFXYymYfJxPV8ArDbppQ.png" /></figure><p>I kept running into the above error. At this stage, we are still using the mock values Andrew used in the videos for <strong>domain_name</strong>, <strong>user_uuid </strong>and <strong>token</strong>.</p><ul><li>Check the value of <strong>domain_name </strong>which is a mock cloudfront.net url.</li><li>Check the List of files where <strong>user_uuid </strong>&amp; <strong>token</strong> are used:</li><li>./bin/terratowns/create</li><li>./bin/terratowns/delete</li><li>./bin/terratowns/read</li><li>./bin/terratowns/update</li><li>./terratowns_mock_server/server.rb</li><li>./main.tf</li></ul><h4>Troubleshooting: json: Unmarshal(non-pointer map[string]interface {})</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPKeX6HW5WLgAFS96zT__w.png" /></figure><p>The error message json: Unmarshal(non-pointer map[string]interface {}) indicates that there’s an issue with unmarshaling JSON data into a non-pointer map[string]interface{} type in your Terraform configuration.</p><p>So I scan through the code and I see the yellow underline below Decode(). I hover over and I get the tip the call of Decode passes non-pointer. It turns out, I was missing the ampersand sign (&amp;) which is a pointer in Golang.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8r1uU1aWjGLqGlX5FsZdKA.png" /></figure><p>The Decode function expects a “pointed (&amp;)” argument so make sure to attach an ampersand before the argument.</p><p>💡Quick tip: difference between pointer and non-pointer arguments</p><ul><li>pointer argument: it points to the actual value. So if the value is updated, your functions are working with the updated value.</li><li>non-pointer argument: it is a copy of the argument. The copy’s value will stay the same even after the argument’s current value is updated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYAMiH3VZoxZnHwtJNIsCg.png" /><figcaption><a href="https://pkg.go.dev/encoding/json#Decoder.Decode">decode function</a></figcaption></figure><p>So I add an ampersand as a pointer (&amp;) as below and run terraform apply. It works a charm 😃!</p><pre>// resourceHouseCreate()<br>// parse response JSON<br> var responseData map[string]interface{}<br> if err := json.NewDecoder(resp.Body).Decode(&amp;responseData); err != nil {<br>  return diag.FromErr(err)<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPwHXXQDWgC8qQJWWJLRxA.png" /></figure><p>This is how I spotted the difference. <a href="https://winmerge.org/">WinMerge</a> is amazing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ic7zPhzQt8qBwroLxNQyMA.png" /></figure><p>Now that the complete Provider Plugin is working, we are good to define terratown_homes and deploy them to <a href="https://terratowns.cloud/">TerraTowns</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZnDWlY6CbLutI-ote6QuQ.png" /><figcaption>terraform apply</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*wilXu1AoLWEjw0qFDRnTCA.png" /><figcaption>Our plugin allows us to provision terratowns home(s).</figcaption></figure><h3>📑 Notes</h3><h4>Go language</h4><ul><li>json.Marshal() converts Go into json-formatted bytes.</li><li>Schema in Go is used to define inputs (attributes of code blocks such as provider or resource) in Terraform provider.</li></ul><h4>Go code flow</h4><ul><li>payload exists only in Create and Update.</li><li>responseData is used in Create and Read only.</li></ul><h3>Resource</h3><h4>Bootcamp</h4><ul><li>Video: <a href="https://www.youtube.com/watch?v=aeJCV-VIWiw&amp;list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;index=55&amp;ab_channel=ExamPro">2 4 0 CRUD Resource</a></li><li>My feature branch: <a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/tree/2.4.0">2 4 0</a></li><li>My complete <a href="https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-complete-learning-journal-3640cebc74b5">Learning Journal</a></li></ul><h4>Golang</h4><ul><li><a href="https://pkg.go.dev/encoding/json#Decoder.Decode">func (*Decoder) Decode</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80890f8c9604" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Cloud Project Bootcamp with Andrew Brown — 2.3.0 Resource Skeleton]]></title>
            <link>https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-2-3-0-resource-skeleton-5be22f6cfe68?source=rss-e6c0ecbdd9d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5be22f6cfe68</guid>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[resources]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Gwen Leigh]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 06:24:59 GMT</pubDate>
            <atom:updated>2023-10-16T06:25:29.472Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform Cloud Project Bootcamp with Andrew Brown — 2.3.0 Resource Skeleton</h3><p>This article is part of my Terraform journey with <a href="https://www.exampro.co/ter-cpb-001">Terraform Bootcamp</a> by <a href="https://www.linkedin.com/in/andrew-wc-brown/">Andrew Brown</a> and <a href="https://www.linkedin.com/in/abayko/">Andrew Bayko</a> with <a href="https://www.linkedin.com/in/chrisfwilliams/">Chris Williams</a> and <a href="https://www.youtube.com/@GiftedLane">Shala</a>.</p><p>My wild career adventure into Cloud Computing continues with Andrews, and I highly, highly recommend you to come join us. Check out <a href="https://www.youtube.com/@ExamProChannel">Andrews’ free youtube learning contents</a>. You can also <a href="https://www.exampro.co/">buy some paid courses here</a> to support their incredibly selfless cause.</p><h3>Agenda</h3><ul><li>Video here: <a href="https://youtu.be/_QBTP0SyGtQ?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A">2 3 0 Resource Skeleton</a></li><li>Feature branch here: <a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/tree/2.3.0">2.3.0</a></li></ul><h4><a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/pull/47">Issue #44 Goals</a></h4><ul><li>✅ 1) Fix validateUUID()</li><li>✅ 2) Define <strong>providerConfigure()</strong></li><li>✅ 3) Write skeletons for Resource() and CRUD functions.</li></ul><h4>Workflow</h4><ul><li>✅ 1) validateUUID()</li><li>✅ 2) <a href="#61f7">providerConfigure()</a></li><li>✅ 3) Resource()</li></ul><h3>Conceptual Summary</h3><p>Up until previous videos, we couldn’t do much with the Provider Plugin as it only has the skeleton with not much working detail. In this episode, we will flesh out the Resource() skeleton to complete its definition.</p><h3>1. validateUUID()</h3><p>We will run into the <strong>uuid </strong>not defined error. We have to install the uuid package by google. Add “github.com/google/uuid”. Then the terminal will require you to install it giving you the command.</p><ul><li>go get github.com/ExamProCo/terraform-provider-terratowns</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYrX5SejvL3KzYpsNvzGOQ.png" /></figure><p>When we try to install it with the go-provided command, it errors out. Hang on, wasn’t it you who just gave me this command to run 👀!?</p><p>We have to run it inside the right module. So cd into the directory terraform-providoer-terratowns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXfRC6sh1SdC-070BTApKw.png" /></figure><p>We also have to make some corrections to the main.go file.</p><ul><li>Wrap the strings to print with double quotes.</li><li>errors as the argument in append must be plural — errors.</li><li>return statement is missing. Add one.</li></ul><pre>func validateUUID(v interface{}, k string) (ws []string, errors []error) {<br>+  log.Print(&quot;validateUUID:start&quot;)   # double-quote<br>  value := v.(string)<br>  if _, err := uuid.Parse(value); err != nil {<br>+   errors = append(errors, fmt.Errorf(&quot;invalid UUID format&quot;))  # errors plural<br> }<br>+  log.Print(&quot;validateUUID:end&quot;)     # double-quote<br>+  return                            # return statement <br>}</pre><p>Now try running tf init. It should initialise just fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*xfMqV14_H7BNx44bAy4-Gg.png" /></figure><h3>2. providerConfigure()</h3><p>We define the function providerConfigure().</p><ul><li>providerConfigure() takes p as an argument, which is a Provider object from the Terraform SDK’s schema package.</li><li>The function returns a schema.ConfigureContextFunc which is a type representing a function used by the Terraform SDK to configure the provider.</li><li>Calling providerConfigure() will initialise a provider with the data filled with the values you provide (for Config) when making that call.</li></ul><pre>// main.go<br><br>func providerConfigure(p *schema.Provider) schema.ConfigureContextFunc {<br> return func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {<br>  log.Print(&quot;providerConfigure:start&quot;)<br>  config := Config{<br>   Endpoint: d.Get(&quot;endpoint&quot;).(string),<br>   Token:    d.Get(&quot;token&quot;).(string),<br>   UserUuid: d.Get(&quot;user_uuid&quot;).(string),<br>  }<br>  log.Print(&quot;providerConfigure:end&quot;)<br>  return &amp;config, nil<br> }<br>}</pre><ul><li>Golang tips: Golang is VERY sensitive about special characters, letter cases, typos and so on. Make sure you are using double quotations not single, all functions or variables that need to be uppercase are correctly so, and so on. If you think you typed everything correctly and still running into errors, try copying and pasting Andrew’s source code from <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/blob/47-terratowns-provider/terraform-provider-terratowns/main.go">here</a>.</li></ul><p>Then Andrew adds the diag package and thestruct Config.</p><pre>// main.go<br>import {<br>  &quot;github.com/hashicorp/terraform-plugin-sdk/v2/diag&quot;<br>}</pre><p>At the top of the main.go file, Andrew adds the Config struct definition as it is used inside the providerConfigure() function.</p><pre>type Config struct {<br>  Endpoint string<br>  Token    string<br>  UserUuid string<br>}</pre><p>Then build again with ./bin/build_provider.</p><p>Now we define the CRUD actions. Every single resource in terraform provider must have these CRUD actions defined.</p><pre>func Resource() *schema.Resource {<br> log.Print(&quot;Resource:start&quot;)<br> resource := &amp;schema.Resource{<br>  CreateContext: resourceHouseCreate,<br>  ReadContext:   resourceHouseRead,<br>  UpdateContext: resourceHouseUpdate,<br>  DeleteContext: resourceHouseDelete,<br> }<br> log.Print(&quot;Resource:end&quot;)<br> return resource<br>}</pre><p>Then we declare the skeletons of the CRUD functions. The detailed definitions will be completed in the next episode.</p><pre>func resourceHouseCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {<br> var diags diag.Diagnostics<br> return diags<br>}<br><br>func resourceHouseRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {<br> var diags diag.Diagnostics<br> return diags<br>}<br><br>func resourceHouseUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {<br> var diags diag.Diagnostics<br> return diags<br>}<br><br>func resourceHouseDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {<br> var diags diag.Diagnostics<br> return diags<br>}</pre><h3>📑 Notes</h3><ul><li>The purpose of the providerConfigure() function is to initialise our custom Provider with configuration details. These include user_uuid, token, and endpoint (the credentials and the website URL) that are required to access our <a href="https://terratowns.cloud/">TerraTowns</a> website.</li></ul><h3>Resources</h3><h4>Bootcamp</h4><ul><li>Video: <a href="https://youtu.be/_QBTP0SyGtQ?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A">2 3 0 Resource Skeleton</a></li><li>My feature branch: <a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/tree/2.3.0">2.3.0</a></li><li>My complete <a href="https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-complete-learning-journal-3640cebc74b5">Learning Journal</a></li></ul><h4>About GoLang</h4><ul><li><a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be22f6cfe68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Cloud Project Bootcamp with Andrew Brown — 2.2.0]]></title>
            <link>https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-2-2-0-a104a17eca9e?source=rss-e6c0ecbdd9d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a104a17eca9e</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[terraform-provider]]></category>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[bootcamp]]></category>
            <dc:creator><![CDATA[Gwen Leigh]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 05:06:46 GMT</pubDate>
            <atom:updated>2023-10-16T05:06:46.536Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform Cloud Project Bootcamp with Andrew Brown — 2.2.0 Provider Block for Custom Terraform Provider</h3><p>This article is part of my Terraform journey with <a href="https://www.exampro.co/ter-cpb-001">Terraform Bootcamp</a> by <a href="https://www.exampro.co/">Andrew Brown and Andrew Bayko</a> with <a href="https://www.linkedin.com/in/chrisfwilliams/">Chris Williams</a> and <a href="https://www.youtube.com/@GiftedLane">Shala</a>.</p><p>My wild career adventure into Cloud Computing continues with Andrews, and I highly, highly recommend you to come join us if you are interested. Check out <a href="https://www.youtube.com/@ExamProChannel">Andrews’ free youtube learning contents</a>. You can also <a href="https://www.exampro.co/">buy some paid courses here</a> to support their good cause.</p><h3>Agenda</h3><p>Video here: <a href="https://youtu.be/PivvxGseOwk?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A">2 2 0 Provider Block for Custom Terraform Provider</a></p><h4>Issue #47 Goals</h4><ul><li>✅ 1) We configure the provider in main.tf in hcl using our plugin.</li></ul><h4>Workflow</h4><ul><li>✅ 1) Update build_provider script</li><li><strong>✅ 2) </strong><a href="#2c69"><strong>Configure our custom provider</strong></a><strong> 🌟</strong></li><li>✅ 2–1) Troubleshoot: Error parsing /home/gitpod/.terraformrc</li><li>✅ 2–2) <a href="#02f3">Troubleshoot: duplicate required providers</a></li><li>✅ 3) <a href="#083d">Debugging</a></li></ul><h3>provider in terraform</h3><p>Following are the bits of information we need to know (from Terraform <a href="https://www.hashicorp.com/blog/writing-custom-terraform-providers">Historical Guide</a>).</p><blockquote>In Terraform, a “provider” is the logical abstraction of an upstream API.</blockquote><blockquote>Terraform supports a plugin model, and all providers are actually plugins. Plugins are distributed as Go binaries. Although technically possible to write a plugin in another language, almost all Terraform plugins are written in <a href="https://golang.org/">Go</a>.</blockquote><h3>1. Update build_provider script</h3><p>Run ./bin/builder_provider to test the path and if the binaries are generated correctly.</p><p>In the middle of the process, Andrew modifies the path <strong>~ </strong>to /home/gitpod to make sure the files are not generated elsewhere. Be sure to check your path is correct.</p><pre>- PLUGIN_DIR=&quot;~/.terraform.d/local.providers/local/terratowns/1.0.0&quot;<br>+ PLUGIN_DIR=&quot;/home/gitpod/.terraform.d/local.providers/local/terratowns/1.0.0&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGlaWDaU9nTo08WjC_2r3Q.png" /></figure><p>The library is now ready.</p><h3>2. Configure our custom provider</h3><p>Now that we built out our library, we want to configure our terraform.</p><ul><li>source attribute: we tell terraform where the source of the compiled provider binary is, which is the path where we generated our binaries with the build_provider script (in 2.1.0).</li><li>Update main.tf at root as below:</li></ul><pre># main.tf (at root)<br>terraform {<br>  required_providers {<br>    terratowns = {<br>      source  = &quot;local.providers/local/terratowns&quot;<br>      version = &quot;1.0.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;terratowns&quot; {<br>  endpoint  = &quot;http://localhost:4567&quot;<br>  user_uuid = &quot;e328f4ab-...&quot;<br>  token     = &quot;9b49b3fb-...&quot;<br>}</pre><ul><li><a href="https://youtu.be/PivvxGseOwk?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;t=461">7:40</a> Andrew, bless you! 😃</li></ul><p>What we are going to do is to writing the details inside the Provider() function block in ./terraform-provider-terratowns/main.go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVOxuxpBB-8arlEyMdQTOw.png" /><figcaption>Conceptually, this is what we write looks like.</figcaption></figure><p>Also have a look at the side-by-side comparison of how we write the plugin under the hood (below, right) and how we use it in the main.tf in HCL (Hashicorp Configuration Language) (below, left).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugxHehOEkeGbrbYCoevhkw.png" /><figcaption>Programmatically, this is how we actually “configure”.</figcaption></figure><p>Then we run the following commands to test our provider:</p><pre>./bin/build_provider<br>terraform init</pre><p>Then we run into two errors:</p><ul><li>Andrew&#39;s error: Error parsing /home/gitpod/.terraformrc</li><li>My error: Duplicate required providers configuration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdEqMcDnZl5t0UajO62RDA.png" /></figure><h4>2–1. Troubleshoot: Error parsing /home/gitpod/.terraformrc</h4><p>There was an equal sign (=) missing in the terraformrc file at root.</p><pre>provider_installation {<br>    filesystem_mirror {<br>        path = &quot;/home/gitpod/.terraform.d/plugins&quot;<br>+       include = [&quot;local.providers/*/*&quot;]<br>    }<br>    direct {<br>        exclude = [&quot;local.providers/*/*&quot;]<br>    }<br>}</pre><h4>2–2. Troubleshoot: duplicate required providers</h4><p>It turns out that earlier at some point, Andrew decided to delete the provider.tf file as we start using the custom “terratowns” provider. If you run into this error, check if you still have this file in your project directory.</p><p>For me, simply deleting provider.tf got rid of the issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgmGW0h9Hw79ezzV6LNHOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5GE03ikvdCUaLUQoYQNdg.png" /></figure><h3>3. Debugging</h3><p>Terraform provides debugging logs and configuringlog levels will make writing a custom provider a lot easier as it provides much more details for troubleshooting. You can print the debug logs by using the TF_LOG tag:</p><ul><li>TF_LOG=DEBUG terraform init</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*ZCaRkwomkX1QZYAx4u5oeg.png" /><figcaption>More detailed debug logs precede the terraform operation log.</figcaption></figure><p>Andrew wants this logging mode to persist so we do some environment configuration:</p><ul><li>Update terraform configuration in gitpod.yml</li><li>Export TF_LOG=DEBUG as an env variable.</li></ul><pre>tasks:<br>  - name: terraform<br>    env: <br>+     TF_LOG=DEBUG<br>    before: |<br>      cd $PROJECT_ROOT<br>      source ./bin/install_terraform_cli<br>      source ./bin/generate_tfrc_credentials<br>      source ./bin/set_tf_alias</pre><pre>export TF_LOG=DEBUG</pre><p>Now the DEBUG mode persists. Try running terraform init without the debug variable and the terminal still prints out the debug information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*eX9DAB6oQ_c-tphgg6wocw.png" /></figure><h3>Q&amp;A</h3><ul><li><a href="https://youtu.be/PivvxGseOwk?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;t=520">8:40</a>: does the build_provider automatically overwrite the existing file if we run it again without deleting the exiting bin files?</li></ul><h3>Resources</h3><h4>Bootcamp</h4><ul><li>Video: <a href="https://youtu.be/PivvxGseOwk?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A">2 2 0 Provider Block for Custom Terraform Provider</a></li><li>My feature branch: <a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/tree/47-terratowns-provider">47-terratowns-provider</a></li><li>My complete <a href="https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-complete-learning-journal-3640cebc74b5">Learning Journal</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a104a17eca9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Cloud Project Bootcamp with Andrew Brown — 2.1.0]]></title>
            <link>https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-2-1-0-cb7938b0d3b5?source=rss-e6c0ecbdd9d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb7938b0d3b5</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[provisioning]]></category>
            <category><![CDATA[terraform-provider]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Gwen Leigh]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 17:39:25 GMT</pubDate>
            <atom:updated>2023-10-15T17:39:25.406Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform Cloud Project Bootcamp with Andrew Brown — 2.1.0 Setup Skeleton for Custom Terraform Provider</h3><p>This article is part of my Terraform journey with <a href="https://www.exampro.co/ter-cpb-001">Terraform Bootcamp</a> by <a href="https://www.exampro.co/">Andrew Brown and Andrew Bayko</a> with <a href="https://www.linkedin.com/in/chrisfwilliams/">Chris Williams</a> and <a href="https://www.youtube.com/@GiftedLane">Shala</a>.</p><p>My wild career adventure into Cloud Computing continues with Andrews, and I highly, highly recommend you to come join us if you are interested. Check out <a href="https://www.youtube.com/@ExamProChannel">Andrews’ free youtube learning contents</a>. You can also <a href="https://www.exampro.co/">buy some paid courses here</a> to support their good cause.</p><h3>Agenda</h3><p>Video here: <a href="https://www.youtube.com/watch?v=pU8-AOhrIV8&amp;list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;index=52&amp;ab_channel=ExamPro">2 1 0 Setup Skeleton for Custom Terraform Provider</a></p><h4><a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/issues/44">Issue #44 Goals</a></h4><ul><li>✅ 1) Write our own Terratowns Provider skeleton in Golang</li></ul><h4>Workflow</h4><ul><li>Conceptual Summary</li><li><a href="#c196">Code we write</a></li><li>✅ 1) <a href="#74c9">main.go</a></li><li>✅ 2) <a href="http://2c69/">.terraformrc</a></li><li>✅ 3) <a href="#02f3">build_provider</a> (bash script)</li><li>✅ 4) <a href="#35a9">go.mod</a></li></ul><h3>Conceptual Summary</h3><p>In this episode, we will write our own custom provider in Golang. It has to be Go <a href="https://www.hashicorp.com/blog/writing-custom-terraform-providers">as Terraform Plugins are distributed as Go binaries</a>. Below is a simplified view of the skeleton of our Go plugin. The three dots (…) indicate that there is a lot going on in the <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/blob/47-terratowns-provider/terraform-provider-terratowns/main.go">final source code</a>.</p><ul><li>In go applications, main() is the <a href="https://en.wikipedia.org/wiki/Entry_point#:~:text=In%20JVM%20languages%20such%20as,a%20static%20method%20named%20Main%20.">entry point</a> for the go program.</li><li>Config holds credential data which is used in Provider().</li><li>The Provider() function instantiates a terraform provider(s) which will be the <a href="https://terratowns.cloud/">terratowns.cloud</a> website.</li><li>The Resource() function instantiates a terraform resource(s) which will give shape to our homes in TerraTowns.</li><li>The Resource() function comes with the four CRUD methods which allow us to manipulate the Resource(terratown homes)’s data.</li></ul><pre>// entry point<br>func main() { ... }<br><br>// Provider handling <br>type Config struct { ... }<br><br>func Provider() *schema.Provider { ... }<br>func validateUUID(...) { ... }<br>func providerConfigure(...) ... { ... }<br><br>// Resource handling <br>func Resource() ... { ... }<br><br>func resourceHouseCreate(...) diag.Diagnostics {...}<br>func resourceHouseRead(...) diag.Diagnostics {...}<br>func resourceHouseUpdate(...) diag.Diagnostics {...}<br>func resourceHouseDelete(...) diag.Diagnostics {...}</pre><h3>Code we write</h3><p>We will write the following three files.</p><ul><li>main.go</li><li>.terraformrc</li><li>build_provider (bash script)</li><li>go.mod (Andrew manually creates this)</li></ul><p>Below are what’s generated automatically by Go.</p><ul><li>go.mod</li><li>go.sum</li></ul><p>Let’s dive in.</p><h3>1. Write main.go</h3><p>Create a new folder for our custom provider. cd into the folder and create the main.go file. We will write our custom provider in Golang.</p><pre>mkdir terraform-provider-terratowns<br>cd terraform-provider-terratowns<br>go mod init  // Initialise the directory.<br>code main.go</pre><p>Below is the go code that will define our custom provider and is the final skeleton at the end of the video 2.1.0. I provide the final version for your convenience. If you are in trouble, feel free to copy and paste (Andrew’s original is <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/blob/2.1.0/terraform-provider-terratowns/main.go">here</a>). However, I strongly encourage you to follow along Andrew’s video.</p><p>📑<strong> Important notes from Andrew:</strong></p><ul><li>There are schema at the Resource() level and Provider() level.</li><li>Provider() is the <a href="https://terratowns.cloud/">terratowns.cloud</a> website and we will need three attributes: endpoint (terratowns.cloud), access token and user_uuid to successfully access the website.</li><li>Resource() is our TerraTown home(s). Every home needs five attributes: name, description, domain_name, town, and content_version.</li></ul><pre>// packadge main: Declares the package name.<br>// The main package is special in Go, it&#39;s where the execution of the program starts.<br>package main<br><br>// fmt is short format, it contains functions for formatted I/O.<br>import (<br> &quot;fmt&quot;<br><br> &quot;github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema&quot;<br> &quot;github.com/hashicorp/terraform-plugin-sdk/v2/plugin&quot;<br>)<br><br>// func main(): Defines the main function, the entry point of the app.<br>// When you run the program, it starts executing from this function.<br>func main() {<br> plugin.Serve(&amp;plugin.ServeOpts{<br>  ProviderFunc: Provider,<br> })<br> // Format.PrintLine<br> // Prints to standard output<br> fmt.Println(&quot;Hello, world&quot;)<br>}<br><br>// In golang, a titlecase function will get exported.<br>func Provider() *schema.Provider {<br> var p *schema.Provider<br> p = &amp;schema.Provider{<br>  ResourcesMap:   map[string]*schema.Resource{},<br>  DataSourcesMap: map[string]*schema.Resource{},<br>  Schema: map[string]*schema.Schema{<br>   &quot;endpoint&quot;: {<br>    Type:        schema.TypeString,<br>    Required:    true,<br>    Description: &quot;The endpoint for the external service&quot;,<br>   },<br>   &quot;token&quot;: {<br>    Type:        schema.TypeString,<br>    Sensitive:   true, // make the token as sensitive to hide in the logs.<br>    Required:    true,<br>    Description: &quot;Bearer token for authorisation&quot;,<br>   },<br>   &quot;user_uuid&quot;: {<br>    Type:        schema.TypeString,<br>    Required:    true,<br>    Description: &quot;UUID for configuration&quot;,<br>    // ValidateFunc: validateUUID,<br>   },<br>  },<br> }<br> // p.ConfigureContextFunc = providerConfigure(p)<br> return p<br>}<br><br>// func validateUUID(v interface{}, k string) (ws []string, errors []error) {<br>//  log.Print(&#39;validateUUID:start&#39;)<br>//  value := v.(string)<br>//  if _, err = uuid.Parse(value); err != nil {<br>//   errors = append(error, fmt.Errorf(&quot;invalid UUID format&quot;))<br>//  }<br>//  log.Print(&#39;validateUUID:end&#39;)<br>// }</pre><h3>2. .terraformrc</h3><p>By convention, we need .terraformrc because terraform’s default way to install provider plugins is from a provider registry. As it won’t be able to find our custom provider plugin from the Hashicorps’ registry (<a href="https://registry.terraform.io/">registry.terraform.io)</a>, we have to overwrite the path to the Registry and provide our custom local path.</p><pre>code .terraformrc</pre><pre># .terraformrc<br>provider_installation {<br>    filesystem_mirror {<br>        path = &quot;/home/gitpod/.terraform.d/plugins&quot;<br>        include [&quot;local.providers/*/*&quot;]<br>    }<br>    direct {<br>        exclude = [&quot;local.providers/*/*&quot;]<br>    }<br>}</pre><ul><li>Andrew referred to <a href="https://medium.com/weareservian/terraform-local-providers-and-registry-mirror-configuration-b963117dfffa">this article</a> for this section. Have a look for more information 👀.</li></ul><h3>3. build_provider</h3><p>Go is a compiled language, meaning it needs to be translated into machine code so the processor can execute it. In case it doesn’t make sense, just know that we need to run the command “go build” to produce a compiled binary file (not human-readable).</p><p>The build_provider file below is the bash script that automates the process of compiling the main.go file we wrote for our custom provider. The script’s workflow is:</p><ul><li>1) Define paths</li><li>2) Copy .terraformrc</li><li>3) Delete existing binary file: every time we make changes to the source code (main.go), we have to manually rebuild it by running the go build command. So we have to remove the existing binary first.</li><li>4) Build then copy to specified locations</li></ul><pre>cd $PROJECT_ROOT/bin<br>code build_provider</pre><pre># build_provider<br>#! /usr/bin/bash<br><br># 1) Define path <br>PLUGIN_DIR=&quot;~/.terraform.d/local.providers/local/terratowns/1.0.0&quot;<br>PLUGIN_NAME=&quot;terraform-provider-terratowns_v1.0.0&quot;<br><br># 2) Copy .terraformrc<br>cd $PROJECT_ROOT/terraform-provider-terratowns<br>cp $PROJECT_ROOT/terraformrc /home/gitpod/.terraformrc<br><br># 3) Delete existing binary file<br>rm -rf ~/.terraform.d/plugins<br>rm -rf $PROJECT_ROOT/.terraform<br>rm -rf $PROJECT_ROOT/.terraform.lock.hcl<br><br># 4) Build then copy to specified locations<br>go build -o $PLUGIN_NAME<br>mkdir -p $PLUGIN_DIR/x86_64/<br>mkdir -p $PLUGIN_DIR/linux_amd64/<br>cp $PLUGIN_NAME $PLUGIN_DIR/x86_64 <br>cp $PLUGIN_NAME $PLUGIN_DIR/linux_amd64</pre><p><strong>📑 Andrew’s notes: x86_64 and amd64</strong></p><p>When we build binaries, we have to build them based on the specific chipset of our computer. The chipset type (example: x86_64, linux_amd64) can vary depeding on your computer’s OS and model (Windows, Mac, Linux, etc). Hence Andrew is just putting both x86_64 andlinux_amd64 to make sure it works as it’s either of the two for our gitpod workspace.</p><h3>4. go.mod</h3><p>go.mod is automatically genrated when we run go mod init. Andrew found the generated file useless (😆) so he decides to write it on our own.</p><ul><li>replace function replaces PROJECT_PATH to whatever path you specify.</li><li>replace [PROJECT_PATH] =&gt; [YOUR_LOCAL_PATH]</li></ul><pre>// go.mod<br>module github.com/ExamProCo/terraform-provider-terratowns<br><br>go 1.20<br><br>// This is specific to our local machine.<br>replace github.com/ExamProCo/terraform-provider-terratowns =&gt; /workspace/terraform-beginner-bootcamp-2023/terraform-provider-terratowns<br></pre><p>Andrew tests compiling the custom provider by running the command:</p><pre>go build -o terraform-provider-terratowns_v1.0.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*U5XJ-aiP4EAxBrZ6kxwE0g.png" /><figcaption>The binary has been generated. Our code works!</figcaption></figure><p>In case you are missing a plugin, go will tell you it’s missing and give you the command to install it. The code looks like this:</p><pre>go get github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema</pre><h3>Notes</h3><ul><li>In the context of Terraform, a “provider” is a way to interact with APIs and resources.</li><li>There’s a schema at the provider level (<a href="https://terratowns.cloud/">terratowns.cloud</a>) and schema at the resource level (terratown homes).</li><li>Schemas have the fields that we have to fill to define the provider and resource.</li><li>go mod init initialises the directory for our terraform provider in Go (this is how you initialise any go project).</li><li>The primary purpose of using the import fmt is to use formatted go IO functions.</li><li>go build generates a binary file (.bin).</li></ul><h3>Resources</h3><h4>Bootcamp</h4><ul><li>Video: <a href="https://www.youtube.com/watch?v=pU8-AOhrIV8&amp;list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;index=52&amp;ab_channel=ExamPro">2 1 0 Setup Skeleton for Custom Terraform Provider</a></li><li>My feature branch: <a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/tree/2.1.0">2 1 0: 47-terratowns-provider</a></li><li>My complete <a href="https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-complete-learning-journal-3640cebc74b5">Learning Journal</a></li></ul><h4>Terraform</h4><ul><li><a href="https://developer.hashicorp.com/terraform/tutorials/providers">Call APIs with Custom SDK Providers</a></li><li><a href="https://www.hashicorp.com/blog/writing-custom-terraform-providers">Writing Custom Terraform Providers</a></li></ul><h4>Brilliant</h4><ul><li><a href="https://medium.com/weareservian/terraform-local-providers-and-registry-mirror-configuration-b963117dfffa">Terraform Local Providers and Registry Mirror Configuration</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb7938b0d3b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Cloud Project Bootcamp with Andrew Brown — Week 2 Live Streaming (Multiverse of Madness…]]></title>
            <link>https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-week-2-live-streaming-multiverse-of-madness-ab8c7cb7e761?source=rss-e6c0ecbdd9d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab8c7cb7e761</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[terraform-cloud]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[version-control]]></category>
            <dc:creator><![CDATA[Gwen Leigh]]></dc:creator>
            <pubDate>Thu, 12 Oct 2023 07:07:17 GMT</pubDate>
            <atom:updated>2023-10-12T07:07:17.136Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform Cloud Project Bootcamp with Andrew Brown — Week 2 Live Streaming (Multiverse of Madness Edition)</h3><p>This article is part of my Terraform journey with <a href="https://www.exampro.co/ter-cpb-001">Terraform Bootcamp</a> by <a href="https://www.linkedin.com/in/andrew-wc-brown/">Andrew Brown</a> and <a href="https://www.linkedin.com/in/abayko/">Andrew Bayko</a> with <a href="https://www.linkedin.com/in/chrisfwilliams/">Chris Williams</a> and <a href="https://www.youtube.com/@GiftedLane">Shala</a>.</p><p>My wild career adventure into Cloud Computing continues with Andrews, and I highly, highly recommend you to come join us if you are interested. Check out <a href="https://www.youtube.com/@ExamProChannel">Andrews’ free youtube learning contents</a>. You can also <a href="https://www.exampro.co/">buy some paid courses here</a> to support their good cause.</p><h3>Agenda</h3><p>Video here: <a href="https://www.youtube.com/watch?v=pWCejw1Mk50&amp;list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;ab_channel=ExamPro">Terraform Beginner Bootcamp Week-2</a></p><h4><a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/compare/main...terraform-cloud">Issue # Goals</a></h4><p>So what are we doing through this live stream? We practice using Terraform Cloud in three execution modes:</p><ul><li>Run locally</li><li>Run remotely via Terraform Cloud</li><li>Run remotely via Terraform Cloud using VCS (Version Control System)</li></ul><p>In Andrew’s words:</p><blockquote>In week 2 live-stream we are just doing click-ops in AWS of what infrastructure we are setting up. It’s just to help people understand the resources we are creating via Terraform.</blockquote><ul><li>✅ 1) Use two Execution Modes on Terraform Cloud: remote &amp; local</li><li>✅ 2) Make changes to for-local code to run it remotely via TC</li><li>✅ 3) Repeat 1–2</li></ul><h4>Workflow</h4><ul><li>📑 Notes: <a href="#8954">Current Week-2 work setup</a></li><li>✅ 1) <a href="#74c9">Local execution test</a></li><li>✅ 2) <a href="#d0a3">Remote execution on Terraform Cloud</a></li><li>✅ 3) <a href="#3741">via Terraform Cloud with VCS</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-L7HWwtL-5w0vRDiJd2v9w.png" /><figcaption>My diagram work was featured during livestream!!! 😍❤️❤️</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwEWGP1xTOs-0SKC9N7uXw.png" /><figcaption>🍯 🏡</figcaption></figure><h3>📑 Notes</h3><h4>Current Week-2 work setup</h4><p>When we run terraform locally (Gitpod workspace in case you are following our Andrews’ bootcamp), the following is how things work under the hood:</p><ul><li>Terraform generates out the state file (terraform.tfstate) <strong>locally</strong>.</li><li>This state file will be <strong>gone </strong>once you destroy the Gitpod workspace.</li><li>To <strong>persist </strong>it, we can have <strong>Terraform Cloud</strong> manage the state file.</li><li>In this case, however, it is still <strong>Gitpod workspace</strong> that executes terraform plan &amp; terraform apply.</li><li>In this setup, the advantage is that the execution is fast as Terraform Cloud doesn’t have to spin up its own containers with Compute environment for terraform.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ut4uiwhk-IS-jOtK-Wf7Q.png" /></figure><h3>1. Local execution test</h3><p>We branch out to a new feature branch called terraform-cloud for this Week-2 live stream:</p><pre>git checkout -b terraform-cloud</pre><p>We are testing terraform with minimal AWS resource configuration. We comment out the following first:</p><ul><li>Entire resource-cdn.tf in the modules/terrahouse_aws</li><li>the Condition inside bucket_policy in module/terrahouse_aws/resource-storage.tf</li></ul><pre>resource &quot;aws_s3_bucket_policy&quot; &quot;bucket_policy&quot; {<br>    bucket = aws_s3_bucket.website_bucket.bucket<br>    # policy = data.aws_iam_policy_document.allow_access_from_another_account.json<br>    policy = jsonencode({<br>      &quot;Version&quot; = &quot;2012-10-17&quot;,<br>      &quot;Statement&quot; = {<br>        &quot;Sid&quot;: &quot;AllowCloudFrontServicePrincipalReadOnly&quot;,<br>        &quot;Effect&quot;: &quot;Allow&quot;,<br>        &quot;Principal&quot; = {<br>            &quot;Service&quot;: &quot;cloudfront.amazonaws.com&quot;<br>        },<br>        &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>        &quot;Resource&quot;: &quot;arn:aws:s3:::${aws_s3_bucket.website_bucket.id}/*&quot;,<br>        # &quot;Condition&quot; = {<br>        #   &quot;StringEquals&quot; = {<br>        #     &quot;AWS:SourceArn&quot;: &quot;arn:aws:cloudfront::${data.aws_caller_identity.current.account_id}:distribution/${aws_cloudfront_distribution.s3_distribution.id}&quot; # .current.arn<br>        #   }<br>        # }<br>      }<br>    })<br>}</pre><p>Then run:</p><pre>terraform init<br>terraform plan</pre><pre>terraform apply</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgHGlubNTciPboMa6IKpqQ.png" /><figcaption>My comment is featured during the live stream! Andrew asked for +5 and my response is binary btw 😃</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNt4QLoyj2z1OMoVyhmZIg.png" /></figure><h3>2. Remote execution on Terraform Cloud</h3><h4>Execution Mode: local &amp; remote</h4><p>When executing terraform locally, we have all the environment variables stored locally and our machine knows where to find them. However, once we manage our state via Terraform Cloud (TC), TC has to have them so it can execute terraform using its own machine (compute resources).</p><p>So we have to set variables on TC. You can find the Variables option on the left pane at the workspace-level settings. Note that the Variables option is dynamic, so it disappears once you set Execution Mode to local.</p><ul><li>When we execute terraform locally, our local machine has the AWS credentials stored locally so we can safely provision resources on AWS cloud.</li><li>When we execute terraform remotely viaTerraform Cloud (TC), TC needs the credentials to access and provision AWS resources on AWS cloud as terraform runs through TC’s own compute envrionment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCWfAJ26CpokFeYLvynGMw.png" /></figure><h4>Set environment variables on Terraform Cloud</h4><ul><li>Set environment variables for the terraform-cloud workspace on TC.</li><li>Add the resource-specific local variables as terraform variables on TC.</li><li>Then run terraform init &amp; terraform plan</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rm1pspIDFHR6rtuQ-DTi6w.png" /></figure><h3>3. via Terraform Cloud with VCS</h3><p>VCS is a Version Control System (such as GitHub, GitLab, or Bitbucket) that takes care of updates and changes to your code as your project develops. We can connect our Terraform Cloud to manage the version control and terraform runs in a more organised manner. Note that, once our workspace is linked to a VCS, we have to commit &amp; push our updates to Github (that is, VCS). This will trigger Terraform Cloud, and then TC will run to reflect the changes to the infrastructure.</p><p>We are now connecting to version control:</p><ul><li>1) Workspace &gt; Settings &gt; Version Control</li><li>2) Click Connect to version control &gt; Select Version control workflow</li><li>3) Then select Github from the top-down menu</li><li>4) Select the repository (terraform-beginner-bootcamp-2023)</li></ul><p>As for the rest of the settings, we would like to use the default configuration. Just know that there are multiple ways to configure the Remote Execution envrionment.</p><ul><li>Apply Method: Auto apply &amp; Manual apply</li><li>VCS Triggers <br>- Always trigger runs<br>- Only trigger runs when files in specified paths change</li></ul><p>For visual guide, I list the screenshots of the configuration steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CWwzm7ND5DD0MR8TTQAFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mx9OEzm9-arJBLBUlwPCfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s66enGfuxmCkpS1gwESfJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1GJ0RZkMt9qCwDEYF2nXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qH28E2AsILeRUQz9pmW1KA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dyulsBrhE5zf_7_cHP8v5g.png" /></figure><p>Now that we are ready with the remote run set up, we want to execute it. So we make some changes to the code and terraform apply. However, the run fails. Check out the status on your TC console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOzS-N6EHxOr-sMtvqe2cA.png" /></figure><p>What does this mean? It means :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeTPjZbunfo1pmbpNlhL3A.png" /></figure><p>Also, there are some errors in the variable configuration. These errors are not necessarily “errors” per se cause they are correct for local execution. However, the remote execution requires a bit different configuration so we have to adjust the code accordingly.</p><p>Andrew makes some changes to the code to fix it. Make sure that you commit &amp; push to trigger Terraform Cloud to run:</p><pre>resource &quot;aws_s3_object&quot; &quot;index_html&quot; {<br>  bucket = aws_s3_bucket.website_bucket.bucket<br>  key    = &quot;index.html&quot;<br>- source = var.index_html_filepath<br>+ source = &quot;${path.root}${var.index_html_filepath}&quot;<br>  content_type = &quot;text/html&quot;<br><br>- etag   = filemd5(&quot;${path.root}/public/index.html&quot;)<br>+ etag   = filemd5(&quot;${path.root}${var.index_html_filepath}&quot;)<br>}<br><br>resource &quot;aws_s3_object&quot; &quot;error_html&quot; {<br>  bucket = aws_s3_bucket.website_bucket.bucket<br>  key    = &quot;error.html&quot;<br>- source = var.error_html_filepath<br>+ source = &quot;${path.root}${var.error_html_filepath}&quot;<br>  content_type = &quot;text/html&quot;<br><br>- etag   = filemd5(&quot;${path.root}/public/error.html&quot;)<br>+ etag   = filemd5(&quot;${path.root}${var.error_html_filepath}&quot;)<br>}</pre><p>However, the runs still fail. On the TC console, click on the specific run that failed to see the details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Cr6Ruil6J5EeDpFQUJe7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPitnSj6FvVd-vWKtTOroQ.png" /></figure><p>In my case, the region information was missing. I added the information and the remote run succeeded.</p><pre>provider &quot;aws&quot; {<br>+  region = &quot;us-east-1&quot;<br>}</pre><pre>git add provider.tf<br>git commit -m &quot;Added region&quot;<br>git push</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9rizGfQOKErAFsnjep3FQ.png" /></figure><p>To wrap up, we can destroy the infrastructure using the Console too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZA7G8ZuLBOKoxmmMDqg6Q.png" /></figure><p>Now this is the end of our hands-on live stream session to practice infrastructure provisioning executions using Terraform Cloud. From the next videos on, we will work back on the Terrahouses to launch them on the TerraTowns. See you in the next one! 👋</p><h3>Chris’ insights (<a href="https://youtu.be/pWCejw1Mk50?t=4440">video</a>)</h3><ul><li>In a production/enterprise environment, what happens in reality is that they don’t run terraform plan &amp; terraform apply from their desktop or local workstation.</li><li>Their VCS (Version Control System like Github) is connected to Terraform Cloud, and every time they commit, this commit triggers terraform plan &amp; terraform apply.</li><li>The change to your IaC is propagated through Github, through Terraform Cloud, then applies to my environment.</li></ul><h3>Good Fun Moments Gallary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQ7zSw_AUQvlbnflK-S2pg.png" /><figcaption>One of my favourite moments during this stream. It was a good laugh :D</figcaption></figure><h3>Resources</h3><h4>Bootcamp</h4><ul><li>Video: <a href="https://www.youtube.com/watch?v=pWCejw1Mk50&amp;list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A&amp;ab_channel=ExamPro">Terraform Beginner Bootcamp Week-2</a></li><li>My feature branch: <a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/tree/terraform-cloud">terraform-cloud</a></li><li>My complete <a href="https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-complete-learning-journal-3640cebc74b5">Learning Journal</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab8c7cb7e761" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Cloud Project Bootcamp with Andrew Brown — 2.0.0 Setting up Terratowns Mock Web Server]]></title>
            <link>https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-2-0-0-setting-up-terratowns-mock-web-server-2471c42799d0?source=rss-e6c0ecbdd9d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2471c42799d0</guid>
            <category><![CDATA[sinatra]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Gwen Leigh]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 08:32:37 GMT</pubDate>
            <atom:updated>2023-10-09T17:15:09.601Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform Cloud Project Bootcamp with Andrew Brown — 2.0.0 Setting up Terratowns Mock Web Server</h3><p>This article is part of my Terraform journey with <a href="https://www.exampro.co/ter-cpb-001">Terraform Bootcamp</a> by <a href="https://www.exampro.co/">Andrew Brown and Andrew Bayko</a> with <a href="https://www.linkedin.com/in/chrisfwilliams/">Chris Williams</a> and <a href="https://www.youtube.com/@GiftedLane">Shala</a>.</p><p>My wild career adventure into Cloud Computing continues with Andrews, and I highly, highly recommend you to come join us if you are interested. Check out <a href="https://www.youtube.com/@ExamProChannel">Andrews’ free youtube learning contents</a>. You can also <a href="https://www.exampro.co/">buy some paid courses here</a> to support their good cause.</p><h3>Agenda</h3><p>Video here: <a href="https://youtu.be/3TgEa1N4BGg?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A">2 0 0 Setting up Terratowns Mock Web Server</a></p><h4><a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/issues/42">Issue #42 Goals</a></h4><ul><li>✅ 1) Download Terratowns mock server into our repo</li></ul><h4>Workflow</h4><ul><li>✅ 1) Initial Setup</li><li>✅ 2) Run, understand &amp; document server.rb</li><li>✅ 3) Test if endpoints work correctly</li></ul><h3>1. Initial Setup</h3><pre>git clone https://github.com/ExamProCo/terratowns_mock_server.git<br><br>cd terratowns_mock_server<br>ls -la <br><br># We should remove the .git tracker. <br># Make sure that you are inside the terratowns_mock_server directory.<br># Otherwise you can just blow away your own repo and the whole work.<br>rm -rf .git</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_b3eF4xQWjCTUSXFAapZg.png" /></figure><p>Now, move the sinatra server setup from ./terratowns_mock_server/gitpod.yaml to gitpod.yaml at root.</p><pre>  - name: sinatra<br>    before: | <br>      cd $PROJECT_ROOT<br>      cd terratowns_mock_server<br>      bundle install<br>      bundle exec ruby server.rb </pre><p>Then change the name of the bin directory in terratowns_mock_server to terratowns, then move it to our bin directory at root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*GvuHlLI2oSRaILClEaUAdg.png" /></figure><p>Now, commit the code so that we can launch a new gitpod workspace to test if the Ruby server runs correctly on launch.</p><h3>2. Run, understand &amp; document server.rb</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bh4MiSjPVBOF7helaiQfOg.png" /><figcaption>A minimal light-weight <a href="https://sinatrarb.com/">web application library</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QugpGo8_HUcEUWxGlehpEA.png" /><figcaption>The sinatra server is running on Gitpod workspace launch.</figcaption></figure><p>Andrew prepared in advance the ruby server code we will use for building our TerraHouses. A good part of this video tutorial is dedicated to understanding what this server code does and documenting comments on what each line does. I’m not going to paste it here. You can find the code <a href="https://github.com/omenking/terraform-beginner-bootcamp-2023/blob/45-terratowns-mock-server/terratowns_mock_server/server.rb">here</a> instead.</p><h3>3. Test if endpoints work correctly</h3><p>You really have to follow the video hands-on as Andrew makes minor changes and tweaks around the code here and there for endpoints testing.</p><p>In the sinatra server terminal, you can interact with the server directly. Try running the following commands:</p><pre>home<br>home.domain_name<br>payload<br>home<br>$home[:domain_name]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LT10FFIBBGj1Bi0mfXXz3g.png" /></figure><p>While working through the server modification, we use the following commands to verify if the endpoints do what they are intended to do:</p><pre>./bin/terratowns/create<br>./bin/terratowns/read   [UUID]<br>./bin/terratowns/update [UUID]<br>./bin/terratowns/delete [UUID]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sN9IiwzK5mkc6Q7ZSnKDZA.png" /></figure><p>Andrew modifies the #DELETE operation code to print the UUID that is deleted.</p><pre>    # delete from mock database<br>-   uuid = $home[&#39;uuid&#39;]<br>+   uuid = $home[:uuid]<br>    $home = {}<br>-   { message: &quot;House deleted successfully&quot; }.to_json<br>+   { uuid: uuid }.to_json<br>  end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ZcVWID7hd5ny79-P5G_QA.png" /></figure><p>Now that the Mock Server is ready, we will move on to building our own custom provider in the next session.</p><h3>Notes</h3><ul><li>$variable in Ruby (dollar sign + variable name) means it’s a global variable.</li><li>The PUT method in web servers typically updates an existing resource.</li><li>bundle install command installs packages for Ruby.</li></ul><h3>Resources</h3><h4>Bootcamp</h4><ul><li>Video: <a href="https://youtu.be/3TgEa1N4BGg?list=PLBfufR7vyJJ4q5YCPl4o2XAzGRZUjuD-A">2 0 0 Setting up Terratowns Mock Web Server</a></li><li><a href="https://github.com/examProCo/terratowns_mock_server">ExamProCo Terratowns Mock Server Repo</a></li><li>My feature branch: <a href="https://github.com/mariachiinajar/terraform-beginner-bootcamp-2023/tree/45-terratowns-mock-server">45-terratowns-mock-server</a></li><li>My complete <a href="https://medium.com/@gwenleigh/terraform-cloud-project-bootcamp-with-andrew-brown-complete-learning-journal-3640cebc74b5">Learning Journal</a></li></ul><h4>Brilliant</h4><ul><li><a href="https://sinatrarb.com/">Sinatra server</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2471c42799d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>