<?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 Matthew Sheppard on Medium]]></title>
        <description><![CDATA[Stories by Matthew Sheppard on Medium]]></description>
        <link>https://medium.com/@matthew.sheppard?source=rss-c1b788d41be5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hNgBdA3Fg1-M-JrQ1CqP6A.jpeg</url>
            <title>Stories by Matthew Sheppard on Medium</title>
            <link>https://medium.com/@matthew.sheppard?source=rss-c1b788d41be5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 11:49:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matthew.sheppard/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[How to build a secure by default Kubernetes cluster with a basic CI/CD pipeline on AWS]]></title>
            <link>https://medium.com/slalom-build/how-to-build-a-secure-by-default-kubernetes-cluster-with-a-basic-ci-cd-pipeline-on-aws-ebfe0da1c7c9?source=rss-c1b788d41be5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebfe0da1c7c9</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Matthew Sheppard]]></dc:creator>
            <pubDate>Mon, 11 Jun 2018 12:04:14 GMT</pubDate>
            <atom:updated>2018-06-11T12:04:14.246Z</atom:updated>
            <content:encoded><![CDATA[<p>Written by <a href="https://medium.com/u/c1b788d41be5">Matthew Sheppard</a> &amp; <a href="https://medium.com/u/f525264c258d">Donald Carnegie</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-Y_lPSDSzBjZfRkHAKEQA.jpeg" /></figure><h4>Kuber-what-es?</h4><p>Kubernetes (pronounced “koo-burr-NET-eez”) is an open-source platform to automate deploying, scaling, and operating application containers. The cool kids often refer to it by the (IOHO) not very good abbreviation “k8s”. Kubernetes’ job is to make the most efficient use of your infrastructure whilst ensuring that your containerised workloads are available and can scale as needed. Some businesses have reported being able to reduce their cloud infrastructure costs by between <a href="https://kubernetes.io/blog/2016/09/how-qbox-saved-50-percent-on-aws-bills/">50%</a> and <a href="https://carlosbecker.com/posts/k8s-sandbox-costs/">70%</a> compared to running on traditional VM based architecture.</p><h4>Contain(erise) Your Success</h4><p>Kubernetes is a massive success story for the <a href="https://www.cncf.io/">Cloud Native Computing Foundation</a> and the open-source community behind it. First announced in mid-2014 as a small project lead by a team of Google engineers, it has grown to be the de facto container orchestration platform and a commodity across the public cloud ecosystem. <a href="https://azure.microsoft.com/en-gb/services/container-service/">Microsoft</a>, <a href="https://cloud.google.com/kubernetes-engine/">Google</a>, <a href="https://aws.amazon.com/eks/">Amazon</a> and <a href="https://www.ibm.com/cloud/container-service">IBM</a> all have a managed Kubernetes offering of some form. In terms of contributors and velocity, Kubernetes is second only in open-source projects to the Linux Kernel. It’s being used at scale for many cool workloads, from <a href="https://cloudplatform.googleblog.com/2016/09/bringing-Pokemon-GO-to-life-on-Google-Cloud.html">powering Pokemon Go</a> to ensuring HBO GO subscribers can smoothly <a href="http://www.eweek.com/cloud/why-hbo-chose-kubernetes-to-help-stream-game-of-thrones">stream of Game of Thrones season 7</a>.</p><h4>Continuous Kubernetes</h4><p>As users and engineers of modern web applications, we expect them to be available 24 hours a day, 7 days a week, and to be able to deploy new versions of them many times a day. Kubernetes in itself is not enough to achieve this goal. It ensures our containerised applications run when and where we want and can find the tools and resources they require. To fully empower our engineers, however, we need to build a CI/CD pipeline around Kubernetes.</p><p><a href="https://www.weave.works/blog/gitops-operations-by-pull-request">GitOps</a> is a term that has been coined by <a href="https://www.weave.works/">Weaveworks</a> to describe using Git as the declarative source of truth for the Kubernetes cluster state. Git becomes our means of tracking system state, and we use constructs within git such as <a href="https://help.github.com/articles/about-pull-requests/">pull requests</a> as a means for merging the state held in git with the state of cloud infrastructure. In a nutshell, approved pull requests result in live changes being made to production. This is a really powerful approach since a proven source code workflow can be applied to manage infrastructure — grasping it fully can rid us of old-school bureaucratic change control processes that are complicated, take too long, and lack accountability. The changes enacted on your infrastructure are always 100% visible, traceable, and accountable. The history is stored perpetually in the git repository, and rolling back to any point in history is a piece of cake.</p><h4><strong>Why Should I Use Kubernetes?</strong></h4><p>Containers are already a huge success story in cloud computing. Despite the relatively short period of time they’ve been in our toolbox, they have become a staple of modern cloud computing and are leveraged by many household name apps. However, the burden of orchestrating, managing, and maintaining containerised systems can be huge — that’s where Kubernetes comes in. Kubernetes takes all the great strengths behind containerisation and provides a platform for deploying and managing them with greater ease.</p><p>Kubernetes is an enabler for DevOps; it helps implement key DevOps practices and paves the way for organisations to implement DevOps. Wherever you install it, be it on your laptop, a cloud provider, or an on-premise data centre, it provides automated deployments of your containerised applications with fully consistent environments. With Kubernetes, gone are the days of building and successfully testing locally, only to find your application behaves differently in test or production environments!</p><h4>YATR? (Yet Another Tutorial, Really?)</h4><p>There are plenty of Kubernetes tutorials out there, so why write another one? Good question! In building Kubernetes clusters for our own fun and for clients, we’ve not come across a tutorial that brings together all the pieces needed to setup a cluster on AWS that could be made production ready. The documentation is mostly there, but it’s a treasure hunt to track it down and work out how to make it work in each particular situation. This makes it particularly challenging for anyone embarking on their first Kubernetes pilot or making the step up from a local <a href="https://github.com/kubernetes/minikube">minikube</a> cluster.</p><p>The aim of this tutorial is to close off this gap and step through the setup of Kubernetes cluster that:</p><ul><li><strong>Is highly available:</strong> We want to ensure that our environments can deal with failure and that our containerised applications will carry on running if some of our nodes fail or an AWS Availability Zone experiences an outage. To achieve this, we’ll run Kubernetes masters and nodes across 3 AWS Availability Zones.</li><li><strong>Enforces the “</strong><a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege"><strong>principle of least privilege</strong></a><strong>”:</strong> By default all pods should run in a restrictive security context; they should not have the ability to make changes to the Kubernetes cluster or the underlying AWS environment. Any pod that needs to make changes to the Kubernetes cluster should use a named service account with the appropriate role and policies attached. If a pod needs to make calls to the AWS API, the calls should be brokered to ensure that pod has sufficient authorisation to make them and use only temporary IAM credentials. We’ll achieve this by using Kubernetes <a href="https://kubernetes.io/docs/admin/authorization/rbac/">Role-based Access Control (RBAC)</a> to ensure that by default pods run with no ability to change the cluster configuration. Where specific cluster services need permissions, we will create a specific service account and bind it to a required permission scope (i.e. cluster wide or in just one <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/">namespace</a>) and grant the required permissions to that service account. Access to the AWS API will be brokered through <a href="https://github.com/jtblin/kube2iam">kube2iam</a>; all traffic from pods destined for the AWS API will be redirected to kube2iam. Based on annotations in the pod configurations, kube2iam will make a call to the AWS API to retrieve temporary credentials matching the specified role in the annotation and return these to the caller. All other AWS API calls will be proxied through kube2iam to ensure the principle of least privilege is enforced and policy cannot be bypassed.</li><li><strong>Integrates with Route53 and Classic Load Balancers:</strong> When we deploy an application, we want the ability to declare in the configuration how it is made available to the world and where it can be found, and have this automated for us. Kubernetes will automatically provision a Classic Load Balancer to an application and <a href="https://github.com/kubernetes-incubator/external-dns">external-dns</a> allows us to assign it a friendly Fully Qualified Domain Name (FQDN), all through Infrastructure as Code.</li><li><strong>Has a basic CI/CD pipeline wrapped around it:</strong> We want to automate the way in which we make changes to the cluster, and to how we deploy / update applications. The configuration files specifying our cluster configuration will be committed to a Git repository and the CI/CD pipeline will apply them to the cluster. To achieve this, we’ll use <a href="https://travis-ci.org/">Travis-CI</a> to apply the configuration that gets committed in our master branch to the Kubernetes cluster. This is a first step in the direction of GitOps, however it doesn’t give us a full GitOps capability.</li></ul><p>At the end of the tutorial, we’ll end up with a Kubernetes cluster that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMLf-v0T5rGZgcpbh0TyPw.png" /><figcaption>Our end-state Kubernetes cluster</figcaption></figure><h4>Before you get started</h4><p>We assume you already have some familiarity with Kubernetes. If you are brand new to Kubernetes, it is recommended you review the <a href="https://kubernetes.io/docs/tutorials/kubernetes-basics/">Kubernetes Basics tutorial</a> and get yourself familiar with its key concepts.</p><p>To build our cluster, we need to make sure we have the following tools installed:</p><ul><li><strong>kubectl</strong><br><em>kubectl</em> (Kubernetes Control) is a command line tool for interacting with a Kubernetes cluster, either running locally on your machine (using minikube) or in the cloud.</li><li><strong>kops</strong><br>The <a href="https://github.com/kubernetes/kops">Kubernetes Operations (kops) project</a> provides tooling for building and operating Kubernetes clusters in the cloud. It currently supports Google Cloud &amp; AWS (with other providers in beta). We’ll be using <em>kops</em> to create and manage our cluster in this tutorial.</li><li><strong>Terraform</strong><br><a href="https://www.terraform.io/intro/index.html">Terraform</a> is an Infrastructure as Code (IAC) tool which allows users to define infrastructure in a high-level configuration language which can then be used to build infrastructure in a service provider such as <a href="https://en.wikipedia.org/wiki/Amazon_Web_Services">AWS</a> or <a href="https://en.wikipedia.org/wiki/Google_Cloud_Platform">Google Cloud Platform</a>. We’ll be using <em>Terraform </em>to create our prerequisites for <em>kops</em> and to modify the IAM policies created by <em>kops</em>.</li><li><strong>AWS CLI</strong><br><a href="https://aws.amazon.com/cli/">AWS CLI</a> is a command line tool for interacting with AWS. This is required by <em>kops</em> &amp; <em>Terraform</em> to perform operations on AWS.</li></ul><p>Installation instructions can be found at the links provided.</p><p>This tutorial was created using <em>Kubernetes v1.8</em> and<em> kops v1.8.1</em>.</p><p>We’re running Mac OS X with <a href="https://brew.sh/">Homebrew</a>, so all we need to do is run the following commands to get these installed:</p><pre>$ brew update<br>$ brew install kubectl<br>$ brew install kops<br>$ brew install python3<br>$ easy_install pip<br>$ pip install awscli — upgrade — user<br>$ export PATH=~/.local/bin:$PATH<br>$ brew install terraform</pre><h4>Create the Cluster</h4><p><strong>Step 1:</strong> Clone our repository</p><pre>$ git clone <a href="https://github.com/slalom-london/k8s-tutorial">https://github.com/slalom-london/k8s-tutorial</a></pre><p><strong>Step 2:</strong> Setup a FQDN that will be used for the cluster in Route53</p><p>The Kubernetes cluster that we will setup will use a FQDN hosted in Route53 to expose service endpoints and the API control plane. You could register a new FQDN or transfer an existing FQDN. AWS has a full step through for each of these options:</p><p><a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-configuring.html">Configuring Amazon Route 53 as your DNS service</a></p><p><strong>Step 3:</strong> Create the prerequisites needed for <em>kops</em></p><p>For <em>kops</em> to build the cluster, it needs an S3 store to hold the cluster configuration and an IAM user account that has the following policies attached to it:</p><pre>AmazonEC2FullAccess<br>AmazonRoute53FullAccess<br>AmazonS3FullAccess<br>IAMFullAccess<br>AmazonVPCFullAccess</pre><p><em>prereqs/kops_pre_reqs.tf</em> will create this for you. It will also create an S3 bucket that will be used as a <a href="https://www.terraform.io/docs/state/remote.html">remote store for our Terraform state.</a> This allows multiple users to work with one set of Infrastructure as Code without causing conflicts. You will need to update the file to replace {my_bucket_name} and {my_tf_bucket_name} with your chosen bucket name.</p><p>Then run the following commands:</p><pre>$ cd prereqs<br>$ terraform init<br>$ terraform plan<br>$ terraform apply</pre><p>If you log into your AWS account, you will now see a newly created <em>kops</em> IAM user, an S3 bucket for the <em>kops</em> state store, and another S3 bucket for the <em>Terraform</em> state store</p><p><strong>Step 4:</strong> Use <em>kops</em> to stand-up the cluster</p><p>In the previous step, we created an IAM account for <em>kops</em>. Now we need to setup our AWS CLI client to use that account. We can grab the <em>kops</em> IAM ID and secret key from the file <em>Terraform</em> uses to store the state of what it has created in the previous step. Open <em>terraform.tfstate</em> in your text editor and look for the section similar to the below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c39c4622e5c849d3f9790a472b51243/href">https://medium.com/media/3c39c4622e5c849d3f9790a472b51243/href</a></iframe><p>Make a note of value in the {iam_id} and {aws_secret_key} fields, and run the following command:</p><pre>$ aws configure --profile kops<br>AWS Access Key ID [None]: <strong>{iam_id}</strong><strong><em><br></em></strong>AWS Secret Access Key [None]: <strong>{aws_secret_key}</strong><strong><em><br></em></strong>Default region name [None]: <strong><em>{your_chosen_aws_region}<br></em></strong>Default output format [None]: <strong><em>text</em></strong></pre><p>Next we need to set a couple of environmental variables so that <em>kops</em> knows which AWS IAM account to use and where it should put its state store:</p><pre>$ export AWS_PROFILE=kops<br>$ export KOPS_STATE_STORE=s3://{my_bucket_name}</pre><p>Now for the main event — let’s use <em>kops</em> to build our cluster. Run the following command, substituting your AWS region, your DNS zone and your chosen cluster name:</p><pre>$ kops create cluster --cloud aws \<br> --bastion \<br> --node-count 3 \<br> --node-size t2.medium \<br> --master-size t2.medium \<br> --zones {your_chosen_aws_region}a,{your_chosen_aws_region}b,{your_chosen_aws_region}c \<br> --master-zones {your_chosen_aws_region}a,{your_chosen_aws_region}b,{your_chosen_aws_region}c \<br> --dns-zone {your_dns_zone} \<br> --topology private \<br> --networking calico \<br> --authorization RBAC \<br> --name {your_cluster_name} \<br> --out=k8s \<br> --target=terraform --yes</pre><p>This command tells <em>kops</em> that we want to build a cluster that:</p><ul><li>Will use AWS</li><li>Has a master node of size t2.medium in each of the specified availability zones</li><li>Has 3 worker nodes of size t2.medium. <em>kops</em> will spread the worker nodes evenly across each of the availability zones</li><li>Uses a private network topology, meaning that the all the nodes have private IP addresses and are not directly accessible from the public Internet</li><li>Uses <a href="https://github.com/projectcalico/cni-plugin">Calico</a> as a <a href="https://github.com/containernetworking/cni">Container Network Interface</a> replacing kubenet as a result of the requirements of the private network topology</li><li>Uses RBAC for Kubernetes access permissions</li><li>Is described in a <em>Terraform</em> configuration file to be written to the directory specified by --out</li></ul><p><em>kops</em> generates a set of <em>Terraform</em> configuration files in a newly created <em>k8s </em>directory<em> </em>that can be applied to create the cluster. Before we build our cluster, we want to add a configuration file to tell <em>Terraform</em> to keep its state store on the S3 bucket that we just created.</p><pre>$ cd k8s<br>$ terraform init<br>$ terraform plan<br>$ terraform apply</pre><p>It will take between 10 and 15 minutes for your cluster to become available. You can check the status of the cluster by running the following command:</p><pre>$ kops validate cluster</pre><p>When the cluster is finished building, you should see an output like this:</p><pre>Using cluster from kubectl context: cluster.zigzag-london.com</pre><pre>Validating cluster cluster.zigzag-london.com</pre><pre>INSTANCE GROUPS<br>NAME   ROLE MACHINETYPE MIN MAX SUBNETS<br>bastions  Bastion t2.micro 1 1 utility-eu-west-1a,utility-eu-west-1b,utility-eu-west-1c<br>master-eu-west-1a Master t2.medium 1 1 eu-west-1a<br>master-eu-west-1b Master t2.medium 1 1 eu-west-1b<br>master-eu-west-1c Master t2.medium 1 1 eu-west-1c<br>nodes   Node t2.medium 3 3 eu-west-1a,eu-west-1b,eu-west-1c</pre><pre>NODE STATUS<br>NAME      ROLE READY<br>ip-172-20-107-234.eu-west-1.compute.internal master True<br>ip-172-20-124-39.eu-west-1.compute.internal node True<br>ip-172-20-44-152.eu-west-1.compute.internal master True<br>ip-172-20-60-188.eu-west-1.compute.internal node True<br>ip-172-20-79-79.eu-west-1.compute.internal master True<br>ip-172-20-87-125.eu-west-1.compute.internal node True</pre><pre>Your cluster cluster.zigzag-london.com is ready</pre><h3>Standing up a CI/CD Environment</h3><p>In order to implement GitOps, we need a CI/CD environment for monitoring our repository &amp; executing updates. For this tutorial we will configure our CI/CD environment to execute deployment steps on each push to the master branch of our repository. We’re doing this for the purposes of convenience of demonstration; allowing developers to do this is definitely bad practise. In a real life project we would recommend a<a href="https://www.atlassian.com/continuous-delivery/continuous-delivery-workflows-with-feature-branching-and-gitflow"> feature branching strategy with a code review and a development lead approval step</a>.</p><p>For this tutorial, we are going to use TravisCI, a cloud based CI service. TravisCI is free so long as:</p><ul><li>You host your repository in Github</li><li>The repository is publicly accessible</li></ul><p><strong>Step 1:</strong> Setup Accounts &amp; Clone repository</p><ul><li>Navigate to <a href="http://www.github.com/">GitHub</a> and sign up\log in</li><li>Create a new, empty repository and name it “k8s-ci”</li><li>Clone this repository to your local machine:</li></ul><pre>$ git clone &lt;URL to new repo&gt;</pre><ul><li>Navigate to <a href="https://travis-ci.org/">TravisCI</a> and sign up using your GitHub account. Navigate to your user profile by clicking on your name on the top right.</li><li>Click the slider against the GitHub repo to enable TravisCI for this repository.</li></ul><p><strong>Step 2:</strong> Setup Triggers</p><p>As we are practicing GitOps, we only want to deploy on an approved pull request. We can configure this in Travis by clicking More Options → Settings.</p><ul><li>Ensure “build pushed branches” is set to on</li><li>Ensure “build pushed pull requests” is set to on</li></ul><p>Travis gets the vast majority of its instructions from a yaml file stored in your repository. Create an empty file named <em>.travis.yml</em> in the root of your repository, and we can start configuring it based on the .travis.yml in our repository:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/578984b1f48184b73c091db05f752deb/href">https://medium.com/media/578984b1f48184b73c091db05f752deb/href</a></iframe><ul><li>Line 1: Specifies that we only want a build to run on the master branch. In a real environment, we would likely also deploy on the pushing of a branch, but to a test environment as opposed to a production environment. One way this could be done is by using environment variables to apply conditional logic to the deploy script, but that is out of scope for this post.</li><li>Line 4: Specifies that we require root permissions using sudo in order to install our dependencies</li><li>Line 5: This is the start of the block where we set the permissions on each of our scripts so they are executable.</li><li>Line 10: This is the start of the block where we specify the scripts that need to run first in order to setup the CI environment before we can execute the scripts that do the actual deployment.</li><li>Line 13: This is the start of the block where we specify the scripts that will run to execute the deployment tasks.</li></ul><p><strong>Step 3:</strong> Manage Secrets</p><p>We don’t want to keep our AWS secrets in a public repository in clear text; this would be extremely bad information security practise. Handily, Travis provides a CLI tool which can be used for storing your secrets to be injected at build time. Travis generates a new public\private key pair for each new account, and these secrets will be encrypted using that keypair and injected as environment variables each time the build runs. To set this up, run the following commands in the root of your repository and login using the requested details:</p><pre>$ sudo gem install travis<br>$ travis login --org</pre><p>There are a two pre-loaded scripts in the <em>build-scripts</em> directory of our repository ready for your secrets to be input. Copy the <em>build_scripts</em> directory from your local copy of our <em>k8s-tutorial </em>repository<em> </em>to your own <em>k8s-ci</em> repository and update them as follows:</p><ul><li>large-secrets.txt: Add your Kubernetes access keys. These can be found in <em>~/.kube/config</em></li><li>setup-secrets.sh: Add your Kubernetes password (again found in <em>~/.kube/config) </em>and AWS access keys from <em>~/.aws/credentials</em></li></ul><p>Then, from the root of your repository, run <em>setup-secrets.sh </em>script using the following command:</p><pre>$ chmod 755 build-scripts/setup-secrets.sh<br>$ ./build-scripts/setup-secrets.sh</pre><p><strong>Make a note of the openssl command the setup-secrets.sh script returns for later, as we will need this to decrypt the secrets.</strong></p><p>This script will encrypt your secrets using Travis and update your <em>.travis.yml </em>file. Commit the encrypted secrets to your repository:</p><pre>$ git add build-scripts/large-secrets.txt.enc .travis.yml<br>$ git commit -m &quot;Committing encrypted secrets&quot;</pre><p>Now your secrets are secured in Travis, we strongly suggest removing them from all files and scripts. It can be super easy to accidentally commit secrets to source control, and your authors are both guilty of this sin! To catch any accidental commits of secrets, we use <a href="https://github.com/awslabs/git-secrets">git-secrets</a>. You can set it up using the following steps:</p><pre>$ brew install git-secrets<br>$ git-secrets --install</pre><p><strong>Step 4</strong>: Install Dependencies</p><p>As TravisCI runs each build in a clean Docker container, we need to install our dependencies every time. These dependencies are the same as we set out in the <strong>“Before you get started”</strong> section of this post. Create a file called <em>install-dependencies.sh </em>in the <em>build-scripts</em> folder and paste the following configuration into it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2ded68cff46f5e4825f5275b6af6734/href">https://medium.com/media/c2ded68cff46f5e4825f5275b6af6734/href</a></iframe><p>Now commit this file to your repository:</p><pre>$ git add install-dependencies.sh<br>$ git commit -m &quot;Adding script to install dependencies&quot;</pre><p><strong>Step 5:</strong> Inject Our Secrets</p><p>Now we need a script for setting up our secrets in the Docker container that we will do our build steps in. Create a file named <em>inject-secrets.sh</em> in the <em>build-scripts </em>folder. Paste in the script below and update it as follows:</p><ul><li>Replace <em>{Your cluster url here}</em> with the URL of your Kubernetes cluster</li><li>Replace the OpenSSL command we made a note of in Step 3 of this section with <em>{Your openssl command from the encrypt secrets stage here} </em>appending<em> ./build-scripts/</em> before <em>large-secrets.txt.enc</em></li><li>Replace <em>{your-aws-region}</em> with the AWS region you are using</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33a93355b1eedb18c9814b074d178661/href">https://medium.com/media/33a93355b1eedb18c9814b074d178661/href</a></iframe><p>This script will pull our secrets from the Travis environment, decrypt them, and inject them into the pertinent config files.</p><p>You will notice in the script above that it refers to a file in the <em>build-scripts </em>directory named <em>kubeconfig</em> — we will need to create this too. Paste in the contents below, swapping out the variable <em>{Your cluster url here}</em> with the URL of your Kubernetes cluster.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97f175aa6d469afd46b5d2dd5d5b0049/href">https://medium.com/media/97f175aa6d469afd46b5d2dd5d5b0049/href</a></iframe><p>Commit both these files to your repository:</p><pre><br>$ git add inject-secrets.sh kubeconfig<br>$ git commit -m &quot;Adding script to inject secrets and kubeconfig file&quot;</pre><p><strong>Step 6:</strong> Environment Setup</p><p>Before we are ready to deploy applications, we need to prepare the cluster by deploying the configuration for <em>kube2iam</em> and <em>external-dns</em>. The configuration for each of these tools has to be a applied in a set order:</p><ul><li><strong>Apply Terraform configuration</strong> to create a new AWS IAM role (and the required policy grants to that role) and a trust relation back to the AWS IAM role that nodes run under. The trust relationship allows a node to assume the new IAM role.</li><li><strong>Apply Kubernetes RBAC configuration</strong> to create a service account, bind it to a required permission scope, and grant the required permissions to that service account. This service account is then specified as part of the configuration of the pods that are providing each of the specific services.</li><li><strong>Apply Kubernetes configurations</strong> to deploy the services. Depending on the service being deployed, this may be a Kubernetes <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">Deployment</a> or <a href="https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/">DaemonSet</a>.</li></ul><p>We’ll build our deployment script so that the cluster is always configured first.</p><p>Copy over the folders containing the templates for <em>external-dns</em> and <em>kube2iam</em> from our repository to your repository.</p><p>First, we will create a script that will apply our Terraform configuration. Create a file called <em>deploy-terraform.sh </em>in the <em>build-scripts</em> directory and add the following code to it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b78d946f04392c218b61283be49bd5d5/href">https://medium.com/media/b78d946f04392c218b61283be49bd5d5/href</a></iframe><p>This script will traverse the directory structure in our repository and apply any Terraform configuration files it finds.</p><p>(NB: In a real production environment, we would add checks in our CI pipeline to ensure that Terraform is not be used maliciously)</p><p>Commit this to your repository:</p><pre>$ git add deploy-terraform.sh<br>$ git commit -m &quot;Adding Terraform deployment script&quot;</pre><p>Now we’re ready to update and commit the Terraform configuration for each of our 3 services to the repository:</p><ul><li>Update <em>external_dns/pod-role-trust-policy.json</em> and replace <em>{your-node-iam-role-arn} </em>with the IAM ARN for Kubernetes nodes in your cluster. This can be found by running the following command:</li></ul><pre>$ aws iam list-roles | grep node</pre><ul><li>Update <em>external_dns/main.tf</em> to replace <em>{your-aws-region} </em>with the AWS region you are working in and <em>{your-tf-bucket}</em> with the name of the bucket you chose to hold the Terraform state store.</li></ul><p>Commit the service configuration to your repository:</p><pre>$ git add external_dns/pod-role-trust-policy.json external_dns/external-dns-iam-setup.tf external_dns/external-dns-role-rights.json external_dns/main.tf<br>$ git commit -m &quot;Adding cluster Terraform service configuration&quot;</pre><p>Travis is configured to apply configuration on each push to master so if we execute a push now:</p><pre>$ git push</pre><p>We should be able to see all our Terraform configuration being applied to our AWS account in the Job Log.</p><p>We have now created all the IAM roles and trust relationships needed by our Kubernetes environment.</p><p>Next, we need a script to apply our Kubernetes configurations for our environment pre-requisites. To complete this step you will need to copy and update the following files from our repository into your repository:</p><ul><li><em>external_dns/external_dns.yaml</em>: Replace <em>{your-dns-zone}</em> with the DNS zone you are using, <em>{your-identifier}</em> with something that will differentiate the DNS records that <em>external-dns</em> will produce (e.g. your name), and <em>{your-external-dns-iam-role-arn}</em> with the IAM ARN for the role that was created when the Terraform configuration was applied. This can be found by running the following command:</li></ul><pre>$ aws iam get-role --role-name external_dns_pod_role</pre><ul><li><em>kube2iam </em>and<em> rbac/</em>: No updates required</li></ul><p>These updates specify which IAM role each of the pods should assume when they need to access the AWS API.</p><p>Now commit these files into the repository:</p><pre>$ git add external_dns/external_dns.yaml rbac/ kube2iam/<br>$ git commit -m &quot;Adding external-dns k8s config&quot;</pre><p>Now we’re going to start building our deploy script for our Kubernetes services. Create a file named <em>deploy-k8s.sh </em>in the <em>build-scripts </em>folder. Start the file off with a header like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01be59ef2be1f7a22a90530aa79cae92/href">https://medium.com/media/01be59ef2be1f7a22a90530aa79cae92/href</a></iframe><p>Next, add the below steps that deploy the Kubernetes RBAC configuration to the cluster:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32fd632a8926186a9f8f64c677913c25/href">https://medium.com/media/32fd632a8926186a9f8f64c677913c25/href</a></iframe><p>These steps are needed because the <em>external-dns</em> service requires Kubernetes API rights in order to run and provide its service to the cluster. As a reminder, RBAC ensures pods have no access to the Kubernetes API by default. This is in line with the “principle of least privilege” and prevents pods being able to alter the cluster settings if they are compromised for any reason.</p><p>In order to get TravisCI to apply these changes, we need to add an additional step to our <em>.travis.yml</em> to execute <em>deploy-k8s.sh</em>. Add the following to the before_install: section:</p><pre>- chmod +x ./build-scripts/deploy-k8s.sh</pre><p>And the following into the <em>script:</em> section:</p><pre>- “./build-scripts/deploy-k8s.sh”</pre><p>Now commit <em>deploy-k8s.sh, .travis.yml and </em>push your repository to master and ensure there are no errors in the Travis build log:</p><pre>$ git add build-scripts/deploy-k8s.sh .travis.yml<br>$ git commit -m &quot;Adding Travis config to deploy k8s config&quot;<br>$ git push</pre><p>Now that we have the Terraform and RBAC configuration added to our CI/CD pipeline, let’s add steps to deploy <em>kube2iam </em>to our <em>deploy-k8s.sh</em> script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bd0a422fc2232d39fd3af347666de48/href">https://medium.com/media/1bd0a422fc2232d39fd3af347666de48/href</a></iframe><p><em>kube2iam</em> is deployed first since <em>external-dns</em> will make calls to the AWS API using <em>kube2iam</em> as a broker.</p><p>Now push your repository to master and ensure there are no errors in the build log:</p><pre>$ git add build-scripts/deploy-k8s.sh<br>$ git commit -m &quot;Updating Travis config to deploy k8s config&quot;<br>$ git push</pre><p>Now, let’s check on our cluster to make sure all the services have been deployed correctly. <em>external-dns</em> is a Deployment, so we can execute the following command to get its status:</p><pre>$ kubectl get deployments --namespace=kube-system</pre><p>If everything has been deployed correctly, we should see something like:</p><pre>NAME                       DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE<br>calico-kube-controllers    1         1         1            1           1h<br>calico-policy-controller   0         0         0            0           1h<br>dns-controller             1         1         1            1           1h<br>external-dns               1         1         1            1           1m<br>kube-dns                   2         2         2            2           1h<br>kube-dns-autoscaler        1         1         1            1           1h</pre><p><em>kube2iam</em> is deployed as DaemonSet since it needs to be running on all nodes to broker calls to the AWS API. We run the following command to get its status:</p><pre>$ kubectl get ds --namespace=kube-system</pre><p>If all is is well, we should see something like:</p><pre>NAME          DESIRED   CURRENT   READY     UP-TO-DATE   AVAILABLE   NODE-SELECTOR   AGE<br>calico-node   6         6         6         6            6           &lt;none&gt;          1h<br>kube2iam      3         3         3         3            3           &lt;none&gt;          7m</pre><p><strong>Step 7:</strong> Deploy A Test Application</p><p>Now it’s time to reap the benefits of the hard work of setting up our cluster and see the power of our workflow and Infrastructure as Code to easily deploy a test application!</p><p>First, we need to add a deployment step to our <em>deploy-k8s.sh</em> script that will deploy our applications:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b03008bd6427c8d8abab2a391956522a/href">https://medium.com/media/b03008bd6427c8d8abab2a391956522a/href</a></iframe><p>This step will apply any Kubernetes configuration files in the <em>apps</em> directory of our repository to the cluster. Commit this change and push to master:</p><pre>$ git add build-scripts/deploy-k8s.sh<br>$ git commit -m &quot;Updating Travis config to deploy k8s config for apps&quot;<br>$ git push</pre><p>As we’re beginning our journey towards GitOps, let’s follow a GitOps process flow for deploying a test application:</p><ul><li>Create a local branch by running the following command:</li></ul><pre>$ git checkout -b testapp</pre><ul><li>Create a folder under called <em>apps</em> in your repository</li><li>In the apps folder, create a file called <em>hello_app_deployment.yaml</em> and add the following to it:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/654656ffe4fef7179a0b8fd448193783/href">https://medium.com/media/654656ffe4fef7179a0b8fd448193783/href</a></iframe><p>This configuration has 2 sections:</p><ol><li><strong>Deployment:</strong> This specifies the details of the container we are going to run, the amount of resources to give it, which port the application inside the container can be accessed on, and the number of replicas of that application we want to run. In this case, we are going to run a simple container that prints “Salutations, globe!” and then the hostname of the container to port 8080. We specify we are going to run 3 replicas — one for each of our cluster nodes.</li><li><strong>Service:</strong> This specifies how the deployment should be exposed, either internally or externally. In the case of our test application, we are exposing it internally on the cluster IP on port 80. We also specify the friendly FQDN (e.g. something like saluations.yourdomain.com) that our application can be accessed on here. You will need to replace <em>{your FQDN here} </em>with your friendly FQDN.</li></ol><p>Now commit this file to your local branch and push the branch to the remote repository:</p><pre>$ git add hello_app_deployment.yaml<br>$ git commit -m &quot;Adding test app&quot;<br>$ git push -u origin testapp</pre><p>If we log into GitHub, we should now see we have a new branch called <em>“testapp”</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0jSkyvuqiQtGhC9NVOKog.png" /></figure><p>We want to raise a pull request and merge to master, so click on <em>“Compare &amp; pull request”</em> and follow the process to complete this activity.</p><p>Once the deployment has completed, we can verify our test application has deployed correctly by running the below commands and checking for similar output:</p><pre>$ kubectl get deployments salutations-deployment</pre><pre>NAME                     DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE<br>salutations-deployment   3         3         3            3           24d</pre><pre>$ kubectl get services salutations-service</pre><pre>NAME                  CLUSTER-IP    EXTERNAL-IP        PORT(S)        AGE<br>salutations-service   100.65.66.9   a78b874f74ed0...   80:32439/TCP   6d</pre><p>The real proof, however, is connecting to our application using our friendly FQDN! If everything has deployed correctly, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPiUkJnHK-9-sHpB_Q-GmQ.png" /></figure><p>Success! If you now refresh this page, you should see the hostname change when your browser accesses the app running on a different Kubernetes node through the Classic Load Balancer.</p><h3><strong>Summary</strong></h3><p>Using this tutorial, we have built a Kubernetes cluster with a good set of security defaults and then wrapped a simple CI/CD pipeline around it. We then specified through Infrastructure as Code how we wanted a simple containerised application to be deployed and used our CI/CD pipeline and Kubernetes cluster to deploy it as defined — automatically.</p><p>This is just a simple illustration of the rich benefits Kubernetes can bring to your developers and your DevOps capabilities when included as part of your toolchain!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebfe0da1c7c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/slalom-build/how-to-build-a-secure-by-default-kubernetes-cluster-with-a-basic-ci-cd-pipeline-on-aws-ebfe0da1c7c9">How to build a secure by default Kubernetes cluster with a basic CI/CD pipeline on AWS</a> was originally published in <a href="https://medium.com/slalom-build">Slalom Build</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>