<?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 Uncle Blythe on Medium]]></title>
        <description><![CDATA[Stories by Uncle Blythe on Medium]]></description>
        <link>https://medium.com/@uncle.blythe?source=rss-fbb1c9df95de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cNAg0pILR2DWF7fb.jpg</url>
            <title>Stories by Uncle Blythe on Medium</title>
            <link>https://medium.com/@uncle.blythe?source=rss-fbb1c9df95de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 21:59:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@uncle.blythe/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[Rails Active model with legacy database]]></title>
            <link>https://medium.com/the-investments-monster/rails-active-model-with-legacy-database-41aaed78e52d?source=rss-fbb1c9df95de------2</link>
            <guid isPermaLink="false">https://medium.com/p/41aaed78e52d</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[legacy]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Uncle Blythe]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 06:35:17 GMT</pubDate>
            <atom:updated>2024-03-08T06:35:17.532Z</atom:updated>
            <content:encoded><![CDATA[<p>working with legacy project that the database schema have “slice” in column name. the name is conflict with instand publie method in Active model.</p><p>Error from rails.</p><blockquote>slice is defined by Active Record. Check to make sure that you don’t have an attribute or method with the same name</blockquote><p>Simple Database schema</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*aEIEw-wLrEQpYKNuP3rV9A.png" /></figure><p>Rails active model. The slice method was promote from Rails 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYBfULOcweRozzASKER6Xw.png" /></figure><p>There is 2 ways to reslove this.</p><ol><li>override instance_method_already_implemented? to avoid conflict</li></ol><pre># app/models/concerns/attributes_concern.rb<br><br>module AttributesConcern<br>  extend ActiveSupport::Concern<br><br>  class_methods do<br>    def instance_method_already_implemented?(method_name)<br>      begin<br>        return super(method_name)<br>      rescue ActiveRecord::DangerousAttributeError<br>        return true<br>      end<br>      false<br>    end<br>  end<br>end<br><br># include AttributesConcern to specify model.rb</pre><p>2. create alias_attribute.</p><pre>class Order &lt; ApplicationRecord<br><br>    include AttributesConcern<br><br>    self.table_name = &#39;order&#39;<br>    self.primary_key = &#39;invoice_id&#39;<br>    self.record_timestamps = false<br><br>    alias_attribute :order_slice, :slice<br><br>end</pre><p>Happy hacking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41aaed78e52d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-investments-monster/rails-active-model-with-legacy-database-41aaed78e52d">Rails Active model with legacy database</a> was originally published in <a href="https://medium.com/the-investments-monster">The Investments Monster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure API with JWT for Python, Golang and Nodejs]]></title>
            <link>https://medium.com/the-investments-monster/secure-api-with-jwt-for-python-golang-and-nodejs-2e63d040e08?source=rss-fbb1c9df95de------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e63d040e08</guid>
            <category><![CDATA[dev]]></category>
            <dc:creator><![CDATA[Uncle Blythe]]></dc:creator>
            <pubDate>Sat, 07 Aug 2021 15:13:15 GMT</pubDate>
            <atom:updated>2021-08-11T10:03:27.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*MV27EEa4rZm4U-0lBRM9Zw.png" /></figure><p>As you know the JSON Web Tokens (<a href="https://jwt.io/">JWT</a>) is most popular that follow industry standard <a href="https://datatracker.ietf.org/doc/html/rfc7519">RFC 7519</a> for make your api securely.</p><p><strong>Python<br></strong>Here i going to show how apply jwt with python flask web framwork and pyjwt. first of all we need to install libary before implement it.<br><a href="https://pyjwt.readthedocs.io/en/latest/installation.html">Pyjwt document</a> , <a href="https://flask.palletsprojects.com/en/2.0.x/">Flask document</a></p><pre>pip install flask pyjwt</pre><p>Basic python jwt for encoding and decoding</p><pre><strong>client_id </strong>= &#39;123456&#39;<br><strong>JWT_SECERT </strong>= &#39;my_secert&#39;<br><strong>exp </strong>= datetime.utcnow() + timedelta(hours=1)<br><strong>encoded </strong>= <strong>jwt</strong>.encode({&#39;client_id&#39;: client_id, &#39;exp&#39;: exp}, JWT_SECERT, algorithm=&#39;HS256&#39;)</pre><pre>// output <br>encoded = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGllbnRfaWQiOiJBUFAgSldUIiwiZXhwIjoxNjI4MzUwNDk5fQ.YzUO_deXSkIce2N_a915dKNzajP2PbkGVoR8RgHdt3s</pre><p>to decoding</p><pre>decode = jwt.decode(encoded, JWT_SECERT, algorithms=[&quot;HS256&quot;])</pre><p>Integrate JWT with Flask</p><pre># app.py<br>from flask import Flask, request, jsonify<br>import jwt<br>from datetime import datetime, timedelta<br>from middleware import require_login</pre><pre>app = Flask(__name__)<br>JWT_SECERT = &#39;my_secert&#39;</pre><pre>@app.route(&#39;/&#39;)<br>def index():<br> return &#39;Hello Flask&#39;</pre><pre>@app.route(&#39;/api/login&#39;, methods=[&#39;POST&#39;])<br>def <strong>login</strong>():<br> payload = request.json<br> exp = datetime.utcnow() + timedelta(hours=1)<br> <strong>encoded = jwt.encode({&#39;client_id&#39;: payload[&#39;client_id&#39;], &quot;exp&quot;: exp}, JWT_SECERT, algorithm=&#39;HS256&#39;)</strong><br> res = {<br>  &#39;status&#39;: 200,<br>  &#39;expireIn&#39;: exp.timestamp(),<br>  &#39;token&#39;: encoded.decode(&#39;utf-8&#39;)<br> }<br> return res</pre><pre>@app.route(&#39;/api/protect&#39;)<br><strong>@require_login</strong><br>def protect():<br> payload = request.json<br> print(payload)<br> return &#39;Protext API&#39;</pre><pre>if __name__ == &#39;__main__&#39;:<br> app.run(host=&#39;0.0.0.0&#39;, port=5000, debug=True)</pre><p>Here we need to implement python decorators as a middleware to verify token after client call to protect api</p><pre># middleware.py<br>from functools import wraps<br>from flask import redirect, url_for, session, request, jsonify<br>import jwt</pre><pre>JWT_SECERT = &#39;my_secert&#39;</pre><pre>def require_login(func): <br> @wraps(func) <br> def wrapper(*args, **kwargs):<br>  if not &#39;<strong>authorization</strong>&#39; in request.headers: <br>   return {&#39;error&#39;:&#39;permission denied&#39;}, 403<br>  <strong>token = request.headers[&#39;authorization&#39;].split(&#39; &#39;)[1]</strong><br>  try:<br>   <strong>decode = jwt.decode(token, JWT_SECERT, algorithms=[&quot;HS256&quot;])</strong><br>   request.json[&#39;jwt_token&#39;] = decode<br>  except Exception as e:<br>   print(&quot;[require_login]&quot;, e)<br>   return {&#39;error&#39;: e}, 403<br>  return func(*args, **kwargs) <br> return wrapper</pre><p>Testing API with CURLs, Login with sending client id to service</p><pre>curl --location --request POST &#39;<a href="http://localhost:5000/api/login&#39;">http://localhost:5000/api/login&#39;</a> \<br>--header &#39;Content-Type: application/json&#39; \<br>--data-raw &#39;{<br>    &quot;client_id&quot;: &quot;APP JWT&quot;<br>}&#39;</pre><p>Access protect api with token</p><pre>curl --location --request GET &#39;<a href="http://localhost:5000/api/protect&#39;">http://localhost:5000/api/protect&#39;</a> \<br>--header &#39;<strong>Authorization: Bearer</strong> <strong>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGllbnRfaWQiOiJBUFAgSldUIiwiZXhwIjoxNjI4MzUwNDk5fQ.YzUO_deXSkIce2N_a915dKNzajP2PbkGVoR8RgHdt3s</strong>&#39; \<br>--header &#39;Content-Type: application/json&#39;</pre><p><strong>Golang<br></strong>In golang i like gin so much and i going to use gin and gin-jwt to mark api</p><pre>package main</pre><pre>import (<br> jwt &quot;github.com/appleboy/gin-jwt/v2&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;log&quot;<br> &quot;time&quot;<br>)</pre><pre>type login struct {<br> Username string `form:&quot;username&quot; json:&quot;username&quot; binding:&quot;required&quot;`<br> Password string `form:&quot;password&quot; json:&quot;password&quot; binding:&quot;required&quot;`<br>}</pre><pre>var identityKey = &quot;id&quot;<br>var jwtSecret = []byte(&quot;my_secret&quot;)</pre><pre>func helloHandler(c *gin.Context) {<br> claims := jwt.ExtractClaims(c)<br> log.Println(claims)<br> user, _ := c.Get(identityKey)<br> c.JSON(200, gin.H{<br>  &quot;userID&quot;:   claims[identityKey],<br>  &quot;userName&quot;: user.(*User).UserName,<br>  &quot;text&quot;:     &quot;Hello World.&quot;,<br> })<br>}</pre><pre>type User struct {<br> UserName  string<br> FirstName string<br> LastName  string<br>}</pre><pre>func main() {<br> r := gin.Default()<br> // the jwt middleware<br> authMiddleware, err := jwt.New(&amp;jwt.GinJWTMiddleware{<br>  Realm:       &quot;test zone&quot;,<br>  Key:         jwtSecret,<br>  Timeout:     time.Hour,<br>  MaxRefresh:  time.Hour,<br>  IdentityKey: identityKey,<br>  PayloadFunc: func(data interface{}) jwt.MapClaims {<br>   if v, ok := data.(*User); ok {<br>    return jwt.MapClaims{<br>     identityKey: v.UserName,<br>    }<br>   }<br>   return jwt.MapClaims{}<br>  },<br>  IdentityHandler: func(c *gin.Context) interface{} {<br>   claims := jwt.ExtractClaims(c)<br>   return &amp;User{<br>    UserName: claims[identityKey].(string),<br>   }<br>  },<br>  Authenticator: func(c *gin.Context) (interface{}, error) {<br>   var loginVals login<br>   if err := c.ShouldBind(&amp;loginVals); err != nil {<br>    return &quot;&quot;, jwt.ErrMissingLoginValues<br>   }<br>   userID := loginVals.Username<br>   password := loginVals.Password</pre><pre>if (userID == &quot;admin&quot; &amp;&amp; password == &quot;admin&quot;) || (userID == &quot;test&quot; &amp;&amp; password == &quot;test&quot;) {<br>    return &amp;User{<br>     UserName:  userID,<br>     LastName:  &quot;Yoojun&quot;,<br>     FirstName: &quot;Naruedol&quot;,<br>    }, nil<br>   }</pre><pre>return nil, jwt.ErrFailedAuthentication<br>  },<br>  Authorizator: func(data interface{}, c *gin.Context) bool {<br>   if v, ok := data.(*User); ok &amp;&amp; v.UserName == &quot;admin&quot; {<br>    return true<br>   }</pre><pre>return false<br>  },<br>  Unauthorized: func(c *gin.Context, code int, message string) {<br>   c.JSON(code, gin.H{<br>    &quot;code&quot;:    code,<br>    &quot;message&quot;: message,<br>   })<br>  },<br>  TokenLookup:   &quot;header: Authorization, query: token, cookie: jwt&quot;,<br>  TokenHeadName: &quot;Bearer&quot;,<br>  TimeFunc:      time.Now,<br> })<br> if err != nil {<br>  log.Fatal(&quot;JWT Error:&quot; + err.Error())<br> }</pre><pre>if err = authMiddleware.MiddlewareInit(); err != nil {<br>  log.Fatal(&quot;authMiddleware.MiddlewareInit() Error:&quot; + err.Error())<br> }</pre><pre>r.POST(&quot;/login&quot;, authMiddleware.LoginHandler)<br> r.NoRoute(authMiddleware.MiddlewareFunc(), func(c *gin.Context) {<br>  claims := jwt.ExtractClaims(c)<br>  log.Printf(&quot;NoRoute claims: %#v\n&quot;, claims)<br>  c.JSON(404, gin.H{&quot;code&quot;: &quot;PAGE_NOT_FOUND&quot;, &quot;message&quot;: &quot;Page not found&quot;})<br> })<br> auth := r.Group(&quot;/auth&quot;)<br> auth.GET(&quot;/refresh_token&quot;, authMiddleware.RefreshHandler)<br> auth.Use(authMiddleware.MiddlewareFunc())<br> {<br>  auth.GET(&quot;/hello&quot;, helloHandler)<br> }</pre><pre>r.GET(&quot;/ping&quot;, func(c *gin.Context) {<br>  c.JSON(200, gin.H{<br>   &quot;message&quot;: &quot;pong&quot;,<br>  })<br> })<br> r.Run(&quot;:3000&quot;)<br>}</pre><p><strong>Nodejs</strong><br>I use jsonwebtoken and express here</p><pre>// package.json<br>{<br>  &quot;name&quot;: &quot;express-with-jwt&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;nodemon index.js&quot;,<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;^4.17.1&quot;,<br>    &quot;jsonwebtoken&quot;: &quot;^8.5.1&quot;<br>  }<br>}</pre><p>Implement jsonwebtoken with express</p><pre>const express = require(&#39;express&#39;)<br>const app = express()<br>const jwt = require(&#39;jsonwebtoken&#39;)</pre><pre>app.use(express.json())</pre><pre>const JWT_SECERT = &#39;my_secert&#39;</pre><pre>const tokenHandler = (req, res, next) =&gt; {<br> const bearerHeader = req.headers[&#39;authorization&#39;]<br> if (typeof bearerHeader !== &#39;undefined&#39;) {<br>  token = bearerHeader.split(&#39; &#39;)[1]<br>  jwt.verify(token, JWT_SECERT, (err, decoded) =&gt; {<br>   if (err) {<br>    res.status(403)<br>    res.json(err)<br>   } else {<br>    req.token = {<br>     token,<br>     decoded,<br>    }<br>   }<br>  })<br>  next()<br> } else {<br>  res.sendStatus(403)<br> }<br>}</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br> res.send(&#39;Hello World&#39;)<br>})</pre><pre>app.post(&#39;/api/login&#39;, (req, res) =&gt; {<br> const user = { id: 1 }<br> const token = jwt.sign({ user }, JWT_SECERT, { expiresIn: 120 })<br> res.json({<br>  token,<br> })<br>})</pre><pre>app.post(&#39;/api&#39;, (req, res) =&gt; {<br> console.log(req.body)<br> res.json({<br>  text: &#39;My Api&#39;,<br> })<br>})</pre><pre>app.post(&#39;/api/protected&#39;, tokenHandler, (req, res) =&gt; {<br> res.json({<br>  text: &#39;This is protected Api&#39;,<br> })<br>})</pre><pre>app.listen(3000, () =&gt; {<br> console.log(&#39;The Applicaiton is listening on port 3000&#39;)<br>})</pre><p>The JWT have more Claim names support many propose for register token</p><ul><li>“exp” (Expiration Time) Claim</li><li>“nbf” (Not Before Time) Claim</li><li>“iss” (Issuer) Claim</li><li>“aud” (Audience) Claim</li><li>“iat” (Issued At) Claim</li></ul><p>Read me details in <a href="https://jwt.io/introduction">JWT.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e63d040e08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-investments-monster/secure-api-with-jwt-for-python-golang-and-nodejs-2e63d040e08">Secure API with JWT for Python, Golang and Nodejs</a> was originally published in <a href="https://medium.com/the-investments-monster">The Investments Monster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup Kubernetes cluster with RKE and Rancher]]></title>
            <link>https://medium.com/the-investments-monster/how-to-setup-kubernetes-cluster-with-rke-and-rancher-e549f8d9b1ab?source=rss-fbb1c9df95de------2</link>
            <guid isPermaLink="false">https://medium.com/p/e549f8d9b1ab</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Uncle Blythe]]></dc:creator>
            <pubDate>Tue, 06 Jul 2021 14:52:17 GMT</pubDate>
            <atom:updated>2021-07-06T14:52:17.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*oq8qqdC_BTQyVPksRWOvCQ.png" /><figcaption>mini kubernetes cluster with rke and rancher</figcaption></figure><h3>Requirements</h3><ul><li>5 VMs or Physical server for mini cluster<br>1 Master/Control plan (10.8.131.52)<br>2 Worker node (10.8.131.53, 10.8.131.54)<br>1 Cluster control (10.8.131.51)<br>1 Rancher GUI (10.8.131.55)</li><li>Floating IP for load balancer (10.8.131.99)</li><li>CentOS 7 Operation system, 4GB+ of memory and swap diabled</li><li>/var or /var/lib/docker should have minimum of 8–16GB free to provide for docker images storage</li><li>Docker CE installed on each node</li><li>RKE and Rancher on cluster control workstations</li></ul><h3><strong>Server preparation (all k8s nodes + cluster control)</strong></h3><p><strong><em>note</em></strong><em>: # is root, $ local user</em></p><p><strong>Docker installation<br></strong>refer: <a href="https://docs.docker.com/engine/install/centos/">Install Docker Engine on CentOS | Docker Documentation</a></p><pre># yum update –y <br># yum install -y yum-utils  <br># yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo <br># yum install docker-ce docker-ce-cli containerd.io <br># systemctl start docker  <br># systemctl enable docker</pre><p><strong>Disables SELinux</strong></p><pre># setenforce 0  <br># sed -i &#39;s/^SELINUX=enforcing$/SELINUX=permissive/&#39; /etc/selinux/config</pre><p><strong>Adding RKE user</strong></p><pre># useradd rke <br># passwd rke (password rke) <br># usermod –aG docker rke </pre><p>Verifications — rke user should execute docker command</p><pre># su - rke<br>(rke) $ docker ps<br>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES</pre><pre>(rke) $ dcoker version<br><br>Client: Docker Engine - Community<br> Version:           20.10.7<br> API version:       1.41<br> Go version:        go1.13.15<br> Git commit:        f0df350<br> Built:             Wed Jun  2 11:58:10 2021<br> OS/Arch:           linux/amd64<br> Context:           default<br> Experimental:      true</pre><pre>Server: Docker Engine - Community<br> Engine:<br>  Version:          20.10.7<br>  API version:      1.41 (minimum version 1.12)<br>  Go version:       go1.13.15<br>  Git commit:       b0f5bc3<br>  Built:            Wed Jun  2 11:56:35 2021<br>  OS/Arch:          linux/amd64<br>  Experimental:     false<br> containerd:<br>  Version:          1.4.6<br>  GitCommit:        d71fcd7d8303cbf684402823e425e9dd2e99285d<br> runc:<br>  Version:          1.0.0-rc95<br>  GitCommit:        b9ee9c6314599f1b4a7f497e1f1f856fe433d3b7<br> docker-init:<br>  Version:          0.19.0<br>  GitCommit:        de40ad0</pre><p><strong>Generate SSH-Key for rke user (cluster control workstation only)</strong></p><pre># su – rke <br>(rke) $ ssh-keygen <br>// Press enters all questions </pre><p>Copy to all k8s nodes</p><pre>(rke) $ ssh-copy-id rke@10.8.131.52 <br>(rke) $ ssh-copy-id rke@10.8.131.53 <br>(rke) $ ssh-copy-id rke@10.8.131.54</pre><h3>Kubernetes Cluster installation with RKE (cluster controll workstation only)</h3><p><strong>Installation rke tools<br></strong>refer: <a href="https://github.com/rancher/rke/#latest-release">GitHub — rancher/rke: Rancher Kubernetes Engine (RKE)</a></p><pre>(rke) $ wget https://github.com/rancher/rke/releases/download/v1.2.9/rke_linux-amd64 -O rke<br>(rke) $ chmod +x rke</pre><p><strong>Preparation Cluster.yml file<br></strong>to creating cluster with rke we need to define nodes role in cluster.yml file first. rke tools will looking on that file to create/remove cluster</p><pre>(rke) $ vim cluster.yml<br>nodes: <br>- address: 10.8.131.92<br>  user: rke <br>  role: <br>    - controlplane <br>    - etcd <br>  hostname_override: kor-devops52<br>- address: 10.8.131.93<br>  user: rke <br>  role: <br>    - worker <br>  hostname_override: kor-devops53<br>- address: 10.8.131.94<br>  user: rke <br>  role: <br>    - worker <br>  hostname_override: kor-devops54</pre><pre>kubernetes_version: v1.20.8-rancher1-1<br>network: <br>    plugin: canal</pre><p><strong>Setup Kubernetes cluster by rke tool</strong></p><pre>(rke) $ ls <br>rke        cluster.yml  <br>(rke) $ ./rke -d up</pre><pre>DEBU[0080] Cluster version [1.20.8-rancher1-1] needs to have kube-api audit log enabled<br>DEBU[0080] Enabling kube-api audit log for cluster version [v1.20.8-rancher1-1]<br>DEBU[0080] Host: 10.8.131.92 has role: controlplane<br>DEBU[0080] Host: 10.8.131.92 has role: etcd<br>DEBU[0080] Host: 10.8.131.93 has role: worker<br>DEBU[0080] Host: 10.8.131.94 has role: worker<br>INFO[0096] [addons] Executing deploy job rke-ingress-controller<br>DEBU[0096] Checking node list for node [kor-devops52], try #1<br>DEBU[0096] [k8s] waiting for job rke-ingress-controller-deploy-job to complete..<br>DEBU[0101] [k8s] Job rke-ingress-controller-deploy-job in namespace kube-system completed successfully<br>INFO[0101] [ingress] ingress controller nginx deployed successfully<br>INFO[0101] [addons] Setting up user addons<br>INFO[0101] [addons] no user addons defined<br>INFO[0101] Finished building Kubernetes cluster successfully</pre><p>If something wrong or fatal, check on each nodes. Try to logging fail container or remove kubelet service.</p><p><strong>Verifications, should have kube_config_cluster.yml created on that path</strong></p><pre>(rke) $ ls <br>cluster.rkestate cluster.yml kube_config_cluster.yml rke</pre><p><strong>Insetallation kubectl to control cluster (cluster control workstation only)<br></strong>refer: <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/">Install and Set Up kubectl on Linux | Kubernetes</a></p><p><strong><em>note</em></strong><em>: this article use Redhat</em></p><pre>(rke) $ cat &lt;&lt;EOF &gt; /etc/yum.repos.d/kubernetes.repo<br>[kubernetes]<br>name=Kubernetes<br>baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64<br>enabled=1<br>gpgcheck=1<br>repo_gpgcheck=1<br>gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg<br>EOF<br>(rke) $ yum install -y kubectl</pre><p><strong>Cluster Verifications</strong></p><pre>(rke) $ kubectl --kubeconfig $(pwd)/kube_config_cluster.yml get nodes -o wide<br>NAME           STATUS   ROLES               AGE     VERSION   INTERNAL-IP   EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION                CONTAINER-RUNTIME<br><strong>kor-devops52</strong>   Ready    <strong>controlplane,etcd </strong>  3m55s   v1.20.8   10.8.131.92   &lt;none&gt;        CentOS Linux 7 (Core)   3.10.0-957.5.1.el7.x86_64     docker://20.10.7<br><strong>kor-devops53</strong>   Ready    <strong>worker              </strong>3m53s   v1.20.8   10.8.131.93   &lt;none&gt;        CentOS Linux 7 (Core)   3.10.0-957.5.1.el7.x86_64     docker://20.10.7<br><strong>kor-devops54 </strong>  Ready    <strong>worker              </strong>3m51s   v1.20.8   10.8.131.94   &lt;none&gt;        CentOS Linux 7 (Core)   3.10.0-1160.31.1.el7.x86_64   docker://20.10.7</pre><p><strong>Setup MetalLB for Cluster loadbalancer on layer2 with Floating IP</strong><br>refer: <a href="https://metallb.universe.tf/installation/#installation-by-manifest">MetalLB, bare metal load-balancer for Kubernetes (installation)</a></p><pre>(rke) $ kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.10.2/manifests/namespace.yaml<br>(rke) $ kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.10.2/manifests/metallb.yaml</pre><p><strong>MetalLB configuration.<br></strong>refer<strong>: </strong><a href="https://metallb.universe.tf/configuration/#layer-2-configuration">MetalLB, bare metal load-balancer for Kubernetes (configuration)</a></p><pre>(rke) $ vim metallb.yml<br>apiVersion: v1<br>kind: ConfigMap <br>metadata:<br>  namespace: metallb-system<br>  name: config<br>data:<br>  config: |<br>    address-pools:<br>    - name: default<br>      protocol: layer2<br>      addresses:<br>      - 10.8.131.99-10.8.131.99</pre><p><strong>Apply metallb.yml configuration</strong></p><pre>(rke) $ kubectl --kubeconfig $(pwd)/kube_config_cluster.yml apply -f metallb.yml</pre><p><strong>Checking metallb service</strong></p><pre>(rke) $ kubectl --kubeconfig $(pwd)/kube_config_cluster.yml get pods –A</pre><pre>NAMESPACE        NAME                                       READY   STATUS      RESTARTS   AGE<br>ingress-nginx    default-http-backend-6977475d9b-65xwh      1/1     Running     0          26m<br>ingress-nginx    nginx-ingress-controller-4rpgr             1/1     Running     0          26m<br>ingress-nginx    nginx-ingress-controller-p259n             1/1     Running     0          26m<br>kube-system      calico-kube-controllers-7d5d95c8c9-j9zls   1/1     Running     0          26m<br>kube-system      canal-9nctm                                2/2     Running     0          26m<br>kube-system      canal-bttgp                                2/2     Running     0          26m<br>kube-system      canal-sk79j                                2/2     Running     0          26m<br>kube-system      coredns-55b58f978-cpt8j                    1/1     Running     0          26m<br>kube-system      coredns-55b58f978-jxsn7                    1/1     Running     0          24m<br>kube-system      coredns-autoscaler-76f8869cc9-hvmxh        1/1     Running     0          26m<br>kube-system      metrics-server-55fdd84cd4-cn25d            1/1     Running     0          26m<br>kube-system      rke-coredns-addon-deploy-job-t7xmn         0/1     Completed   0          26m<br>kube-system      rke-ingress-controller-deploy-job-d9fss    0/1     Completed   0          26m<br>kube-system      rke-metrics-addon-deploy-job-jtsdp         0/1     Completed   0          26m<br>kube-system      rke-network-plugin-deploy-job-hdtcp        0/1     Completed   0          26m<br>metallb-system   controller-6b78bff7d9-rqz48                1/1     Running     0          15m<br>metallb-system   speaker-jqgcr                              1/1     Running     0          15m<br>metallb-system   speaker-pxz4s                              1/1     Running     0          15m</pre><h3>Deployment with simple applications</h3><p>This step requires only kube_config_cluster.yml and kubectl. We can deploy an application anywhere. So that we can build auto CI/CD by setup new pipeline integrate with GitLab or any source code repository and then set up Gitlab Runner or Jenkins that can execute kubectl. Build image and ship to kubernetes cluster</p><p><strong>Prepare deployment file (just demonstrate only)<br></strong>3 sections :: Service, Deployment, HorizontalPodAutoscaler</p><pre>(rke) $ vim deployment.yml</pre><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>    labels:<br>        app: hellok8s<br>    name: hellok8s<br>    namespace: default<br>    annotations:<br>        metallb.universe.tf/allow-shared-ip: production-public-ip<br>spec:<br>    ports:<br>        - port: 8080<br>          protocol: TCP<br>          targetPort: 80<br>    selector:<br>        app: hellok8s<br>    type: LoadBalancer</pre><pre>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>    name: hellok8s<br>spec:<br>    selector:<br>        matchLabels:<br>            app: hellok8s<br>    replicas: 1<br>    template:<br>        metadata:<br>            labels:<br>                app: hellok8s<br>        spec:<br>            containers:<br>                - name: hellok8s<br>                  image: nginx:stable-alpine<br>                  resources:<br>                      requests:<br>                          cpu: &#39;20m&#39;<br>                  ports:<br>                      - containerPort: 80<br>                  env:<br>                      - name: TZ<br>                        value: Asia/Bangkok</pre><pre>---<br>apiVersion: autoscaling/v2beta2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>    name: hellok8s<br>spec:<br>    scaleTargetRef:<br>        apiVersion: apps/v1beta2<br>        kind: Deployment<br>        name: hellok8s<br>    minReplicas: 1<br>    maxReplicas: 4<br>    metrics:<br>        - type: Resource<br>          resource:<br>              name: cpu<br>              target:<br>                  type: Utilization<br>                  averageUtilization: 80</pre><p><strong>Deploy to kubernetes</strong></p><pre>(rke)$ kubectl --kubeconfig $(pwd)/kube_config_cluster.yml apply -f deployment.yml<br>service/hellok8s created<br>deployment.apps/hellok8s created<br>horizontalpodautoscaler.autoscaling/hellok8s created</pre><p>Checking an application service with kubectl</p><pre>(rke)$ kubectl --kubeconfig $(pwd)/kube_config_cluster.yml get all<br>NAME                           READY   STATUS         RESTARTS   AGE<br>pod/hellok8s-98fb9d67b-bdffn   1/1     Running        0          15s</pre><pre>NAME                 TYPE           CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE<br>service/hellok8s     LoadBalancer   10.43.254.44   10.8.131.99   8080:30599/TCP   15s<br>service/kubernetes   ClusterIP      10.43.0.1      &lt;none&gt;        443/TCP          121m</pre><pre>NAME                       READY   UP-TO-DATE   AVAILABLE   AGE<br>deployment.apps/hellok8s   0/1     1            0           15s</pre><pre>NAME                                 DESIRED   CURRENT   READY   AGE<br>replicaset.apps/hellok8s-98fb9d67b   1         1         0       15s</pre><pre>NAME                                           REFERENCE             TARGETS         MINPODS   MAXPODS   REPLICAS   AGE<br>horizontalpodautoscaler.autoscaling/hellok8s   Deployment/hellok8s   &lt;unknown&gt;/80%   1         4         0          15s</pre><p>Accessing an application with 10.8.131.99 (Floating-IP, External IP for Loadbalacer)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMu4ga_nHl8H0jxstnuwXQ.png" /><figcaption>simple web application with nginx run on kubernetes</figcaption></figure><h3>Setup Rancher GUI to control Kubernetes (optional)</h3><p>we can setup rancher gui at 10.8.131.55 (another machine) or same machine with cluster control<br>refer: <a href="https://rancher.com/docs/rancher/v2.x/en/installation/other-installation-methods/single-node-docker/">Rancher Docs: Installing Rancher on a Single Node Using Docker</a></p><pre># docker run -d --restart=unless-stopped -p 80:80 -p 443:443 --privileged rancher/rancher</pre><pre>Unable to find image &#39;rancher/rancher:latest&#39; locally<br>latest: Pulling from rancher/rancher<br>01bf7da0a88c: Pull complete<br>f3b4a5f15c7a: Pull complete<br>57ffbe87baa1: Pull complete<br>84d8cc09b701: Pull complete<br>afe9e2465e8b: Pull complete<br>9f3ee9b60694: Extracting [==========================&gt;                        ]  16.38MB/31.44MB<br>c1bda8cc7988: Download complete<br>69d5b4da5a88: Download complete<br>f122c9c34424: Download complete<br>8caabfe0006c: Download complete<br>dfe218bc61c0: Download complete<br>65635bb5c3ee: Download complete<br>c8402093f450: Download complete<br>827338662b84: Download complete<br>61d88446a779: Download complete<br>320ea75f6b79: Download complete<br>433836c91ee4: Download complete<br>88b74081f66e: Download complete<br>e886376b2df3: Download complete</pre><p>Docker check process</p><pre># docker ps<br>CONTAINER ID   IMAGE             COMMAND           CREATED          STATUS          PORTS                                      NAMES<br>36c79a66a100   rancher/rancher   &quot;entrypoint.sh&quot;   35 seconds ago   Up 10 seconds   0.0.0.0:80-&gt;80/tcp, 0.0.0.0:443-&gt;443/tcp   adoring_sammet</pre><p>If something wrong, please check the resource requirements on Rancher web or ignore installing k3s in rancher docker with rancher/rancher [options]</p><p>refer: <a href="https://rancher.com/docs/rancher/v2.0-v2.4/en/installation/requirements/">Rancher Docs: Installation Requirements</a></p><p><strong>Accessing the Rancher application</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y3kd2Cin81mOgvuwAMPmcg.png" /><figcaption>access rancher with https://10.8.131.55</figcaption></figure><p><strong>Set Password</strong> for admin and select <strong>I want to create or manage multiple cluster</strong></p><p>The rancher has provided a local cluster with k3s inside docker container. We can ignore it and import our cluster into rancher</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDnVtnPICD7-ZZrJ43p6Bw.png" /><figcaption>Rancher clusters dashboard</figcaption></figure><p><strong>Adding existing cluster</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSPPEGA9xQDLG0b5QD3h4w.png" /></figure><p><strong>Put the cluster name</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aiTs2kyEpdmiLJMShIrEmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZpHEm_O5uxAgzzhDUV0Lg.png" /></figure><p><strong>Import cluster with apply rancher service to cluster (on cluster control)<br></strong>Back to cluster control — 10.8.131.51</p><p><strong><em>note</em></strong><em>: we use insecure because we did not implement cacerts before.</em></p><pre>(rke) $ curl --insecure -sfL https://kor-devops55/v3/import/bdqpvfv4n5c56sjctc5rglz4q4wczlxvn6dlr5l6466l7t2lk9v nrj.yaml | kubectl --kubeconfig $(pwd)/kube_config_cluster.yml apply -f -</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfffID8FgFpZxC54TIydvQ.png" /><figcaption>New cluster in Rancher cluster dashboard</figcaption></figure><p><strong>Check cluster nodes at our cluster</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLriysmHALbDlmDDNqtgsw.png" /><figcaption>Kubernetes’s node from rke setting up</figcaption></figure><p><strong>Discovery applications services</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YfH74buw0Z_gLmcHs-7MWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUhHqDAHfu0ioyzu6XhRIA.png" /></figure><p><strong>Press + button to scale out pod of application</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJbu5GnwmYQZiLvk2VEW-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMu4ga_nHl8H0jxstnuwXQ.png" /><figcaption>access an application with entrypoint on dashboard</figcaption></figure><p><em>Happy invest on leaning, stay moon</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e549f8d9b1ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-investments-monster/how-to-setup-kubernetes-cluster-with-rke-and-rancher-e549f8d9b1ab">How to setup Kubernetes cluster with RKE and Rancher</a> was originally published in <a href="https://medium.com/the-investments-monster">The Investments Monster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>