One place for hosting & domains

      Tutorial

      Installing the Linode CCM on an Unmanaged Kubernetes Cluster – A Tutorial


      Updated by Linode Contributed by Linode

      What is the Linode CCM?

      The Linode Cloud Controller Manager (CCM) provides a way for Kubernetes clusters to access additional Linode services. Linode’s CCM provides access to Linode’s load balancing service, Linode NodeBalancers.

      NodeBalancers provide your Kubernetes cluster with a reliable way of exposing resources to the public internet. The Linode CCM handles the creation and deletion of the NodeBalancer, and, along with other Master Plane components, correctly identifies the resources, and their networking, that the NodeBalancer will route traffic to. Whenever a Kubernetes Service of the LoadBalancer type is created, your Kubernetes cluster will create a Linode NodeBalancer service with the help of the Linode CCM.

      Note

      This guide will show you how to manually install the Linode CCM on an unmanaged Kubernetes cluster. This guide exists to support special use cases. For example, if you would like to experiment with various elements of a Kubernetes control plane.

      If you would like to use Kubernetes for production scenarios and make use of Linode NodeBalancers to expose your cluster’s resources, it is recommended that you use the Linode Kubernetes Engine to deploy your cluster. An LKE cluster’s control plane has the Linode CCM preinstalled and does not require any of the steps included in this guide.

      Similarly, if you would like to deploy an unmanaged Kubernetes cluster on Linode, the best way to accomplish that is using Terraform and the Linode K8s module. The Linode K8s module will also include the Linode CCM preinstalled on the Kubernetes master’s control plane and does not require any of the steps included in this guide.

      If you have used the Linode Kubernetes Engine (LKE) or the Linode Terraform K8s module to deploy your cluster, you should instead refer to the Getting Started with Load Balancing on a Linode Kubernetes Engine (LKE) Cluster guide for steps on adding and configuring NodeBalancers on your Kubernetes cluster.

      In this Guide

      You will manually install the Linode CCM on your unmanaged Kubernetes cluster. This will include:

      Before You Begin

      1. Deploy a new unmanaged Kubernetes cluster. You can deploy an unmanaged Kubernetes cluster on Linode by following the Getting Started with Kubernetes: Use kubeadm to Deploy a Cluster on Linode

        Note

        It is recommended that you install the Linode CCM on a new Kubernetes cluster, as there are a number of issues that prevent the CCM from running on Nodes that are in the “Ready” state.

      2. Ensure you have kubectl installed on your local computer and you can access your Kubernetes cluster with it.

      3. Install Git on your local computer.

      4. Generate a Linode APIv4 token.

      Running the Linode Cloud Controller Manager

      Update Your Cluster Configuration

      In order to run the Linode Cloud Controller Manager:

      • You must start kubelet with the --cloud-provider=external flag.
      • kube-apiserver and kube-controller-manager must NOT supply the --cloud-provider flag.

      These configurations will change the behavior of your cluster and how it interacts with its Nodes. For more details, visit the upstream Cloud Controller documentation.

      Install the Linode CCM

      The Linode CCM’s GitHub repository provides a helper script that creates a Kubernetes manifest file that you can use to install the CCM on your cluster. These steps should be run on your local computer and were tested on a macOS.

      Note

      You will need your Linode APIv4 token to complete the steps in this section.
      1. Clone the Linode CCM’s GitHub repository.

        git clone [email protected]:linode/linode-cloud-controller-manager.git
        
      2. Move into the CCM repository’s deploy directory.

        cd linode-cloud-controller-manager/deploy/
        
      3. Run the generate-manifest.sh script. Ensure you replace $LINODE_API_TOKEN with your own Linode APIv4 token and us-east with the Linode region where your cluster resides. To view a list of regions, you can use the Linode CLI, or you can view the Regions API endpoint.

        ./generate-manifest.sh $LINODE_API_TOKEN us-east
        

        After running the script, you should have a new manifest file in the repo’s deploy directory, ccm-linode.yaml.

      4. Apply the manifest file to your cluster in order to install the Linode CCM and the required supporting resources.

        kubectl create -f ccm-linode.yaml
        

        Note

        You can create your own ccm-linode.yaml manifest file by editing the contents of the ccm-linode-template.yaml file and changing the values of the data.apiToken and data.region fields with your own desired values. This template file is located in the deploy directory of the Linode CCM repository.

      Updating the Linode CCM

      The easiest way to update the Linode CCM is to edit the DaemonSet that creates the Linode CCM Pod. To do so:

      1. Run the edit command to make changes to the CCM Daemonset.

        kubectl edit ds -n kube-system ccm-linode
        
      2. The CCM Daemonset manifest will appear in vim. Press i to enter insert mode. Navigate to spec.template.spec.image and change the field’s value to the desired version tag. For instance, if you had the following image:

        image: linode/linode-cloud-controller-manager:v0.2.2
        

        You could update the image to v0.2.3 by changing the image tag:

        image: linode/linode-cloud-controller-manager:v0.2.3
        

        For a complete list of CCM version tags, visit the CCM DockerHub page.

        Caution

        The CCM Daemonset manifest may list latest as the image version tag. This may or may not be pointed at the latest version. To ensure the latest version, it is recommended to first check the CCM DockerHub page, then use the most recent release.
      3. Press escape to exit insert mode, then type :wq and press enter to save your changes. A new Pod will be created with the new image, and the old Pod will be deleted.

      Next Steps

      Now that you have the Linode CCM installed on your Kubernetes cluster, you can learn how to add and configure Linode NodeBalancers on your cluster.

      This guide is published under a CC BY-ND 4.0 license.



      Source link

      Creating Single File Components in VueJS – A Tutorial


      Updated by Linode Contributed by Pavel Petrov

      When first learning VueJS, and when using it for smaller projects, you will likely use regular, globally-defined components. Once your project grows and you start needing more structure and flexibility, single file components can be a better option.

      Below you can see an example of a barebones single file component, which we will examine part-by-part later in the guide:

      SkeletonComponent.vue
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      
      <template>
      <h1>{{ greeting }}</h1>
      </template>
      
      <script>
      export default {
          name: 'SkeletonComponent',
          data: function() {
              return {
                  greeting: 'Hello'
              };
          },
          props: [],
          methods: {
          },
          created: function(){
          }
      }
      </script>
      
      <style scoped>
      h1 {
          font-size: 2em;
          text-align: center;
      }
      </style>

      In this guide, you will learn:

      Note

      Before You Begin

      If you haven’t read our Building and Using VueJS Components already, go take a look.

      Make sure you have Node.js installed. If you don’t, our How to Install Node.js guide outlines different installation options.

      What are Single File Components

      Single file components are similar to regular components, but there are a few key differences which can make single file components the better tool for your project:

      • They can be defined locally, instead of globally.

      • You can define your component’s <template> outside of your JavaScript, which allows for syntax highlighting in your text editor, unlike with string templates.

      • CSS/styling information is included in the component definition.

      Inspecting a Single File Component

      Single file components are contained in files with the .vue extension. Each .vue file consists of three parts: template, script, style. Let’s revisit our barebones component:

      SkeletonComponent.vue
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      
      <template>
      <h1>{{ greeting }}</h1>
      </template>
      
      <script>
      export default {
          name: 'SkeletonComponent',
          data: function() {
              return {
                  greeting: 'Hello'
              };
          },
          props: [],
          methods: {
          },
          created: function(){
          }
      }
      </script>
      
      <style scoped>
      h1 {
          font-size: 2em;
          text-align: center;
      }
      </style>
      • Lines 1-3 of the component define the <template>, where we specify the HTML template of our component. In comparison, a regular component’s template is represented with a string property inside the component’s JavaScript. This can become increasingly confusing for complex components, because there is no syntax highlighting within the string.

        Another benefit for your templates is that you do not have to adjust the {{ }} mustache tag delimiters to [[ ]] or something else if you are working with another framework that already uses them.

        Note

        For example, Symfony developers using VueJS would have to update their delimiter configuration, because Twig already uses mustache delimiters for its rendering methods. Even though this might be a fairly trivial task, using single file components eliminates that need entirely.
      • The script section of the component (lines 5-19) defines the component’s properties and business logic. This is similar to how regular components are defined, but instead everything is within an export statement.

      • The style section, on lines 21-26, uses the scoped attribute to create component-specific CSS. If you were instead using regular components, you would have no way of adding component-specific CSS, and thus you would have to define your styles globally.

        This makes your components completely independent, so you can now not only use them in your current project, but reuse them among other projects as well. Finally, you can use preprocessors like SASS and Babel for the styling information in your component.

      Prepare your Development Environment

      One drawback of single file components for beginners is that they require webpack or Browserify to build. These tools bundle your application’s dependencies, but they can add to the learning curve. Vue provides a CLI package that’s built on top of webpack and which simplifies managing your project.

      We’ll use this tool throughout this guide; to install it, run:

      sudo npm install -g @vue/cli
      

      The Vue CLI will now be available globally on your workstation (because the -g flag was used).

      Note

      If you’re using NVM, you can install Vue CLI without sudo:

      npm install -g @vue/cli
      

      Create your Project

      All of the examples in this guide will live under a single project. Run the vue create command to create a directory for this project and have Vue CLI build the project skeleton for you:

      vue create single-file-components --packageManager=npm
      
        
      Vue CLI v4.3.1
      ? Please pick a preset: (Use arrow keys)
      ❯ default (babel, eslint)
      Manually select features
      
      

      Note

      You can specify --packageManager=yarn if you prefer yarn to npm.

      The CLI uses pretty sensible defaults, so if you’re a beginner you can just press enter and the Vue CLI will build your first project and install the needed dependencies. If you haven’t done this before, it might take a while to fetch the needed dependencies.

      Now let’s test:

      cd single-file-components && npm run serve
      
        
      DONE Compiled successfully in 3398ms
      
      App running at:
      
      -   Local: http://localhost:8080/
      -   Network: unavailable
      
      Note that the development build is not optimized.
      To create a production build, run npm run build.
      
      

      What npm run serve does is run the development server, but the cool thing is that while you make changes the dev server automatically rebuilds the project and injects the changes in the browser, so you don’t even have to refresh.

      Now, if everything is fine, you should be able to open http://localhost:8080 in your browser and you will see the VueJS welcome screen:

      VueJS Welcome Screen

      Let’s look at the directory structure of the default application and go through each folder:

      tree -I node_modules
      
        
      .
      ├── babel.config.js
      ├── package.json
      ├── package-lock.json
      ├── public
      │   ├── favicon.ico
      │   └── index.html
      ├── README.md
      └── src
          ├── App.vue
          ├── assets
          │   └── logo.png
          ├── components
          │   └── HelloWorld.vue
          └── main.js
      
      

      Note

      The -I node_modules option will tell tree to ignore your node_modules/ directory, which is where all of the node dependencies reside.

      The public Folder and index.html

      Files in the public folder will not be bundled by webpack. When your project is created, this folder will contain an index.html file:

      index.html
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="utf-8" />
          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width,initial-scale=1.0" />
          <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
          <title><%= htmlWebpackPlugin.options.title %></title>
      </head>
      <body>
          <noscript>
              <strong>
                  We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't
                  work properly without JavaScript enabled. Please enable it to
                  continue.
              </strong>
          </noscript>
          <div id="app"></div>
          <!-- built files will be auto injected -->
      </body>
      </html>

      On lines 7, 8, and 13 you will notice the <%= %> syntax where the favicon link and page title are embedded; this is part of the lodash template syntax, which the index file is written in. While your index file isn’t included in webpack’s dependency bundle, it will be processed by the html-webpack-plugin, which does a few useful things:

      • It populates the variables that you embed using the template syntax. You can see more about the default variable values exposed by webpack here.
      • It automatically connects your index to the app bundle that webpack compiles: on line 19, you’ll see a comment that says the files built by webpack are auto-injected by the build procedure.

        More about the build procedure for index.html

        This is an example of what the file will look like after the build procedure:

        index.html
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        
        <!DOCTYPE html>
        <html lang=en>
        <head>
            <meta charset=utf-8>
            <meta http-equiv=X-UA-Compatible content="IE=edge">
            <meta name=viewport content="width=device-width,initial-scale=1">
            <link rel=icon href=/favicon.ico> <title>single-file-components</title>
            <link href=/css/app.fb0c6e1c.css rel=preload as=style>
            <link href=/js/app.ae3090b2.js rel=preload as=script>
            <link href=/js/chunk-vendors.b4c61135.js rel=preload as=script>
            <link href=/css/app.fb0c6e1c.css rel=stylesheet>
        </head>
        <body>
            <noscript>
                <strong>
                    We're sorry but single-file-components doesn't work properly without JavaScript enabled. Please
                    enable it to continue.
                </strong>
            </noscript>
            <div id=app></div>
            <script src=/js/chunk-vendors.b4c61135.js></script>
            <script src=/js/app.ae3090b2.js></script>
        </body>
        </html>

        Notice that your app’s script and CSS dependencies have been added to the file on lines 21 and 22, and that these files have random hash appended their names (e.g. app.ae3090b2.js). These hashes will change over time for subsequent builds of your app, and the html-webpack-plugin will keep the hash updated in your index. Without this feature, you would need to update those lines for each build.

      The rest of the body contains these elements:

      • The noscript tag, which is in place to warn users with disabled JS that the app will not work unless they enable it.
      • The <div id="app"></div> container where our VueJS app will be bound.

      The src Folder

      The src/ folder is where most of your work will be done. The src/main.js file will serve as the entry point for webpack’s build process:

      src/main.js
      1
      2
      3
      4
      5
      6
      7
      8
      9
      
      import Vue from 'vue'
      import App from './App.vue'
      
      Vue.config.productionTip = false
      
      new Vue({
          render: h => h(App),
      }).$mount('#app')
      

      This file imports VueJS (line 1), imports the App component from the src folder (line 2), and binds the App component to the container with the id property set to app (lines 6-8).

      Now to the interesting part: src/App.vue:

      src/App.vue
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      
      <template>
          <div id="app">
              <img alt="Vue logo" src="./assets/logo.png" />
              <HelloWorld msg="Welcome to Your Vue.js App" />
          </div>
      </template>
      
      <script>
      import HelloWorld from "./components/HelloWorld.vue";
      export default {
          name: "App",
          components: {
              HelloWorld,
          },
      };
      </script>
      
      <style>
      #app {
          font-family: Avenir, Helvetica, Arial, sans-serif;
          -webkit-font-smoothing: antialiased;
          -moz-osx-font-smoothing: grayscale;
          text-align: center;
          color: #2c3e50;
          margin-top: 60px;
      }
      </style>

      This is a simple single file component relatively similar to the example we discussed above, but this example shows how to import and use components:

      • On line 9, the HelloWorld component is imported.
      • On lines 12-14, the HelloWorld component is locally registered for use within the App component. The registered component can only be used in the template of the parent component that registered it. Contrast this with the components in Building and Using VueJS Components, which were globally registered.

        Note

        Local registration is a valuable architectural feature for reusable components within big projects.

      • The HelloWorld component is used within the App component’s template on line 4.

      Building your First Single File Components

      Now that we’ve covered the basic structure of the project created by Vue CLI, let’s build our own components on top of that. As in Building and Using VueJS Components, we will again be building a rating application, but this time it will be a little more sophisticated.

      This is what your rating app will look like:

      Rating App - Finished Product

      This is how it will behave:

      • Clicking on a star on the left side will register a vote for that star.

      • The left side will interactively change when a user hovers over the stars.

      • It will allow the user to rate only once on each visit to the page. If the page is refreshed, or if it is visited again later, the user can vote again.

      • It will keep score of votes between page visits in the browser’s local storage.

      Here’s how the app’s template will look in protocode; you do not need to copy and paste this:

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      
      <div id="app">
          <div class="inner">
              <div class="ratingContainer">
                  <span class="bigRating"></span>
                  <div class="rating-stars">
                      <Star weight="1"></Star>
                      <Star weight="2"></Star>
                      <Star weight="3"></Star>
                      <Star weight="4"></Star>
                      <Star weight="5"></Star>
                  </div>
              </div>
              <Summary></Summary>
          </div>
      </div>

      We’ll make each star a separate component (named Star), and we’ll also create a Summary component which will hold the summary of the votes.

      App.vue

      To start, replace the content of your App.vue with this snippet:

      src/App.vue
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      
      <template>
          <div id="app">
              <div class="inner">
                  <div class="ratingContainer">
                      <span class="bigRating" v-html="bigRating"></span>
                      <div>
                          <Star
                              v-for="index in 5"
                              v-bind:key="index"
                              v-bind:weight="index"
                              v-bind:enabled="enabled"
                              v-bind:currentRating="currentRating"
                          ></Star>
                      </div>
                  </div>
                  <Summary v-bind:ratings="ratings"></Summary>
              </div>
          </div>
      </template>
      
      <script>
      import Star from "./components/Star.vue";
      import Summary from "./components/Summary.vue";
      
      export default {
          name: "App",
          components: { Star, Summary },
          data: function () {
              return {
                  currentRating: 0,
                  bigRating: "&#128566;", // Emoji: 😶
                  enabled: true,
                  ratings: [
                      {
                          weight: 1,
                          votes: 0,
                      },
                      {
                          weight: 2,
                          votes: 0,
                      },
                      {
                          weight: 3,
                          votes: 0,
                      },
                      {
                          weight: 4,
                          votes: 0,
                      },
                      {
                          weight: 5,
                          votes: 0,
                      },
                  ],
              };
          },
          methods: {},
          created: function () {
              if (localStorage.ratings) {
                  this.ratings = JSON.parse(localStorage.ratings);
              }
          },
      };
      </script>
      
      <style>
      @import url(https://fonts.googleapis.com/css?family=Roboto:100, 300, 400);
      @import url(https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css);
      #app {
          width: 400px;
      }
      .ratingContainer {
          float: left;
          width: 45%;
          margin-right: 5%;
          text-align: center;
      }
      .bigRating {
          color: #333333;
          font-size: 72px;
          font-weight: 100;
          line-height: 1em;
          padding-left: 0.1em;
      }
      </style>

      This is the main component, but there are no methods set on it yet, so for now it doesn’t have any functionality. Here are some notable parts of the code:

      • <template>:

        • On lines 7-13, all five Star components are rendered from a single <Star> declaration with the v-for="index in 5" syntax. A weight is assigned to each Star by the v-bind:weight="index" syntax. The key attribute is also bound to the index. The enabled and currentRating props will be bound to values that are described in the <script> section.

          Note

          The v-for syntax is similar to the following for loop: for(let index=1;index<=5;index++).

        • On line 16, the Summary component is rendered. It will display data from the bound ratings property.

      • <script>

        • Lines 22 and 23 import the Star and Summary components, which are then registered on line 27. These will be created separately in the next section.

        • The data function is declared on lines 28-56, and it contains the following variables which will control the functionality of the app once the methods are added later:

          • currentRating: As we hover over the stars, we will use this variable to store the rating of the hovered star.

          • bigRating: This will be set to an emoticon that represents the currentRating.

          • enabled: This will be used to disable the rating application once the user has cast a vote.

          • ratings: This is a structure for the votes that have been cast. We set the default value in the data function, and if there are any votes saved in the browser’s localStorage, then we overwrite the defaults, which imitates a persistence layer. In the created hook (lines 58-62) you can see how we fetch the saved cast votes.

      Star.vue and Summary.vue

      In your src/components/ directory, create two files named Star.vue and Summary.vue and paste these snippets into them:

      src/components/Star.vue
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      
      <template>
          <i class="icon-star"></i>
      </template>
      
      <script>
      export default {
          name: "Star",
          props: ["weight", "enabled", "currentRating"]
      };
      </script>
      
      <style scoped>
      i.icon-star {
          font-size: 20px;
          color: #e3e3e3;
          margin-bottom: 0.5em;
      }
      </style>
      src/components/Summary.vue
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      
      <template>
          <div class="summaryContainer">
              <ul>
                  <li v-for="rating in ratings" v-bind:key="rating.weight">
                      {{ rating.weight }}<i class="icon-star"></i>: {{ rating.votes }}
                  </li>
              </ul>
          </div>
      </template>
      
      <script>
      export default {
          name: "Summary",
          props: ["ratings"]
      };
      </script>
      
      <style scoped>
      .summaryContainer {
          float: left;
          width: 50%;
          font-size: 13px;
      }
      </style>

      Here are some notable parts of the code:

      • In both components, the Font Awesome icon-star is used. On lines 13-17 of Star.vue, some styling is set for the icons in the Star component, including setting the color to light grey.

        Because this style section uses the scoped attribute, these styles are limited to the Star component. As a result, the icons in the Summary component are not also styled in this way.

      • On lines 4-6 of Summary.vue, the v-for syntax is used again to display the rating votes.

      After creating Star.vue and Summary.vue, the application can be viewed in the browser. Head to http://127.0.0.1:8080 and you will see the following:

      Rating App - No Votes, Noninteractive

      Because there are no methods set on the components yet, it will not be interactive.

      Note

      If you’re not still running npm run serve in your terminal, you’ll need to re-run it from inside your project.

      Adding Methods to the Components

      The application right now is a skeleton, so now we’ll make it work. These three custom events will be handled:

      • When you hover over a star, all previous stars will be highlighted in yellow. For example, if you hover over the star number 4, stars 1-3 also get highlighted.

      • When your mouse moves away, the highlight will be removed.

      • When you click on a star, a vote is cast and you no longer can vote until you visit the page again.

      Updating App.vue

      1. Update the Star component declaration in the <template> of src/App.vue to match this snippet:

        src/App.vue
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        
        <!-- ... --->
        <Star
            v-for="index in 5"
            v-bind:key="index"
            v-bind:weight="index"
            v-bind:enabled="enabled"
            v-bind:currentRating="currentRating"
            v-on:lightUp="lightUpHandler"
            v-on:lightDown="lightDownHandler"
            v-on:rate="rateHandler"
        ></Star>
        <!-- ... --->

        The new additions to this declaration are the v-on directives, which set methods as event handlers for the custom lightUp, lightDown, and rate events.

        Note

        The Star component will be updated in the next section to emit those events.

      2. Next, replace the methods object in the component with the following snippet. These are the event handlers:

        src/App.vue
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        
        // ...
        methods: {
            lightUpHandler: function (weight) {
                this.currentRating = weight;
        
                // Display different emojis based on the weight
                if (weight <= 2) {
                    this.bigRating = "&#128549;"; // Emoji: 😥
                }
                if (weight > 2 && weight <= 4) {
                    this.bigRating = "&#128556;"; // Emoji: 😬
                }
                if (weight > 4) {
                    this.bigRating = "&#128579;"; // Emoji: 🙃
                }
            },
            lightDownHandler: function () {
                // Reset on mouse away
                this.currentRating = 0;
                this.bigRating = "&#128566;"; // Emoji: 😶
            },
            rateHandler: function (weight) {
                this.currentRating = weight;
        
                // Finding the relevant rating and incrementing the cast votes
                let rating = this.ratings.find((obj) => obj.weight == weight);
                rating.votes++;
        
                // Disabling from voting again
                this.enabled = false;
        
                // Saves the votes to the browser localStorage
                localStorage.setItem("ratings", JSON.stringify(this.ratings));
            },
        },
        // ...
        
        • The lightUpHandler and rateHandler methods receive a weight from the Star component that emitted the corresponding event. These methods set the weight as the currentRating.

        • At the end of the rateHandler method, the component’s ratings are converted to a JSON object and saved so we can use them as a starting point the next time the page loads (line 33).

        Full contents of App.vue

        At this point, your App.vue should be the same as this snippet:

        src/App.vue
          1
          2
          3
          4
          5
          6
          7
          8
          9
         10
         11
         12
         13
         14
         15
         16
         17
         18
         19
         20
         21
         22
         23
         24
         25
         26
         27
         28
         29
         30
         31
         32
         33
         34
         35
         36
         37
         38
         39
         40
         41
         42
         43
         44
         45
         46
         47
         48
         49
         50
         51
         52
         53
         54
         55
         56
         57
         58
         59
         60
         61
         62
         63
         64
         65
         66
         67
         68
         69
         70
         71
         72
         73
         74
         75
         76
         77
         78
         79
         80
         81
         82
         83
         84
         85
         86
         87
         88
         89
         90
         91
         92
         93
         94
         95
         96
         97
         98
         99
        100
        101
        102
        103
        104
        105
        106
        107
        108
        109
        110
        111
        112
        113
        114
        115
        116
        117
        118
        119
        120
        121
        
        <template>
            <div id="app">
                <div class="inner">
                    <div class="ratingContainer">
                        <span class="bigRating" v-html="bigRating"></span>
                        <div>
                            <Star
                                v-for="index in 5"
                                v-bind:key="index"
                                v-bind:weight="index"
                                v-bind:enabled="enabled"
                                v-bind:currentRating="currentRating"
                                v-on:lightUp="lightUpHandler"
                                v-on:lightDown="lightDownHandler"
                                v-on:rate="rateHandler"
                            ></Star>
                        </div>
                    </div>
                    <Summary v-bind:ratings="ratings"></Summary>
                </div>
            </div>
        </template>
        
        <script>
        import Star from "./components/Star.vue";
        import Summary from "./components/Summary.vue";
        
        export default {
            name: "App",
            components: { Star, Summary },
            data: function () {
                return {
                    currentRating: 0,
                    bigRating: "&#128566;", // Emoji: 😶
                    enabled: true,
                    ratings: [
                        {
                            weight: 1,
                            votes: 0,
                        },
                        {
                            weight: 2,
                            votes: 0,
                        },
                        {
                            weight: 3,
                            votes: 0,
                        },
                        {
                            weight: 4,
                            votes: 0,
                        },
                        {
                            weight: 5,
                            votes: 0,
                        },
                    ],
                };
            },
            methods: {
                lightUpHandler: function (weight) {
                    this.currentRating = weight;
        
                    // Display different emojis based on the weight
                    if (weight <= 2) {
                        this.bigRating = "&#128549;"; // Emoji: 😥
                    }
                    if (weight > 2 && weight <= 4) {
                        this.bigRating = "&#128556;"; // Emoji: 😬
                    }
                    if (weight > 4) {
                        this.bigRating = "&#128579;"; // Emoji: 🙃
                    }
                },
                lightDownHandler: function () {
                    // Reset on mouse away
                    this.currentRating = 0;
                    this.bigRating = "&#128566;"; // Emoji: 😶
                },
                rateHandler: function (weight) {
                    this.currentRating = weight;
        
                    // Finding the relevant rating and incrementing the cast votes
                    let rating = this.ratings.find((obj) => obj.weight == weight);
                    rating.votes++;
        
                    // Disabling from voting again
                    this.enabled = false;
        
                    // Saves the votes to the browser localStorage
                    localStorage.setItem("ratings", JSON.stringify(this.ratings));
                },
            },
            created: function () {
                if (localStorage.ratings) {
                    this.ratings = JSON.parse(localStorage.ratings);
                }
            },
        };
        </script>
        
        <style>
        @import url(https://fonts.googleapis.com/css?family=Roboto:100, 300, 400);
        @import url(https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css);
        #app {
            width: 400px;
        }
        .ratingContainer {
            float: left;
            width: 45%;
            margin-right: 5%;
            text-align: center;
        }
        .bigRating {
            color: #333333;
            font-size: 72px;
            font-weight: 100;
            line-height: 1em;
            padding-left: 0.1em;
        }
        </style>

      Updating Star.vue

      Let’s modify the Star component to emit the events:

      1. In the template of Star.vue, replace the <i> element with this snippet:

        src/components/Star.vue
        1
        2
        3
        4
        5
        6
        7
        8
        
        <!-- ... --->
        <i
            v-bind:class="getClass()"
            v-on:mouseover="mouseoverHandler"
            v-on:mouseleave="mouseleaveHandler"
            v-on:click="clickHandler"
        ></i>
        <!-- ... --->
        • The CSS classes of the icon will now be dynamically generated by a getClass method on the component. This change is made so that the hover highlight effect can be toggled by a CSS class.

        • The mouseover, mouseleave, and click DOM events are associated with new handler methods that will also be added to the component.

      2. In the script section, add this data function to the component:

        src/components/Star.vue
        1
        2
        3
        4
        5
        6
        7
        8
        
        // ...
        data: function () {
            return {
                hover: false,
            };
        },
        // ...
        

        The hover variable will maintain the hover state of the component.

      3. Also in the script section, add this methods object to the component:

        src/components/Star.vue
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        
        // ...
        methods: {
            getClass: function () {
                var baseClass = "icon-star";
        
                // Adds the hover class if you're hovering over the component or you are hovering over a star with greater weight
                if (this.hover || this.currentRating >= this.weight) {
                    baseClass += " hover";
                }
                return baseClass;
            },
            mouseoverHandler: function () {
                // Makes sure stars are not lighting up after vote is cast
                if (this.enabled) {
                    // Emits the lightUp event with the weight as a parameter
                    this.$emit("lightUp", this.weight);
                    // Enables hover class
                    this.hover = true;
                }
            },
            mouseleaveHandler: function () {
                // Makes sure stars are not lighting up after vote is cast
                if (this.enabled) {
                    // Emits the lightDown event
                    this.$emit("lightDown", this.weight);
                    // Removes hover class
                    this.hover = false;
                }
            },
            clickHandler: function () {
                // Makes sure you only vote if you haven't voted yet
                if (this.enabled) {
                    // Emits the rate event with the weight as parameter
                    this.$emit("rate", this.weight);
                } else {
                    alert("Already voted");
                }
            },
        },
        // ...
        
        • The mouseoverHandler, mouseleaveHandler, and clickHandler methods will emit the lightUp, lightDown, and rate custom events, respectively.

        • These methods also first check to see if enabled has been set to false; if false, then the methods do nothing, which means that the DOM events will result in no action.

        • In the getClass method, the currentRating prop is used to determine if a star icon should be highlighted. This prop was previously bound to the currentRating data property of the App component.

          Note

          The currentRating prop is not a particularly beautiful solution, but we will improve on that further in the guide.

      4. Finally, add this rule to the style section:

        src/components/Star.vue
        1
        2
        3
        4
        5
        6
        
        /* ... */
        i.icon-star.hover {
            color: yellow;
        }
        /* ... */
        

        Full contents of Star.vue

        At this point, your Star.vue should be the same as this snippet:

        src/components/Star.vue
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        57
        58
        59
        60
        61
        62
        63
        64
        65
        66
        67
        68
        69
        
        <template>
            <i
                v-bind:class="getClass()"
                v-on:mouseover="mouseoverHandler()"
                v-on:mouseleave="mouseleaveHandler()"
                v-on:click="clickHandler()"
            ></i>
        </template>
        
        <script>
        export default {
            name: "Star",
            data: function () {
                return {
                    hover: false,
                };
            },
            props: ["weight", "enabled", "currentRating"],
            methods: {
                getClass: function () {
                    var baseClass = "icon-star";
        
                    // Adds the hover class if you're hovering over the component or you are hovering over a star with greater weight
                    if (this.hover || this.currentRating >= this.weight) {
                        baseClass += " hover";
                    }
                    return baseClass;
                },
                mouseoverHandler: function () {
                    // Makes sure stars are not lighting up after vote is cast
                    if (this.enabled) {
                        // Emits the lightUp event with the weight as a parameter
                        this.$emit("lightUp", this.weight);
                        // Enables hover class
                        this.hover = true;
                    }
                },
                mouseleaveHandler: function () {
                    // Makes sure stars are not lighting up after vote is cast
                    if (this.enabled) {
                        // Emits the lightDown event
                        this.$emit("lightDown", this.weight);
                        // Removes hover class
                        this.hover = false;
                    }
                },
                clickHandler: function () {
                    // Makes sure you only vote if you haven't voted yet
                    if (this.enabled) {
                        // Emits the rate event with the weight as parameter
                        this.$emit("rate", this.weight);
                    } else {
                        alert("Already voted");
                    }
                },
            },
        };
        </script>
        
        <style scoped>
        i.icon-star {
            font-size: 20px;
            color: #e3e3e3;
            margin-bottom: 0.5em;
        }
        i.icon-star.hover {
            color: yellow;
        }
        </style>
      5. Head to http://localhost:8080/ in your browser, and you should see that your rating application now works. Try hovering over the stars and clicking on them to observe the interaction. If you refresh the page, you can vote again, and the votes will be tallied:

      Rating App - With Rating Interaction

      Communication between Components Via an Event Bus

      Notice how clumsy all of the v-on directives chained one after the other look:

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      
      <Star
          v-for="index in 5"
          v-bind:key="index"
          v-bind:weight="index"
          v-bind:enabled="enabled"
          v-bind:currentRating="currentRating"
          v-on:lightUp="lightUpHandler"
          v-on:lightDown="lightDownHandler"
          v-on:rate="rateHandler"
      ></Star>

      This setup can be inelegant to scale: imagine having 10 of those on a single component, and then imagine you have 10 components. The directives would become hard to follow, so it’s worth exploring other ways to communicate between components.

      Fortunately, VueJS supports a publish-subscribe pattern called an event bus. You can easily implement it in your components to make things a bit more elegant.

      Event Bus Basics

      In VueJS, an event bus is a new Vue instance that is declared globally (in main.js, for example):

      src/main.js
      1
      2
      3
      4
      
      // ...
      export const eventBus = new Vue();
      // ...
      

      It is then imported in each component which accesses it:

      AnyComponent.vue
      1
      2
      3
      4
      
      // ...
      import { eventBus } from "../main.js";
      // ...
      

      Components can emit events to the event bus:

      SomeComponent.vue
      1
      2
      3
      4
      
      // ...
      eventBus.$emit("event", parameter);
      // ...
      

      Other components will register event handlers on the same event bus with the $on method:

      AnotherComponent.vue
      1
      2
      3
      4
      5
      6
      
      // ...
      eventBus.$on("event", (parameter) => {
          // Do stuff
      });
      // ...
      

      Basically, think of the event bus as a global communication layer between your components.

      Adding an Event Bus to your App

      Now let’s rebuild our example to take advantage of an event bus:

      1. Open main.js and replace its content with this snippet:

        src/main.js
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        
        import Vue from "vue";
        import App from "./App.vue";
        
        Vue.config.productionTip = false;
        
        export const eventBus = new Vue();
        
        new Vue({
            render: h => h(App)
        }).$mount("#app");
        

        This update adds an event bus declaration on line 6.

      2. Open App.vue and replace its content with this snippet:

        src/App.vue
          1
          2
          3
          4
          5
          6
          7
          8
          9
         10
         11
         12
         13
         14
         15
         16
         17
         18
         19
         20
         21
         22
         23
         24
         25
         26
         27
         28
         29
         30
         31
         32
         33
         34
         35
         36
         37
         38
         39
         40
         41
         42
         43
         44
         45
         46
         47
         48
         49
         50
         51
         52
         53
         54
         55
         56
         57
         58
         59
         60
         61
         62
         63
         64
         65
         66
         67
         68
         69
         70
         71
         72
         73
         74
         75
         76
         77
         78
         79
         80
         81
         82
         83
         84
         85
         86
         87
         88
         89
         90
         91
         92
         93
         94
         95
         96
         97
         98
         99
        100
        101
        102
        103
        104
        105
        106
        107
        108
        109
        110
        
        <template>
            <div id="app">
                <div class="inner">
                    <div class="ratingContainer">
                        <span class="bigRating" v-html="bigRating"></span>
                        <div>
                            <Star
                                v-for="index in 5"
                                v-bind:key="index"
                                v-bind:weight="index"
                                v-bind:enabled="enabled"
                            ></Star>
                        </div>
                    </div>
                    <Summary v-bind:ratings="ratings"></Summary>
                </div>
            </div>
        </template>
        
        <script>
        import Star from "./components/Star.vue";
        import Summary from "./components/Summary.vue";
        
        import { eventBus } from "./main.js";
        
        export default {
            name: "App",
            components: { Star, Summary },
            data: function () {
                return {
                    bigRating: "&#128566;", // Emoji: 😶
                    enabled: true,
                    ratings: [
                        {
                            weight: 1,
                            votes: 0,
                        },
                        {
                            weight: 2,
                            votes: 0,
                        },
                        {
                            weight: 3,
                            votes: 0,
                        },
                        {
                            weight: 4,
                            votes: 0,
                        },
                        {
                            weight: 5,
                            votes: 0,
                        },
                    ],
                };
            },
            created: function () {
                if (localStorage.ratings) {
                    this.ratings = JSON.parse(localStorage.ratings);
                }
                eventBus.$on("lightUp", (weight) => {
                    // Display different emojis based on the weight
                    if (weight <= 2) {
                        this.bigRating = "&#128549;"; // Emoji: 😥
                    }
                    if (weight > 2 && weight <= 4) {
                        this.bigRating = "&#128556;"; // Emoji: 😬
                    }
                    if (weight > 4) {
                        this.bigRating = "&#128579;"; // Emoji: 🙃
                    }
                });
                eventBus.$on("lightDown", () => {
                    this.bigRating = "&#128566;"; // Emoji: 😶
                });
                eventBus.$on("rate", (weight) => {
                    // Finding the relevant rating and incrementing the cast votes
                    let rating = this.ratings.find((obj) => obj.weight == weight);
                    rating.votes++;
        
                    // Disabling from voting again
                    this.enabled = false;
        
                    // Saves the votes to the browser localStorage
                    localStorage.setItem("ratings", JSON.stringify(this.ratings));
                });
            },
        };
        </script>
        
        <style>
        @import url(https://fonts.googleapis.com/css?family=Roboto:100, 300, 400);
        @import url(https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css);
        #app {
            width: 400px;
        }
        .ratingContainer {
            float: left;
            width: 45%;
            margin-right: 5%;
            text-align: center;
        }
        .bigRating {
            color: #333333;
            font-size: 72px;
            font-weight: 100;
            line-height: 1em;
            padding-left: 0.1em;
        }
        </style>

        The following changes have been made in this updated file:

        • The eventBus instance is imported on line 24.
        • We removed the v-on directives from the Star component declaration in the template (lines 7-12).
        • The component’s methods have been removed, which previously served as the event handlers for the v-on directives.
        • Instead, we subscribe to the events in the created hook (lines 61-86). The logic that was in the component’s methods has been moved here.
        • We also no longer need the currentRating data property, so it has been removed. This is because the Star components will also subscribe to the event bus and can be directly notified of all lightUp and rate events.

        The template looks much leaner now, and you can easily spot the subscribed events by simply having a look in the created hook.

      3. Open Star.vue and replace its content with this snippet:

        src/components/Star.vue
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        57
        58
        59
        60
        61
        62
        63
        64
        65
        66
        67
        68
        69
        70
        71
        72
        73
        74
        75
        76
        77
        78
        79
        80
        81
        82
        83
        84
        85
        86
        87
        88
        89
        
        <template>
            <i
                v-bind:class="getClass()"
                v-on:mouseover="mouseoverHandler"
                v-on:mouseleave="mouseleaveHandler"
                v-on:click="clickHandler"
            ></i>
        </template>
        
        <script>
        import { eventBus } from "../main.js";
        
        export default {
            name: "Star",
            data: function () {
                return {
                    hover: false,
                    active: false,
                };
            },
            props: ["weight", "enabled"],
            methods: {
                getClass: function () {
                    var baseClass = "icon-star";
                    if (this.active) {
                        baseClass += " active";
                    }
                    if (this.hover) {
                        baseClass += " hover";
                    }
                    return baseClass;
                },
                mouseoverHandler: function () {
                    // Makes sure stars are not lighting up after vote is cast
                    if (this.enabled) {
                        // Emits the lightUp event with the weight as a parameter
                        eventBus.$emit("lightUp", this.weight);
                    }
                },
                mouseleaveHandler: function () {
                    // Makes sure stars are not lighting up after vote is cast
                    if (this.enabled) {
                        // Emits the lightDown event
                        eventBus.$emit("lightDown");
                    }
                },
                clickHandler: function () {
                    // Makes sure you only vote if you haven't voted yet
                    if (this.enabled) {
                        // Emits the rate event with the weight as parameter
                        eventBus.$emit("rate", this.weight);
                    } else {
                        alert("Already voted");
                    }
                },
            },
            created: function () {
                eventBus.$on("lightUp", (targetWeight) => {
                    if (targetWeight >= this.weight) {
                        this.hover = true;
                    } else {
                        this.hover = false;
                    }
                });
                eventBus.$on("lightDown", () => {
                    this.hover = false;
                });
                eventBus.$on("rate", (targetWeight) => {
                    if (targetWeight >= this.weight) {
                        this.active = true;
                    }
                });
            },
        };
        </script>
        
        <style scoped>
        i.icon-star {
            font-size: 20px;
            color: #e3e3e3;
            margin-bottom: 0.5em;
        }
        i.icon-star.hover {
            color: yellow;
        }
        i.icon-star.active {
            color: #737373;
        }
        </style>

        The following changes have been made in this updated file:

        • The eventBus instance is imported on line 11.
        • The currentRating prop has been removed (line 21).
        • We’ve modified the handler methods to emit the events on the eventBus instance (lines 22-56)
        • We also subscribe to the same events from the created hook (lines 57-73), so that all Star components are aware of which component the user is currently hovering over without needing the currentRating prop.
        • We’ve added an active class to the component’s style (lines 86-88). This is enabled when a user enters a rating, and it sets a different highlight color for the stars. To enable the class, an active data property has been added to the component (line 18), and it is set to true within the rate event handling logic (line 70).

        Rating App - With Event Bus

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      This guide is published under a CC BY-ND 4.0 license.



      Source link

      Ansible Adhoc Commands – A Tutorial


      Updated by Linode Contributed by Avi

      Marquee image for Ansible Adhoc Commands - A Tutorial

      In this tutorial, you’ll learn about several Ansible adhoc commands which are used by system and devops engineers.

      Adhoc commands are commands which you run from the command line, outside of a playbook. These commands run on one or more managed nodes and perform a simple/quick task–most often, these will be tasks that you don’t need to repeat. For example, if you want to reload Apache across a cluster of web servers, you can run a single adhoc command to achieve that task.

      Note

      In Ansible, all modules can be executed in either a playbook or through an adhoc command.

      The basic syntax for invoking an adhoc command is:

      ansible host_pattern -m module_name -a "module_options"
      

      Before You Begin

      To run the commands in this tutorial, you’ll need:

      • A workstation or server with the Ansible command line tool installed on it that will act as the control node. The Set Up the Control Node section of the Getting Started With Ansible guide has instructions for setting up a Linode as a control node. Installation instructions for non-Linux distributions can be found on the Ansible documentation site.

      • At least one other server that will be managed by Ansible. Some commands in this guide will target a non-root user on this server. This user should have sudo privileges. There are a couple options for setting up this user:

      Note

      The commands in this guide will be run from the control node and will target a host named Client. Your control node’s Ansible inventory should be configured so that at least one of your managed nodes has this name. The Create an Ansible Inventory section of the Getting Started With Ansible guide outlines how to set up an inventory file.

      Note

      Alternatively, you can modify the commands in this guide to use a different host name.

      Basic Commands

      Ping

      To check that you can reach your managed node, use the ping module:

      ansible -m ping Client
      
        
      node1 | SUCCESS => {
          "ansible_facts": {
              "discovered_interpreter_python": "/usr/bin/python"
          },
          "changed": false,
          "ping": "pong"
      }
      
      

      Run with Privilege Escalation

      This adhoc command demonstrates how a non-root user on the managed node can gain the privileges of a root user when executing a module. Specifically, this example shows how to use privilege escalation to run the fdisk command through the shell module:

      ansible Client -m shell -a 'fdisk -l' -u non_root_user --become -K
      
        
      BECOME password:
      node1 | CHANGED | rc=0 >>
      Disk /dev/sda: 79.51 GiB, 85362475008 bytes, 166723584 sectors
      Disk model: QEMU HARDDISK
      Units: sectors of 1 * 512 = 512 bytes
      Sector size (logical/physical): 512 bytes / 512 bytes
      I/O size (minimum/optimal): 512 bytes / 512 bytes
      Disk /dev/sdb: 512 MiB, 536870912 bytes, 1048576 sectors
      Disk model: QEMU HARDDISK
      Units: sectors of 1 * 512 = 512 bytes
      Sector size (logical/physical): 512 bytes / 512 bytes
      I/O size (minimum/optimal): 512 bytes / 512 bytes
      
      
      • The -u option is used to specify the user on the managed node.

        Note

        By default, Ansible will try to establish a connection to the managed node under the same user that you execute the Ansible CLI with on the control node.

      • The --become option is used to execute the command with the privileges of the root user.

      • The -K option is used to prompt for the privilege escalation password of the user.

      Reboot a Managed Node

      Below is a command that reboots the managed node:

      ansible Client -a "/sbin/reboot" -f 1
      

      This command omits the -m option that specifies the module. When the module is not specified, the command module is the default that’s used.

      The command module is similar to the shell module in that both will execute a command that you pass to it. The shell module will run the command through a shell on the managed node, while the command module will not run it through a shell.

      Note

      The -f option is used to define number of forks that Ansible will use on the control node when running your command.

      Note

      If your managed node is a Linode, then Linode’s shutdown watchdog Lassie needs to be enabled for the reboot to succeed. This is because a Linode is not able to turn itself on–instead, Linode’s host environment must boot the Linode.

      Collecting System Diagnostics

      Check Free Disk Space

      This command is used to check the free disk space on all of a managed node’s mounted disks. It lists all the filesystems present on the managed node along with the filesystem size, space used, and space available in a human-readable format:

      ansible Client -a "df -h"
      
        
      node1 | CHANGED | rc=0 >>
      Filesystem      Size  Used Avail Use% Mounted on
      udev            1.9G     0  1.9G   0% /dev
      tmpfs           394M  596K  394M   1% /run
      /dev/sda         79G  2.6G   72G   4% /
      tmpfs           2.0G  124K  2.0G   1% /dev/shm
      tmpfs           5.0M     0  5.0M   0% /run/lock
      tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
      tmpfs           394M     0  394M   0% /run/user/0
      
      

      This command checks the available and used space on a specific filesystem:

      ansible Client -m shell -a 'df -h /dev/sda'
      
        
      node1 | CHANGED | rc=0 >>
      Filesystem      Size  Used Avail Use% Mounted on
      /dev/sda         79G  2.6G   72G   4% /
      
      

      Check Memory and CPU Usage

      Use the free command with the shell module to see the free and used memory of your managed node in megabytes:

      ansible Client -m shell -a 'free -m'
      
        
      node1 | CHANGED | rc=0 >>
                    total        used        free      shared  buff/cache   available
      Mem:           3936         190        3553           0         192        3523
      Swap:           511           0         511
      
      

      Use the mpstat command with the shell module to check CPU usage:

      ansible Client -m shell -a 'mpstat -P ALL'
      
        
      node1 | CHANGED | rc=0 >>
      Linux 5.3.0-40-generic (localhost)      03/21/2020      _x86_64_        (2 CPU)
      
      07:41:27 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
      07:41:27 PM  all    0.96    0.00    0.72    0.08    0.00    0.02    0.01    0.00    0.00   98.21
      07:41:27 PM    0    0.93    0.00    0.73    0.06    0.00    0.03    0.01    0.00    0.00   98.24
      07:41:27 PM    1    1.00    0.00    0.71    0.09    0.00    0.01    0.01    0.00    0.00   98.17
      
      

      Check System Uptime

      This Ansible command will show how long your managed nodes have been up and running:

      ansible Client -a "uptime"
      
        
      node1 | CHANGED | rc=0 >>
       19:40:11 up 8 min,  2 users,  load average: 0.00, 0.02, 0.00
      
      

      File Transfer

      Copy Files

      The copy module is used to transfer a file or directory from the control node to your managed nodes by defining the source and destination paths. You can define the file owner and file permissions in the command:

      cd ~
      echo "Hello World" > test.txt
      ansible Client -m copy -a 'src=test.txt dest=/etc/ owner=root mode=0644' -u non_root_user --become -K
      
        
      BECOME password:
      node1 | CHANGED => {
          "ansible_facts": {
              "discovered_interpreter_python": "/usr/bin/python"
          },
          "changed": true,
          "checksum": "13577023221e91069c21d8f10a4b90f8192d6a26",
          "dest": "/etc/test",
          "gid": 0,
          "group": "root",
          "md5sum": "eb662c21e683b643f0fcb5997d7bbccf",
          "mode": "0644",
          "owner": "root",
          "size": 18,
          "src": "/root/.ansible/tmp/ansible-tmp-1584820375.14-54524496813834/source",
          "state": "file",
          "uid": 0
      }
      
      

      You can also use Ansible to check whether your file got copied to your destination location:

      sudo ansible Client -m shell -a 'ls -l /etc/test*'
      
        
      node1 | CHANGED | rc=0 >>
      -rw-r--r-- 1 root root 12 Jun  1 22:35 /etc/test.txt
      
      

      Fetch Files

      The fetch module is used to transfer a file from a managed node to the control node. After the command runs successfully, the changed variable in Ansible’s output will be set to true.

      ansible Client -m fetch -a 'src=/etc/test.txt dest=/etc/'
      
        
      node1 | CHANGED => {
          "changed": true,
          "checksum": "648a6a6ffffdaa0badb23b8baf90b6168dd16b3a",
          "dest": "/etc/192.0.2.4/etc/test.txt",
          "md5sum": "e59ff97941044f85df5297e1c302d260",
          "remote_checksum": "648a6a6ffffdaa0badb23b8baf90b6168dd16b3a",
          "remote_md5sum": null
      }
      
      

      Note that the fetched file was placed into /etc/192.0.2.4/etc/test.txt. By default, the fetch module will put fetched files into separate directories for each hostname that you’re fetching from. This prevents a file from one managed node from overwriting the file from another managed node.

      To avoid creating these directories, include the flat=yes option:

      ansible Client -m fetch -a 'src=/etc/test.txt dest=/etc/ flat=yes'
      
        
      node1 | SUCCESS => {
          "changed": false,
          "checksum": "648a6a6ffffdaa0badb23b8baf90b6168dd16b3a",
          "dest": "/etc/test.txt",
          "file": "/etc/test.txt",
          "md5sum": "e59ff97941044f85df5297e1c302d260"
      }
      
      

      Create Directories

      The file module is used to create, remove, and set permissions on files and directories, and create symlinks. This command will create a directory at /root/linode/new/ on the the managed node with the owner and permissions defined in the options:

      ansible Client -m file -a "dest=/root/linode/new/ mode=755 owner=root group=root state=directory" -u non_root_user --become -K
      
        
      node1 | CHANGED => {
          "ansible_facts": {
              "discovered_interpreter_python": "/usr/bin/python"
          },
          "changed": true,
          "gid": 0,
          "group": "root",
          "mode": "0755",
          "owner": "root",
          "path": "/root/linode/new",
          "size": 4096,
          "state": "directory",
          "uid": 0
      }
      
      

      Note that all intermediate directories that did not exist will also be created. In this example, if the linode/ subdirectory did not already exist, then it was created.

      Managing Packages

      Install a Package

      The package module can be used to install a new package on the managed node. This command installs the latest version of NGINX:

      ansible Client -m package -a 'name=nginx state=present' -u non_root_user --become -K
      
        
      node1 | CHANGED => {
          "ansible_facts": {
              "discovered_interpreter_python": "/usr/bin/python"
          },
          "cache_update_time": 1584821061,
          "cache_updated": false,
          "changed": true,
          "stderr": "",
          "stderr_lines": [],
          "stdout": "Reading package lists...nBuilding dependency tree...
              "Unpacking nginx (1.16.1-0ubuntu2.1) ...",
              "Setting up libxpm4:amd64 (1:3.5.12-1) ...",
              "Setting up nginx-common (1.16.1-0ubuntu2.1) ...",
              "Setting up nginx-core (1.16.1-0ubuntu2.1) ...",
              "Setting up nginx (1.16.1-0ubuntu2.1) ...",
          ]
      }
      
      

      Note

      The package module works across distributions. There are also modules for specific package managers (e.g. the apt module and the yum module). These modules offer more options that are specific to those package managers.

      Uninstall a Package

      To uninstall a package, set state=absent in the command’s options:

      ansible Client -m package -a 'name=nginx state=absent' -u non_root_user --become -K
      
        
      node1 | CHANGED => {
          "ansible_facts": {
              "discovered_interpreter_python": "/usr/bin/python"
          },
          "changed": true,
          "stderr": "",
          "stderr_lines": [],
          "stdout": "Reading package lists...nBuilding dependency tree …
              "  nginx-core",
              "Use 'sudo apt autoremove' to remove them.",
              "The following packages will be REMOVED:",
              "  nginx*",
              "Removing nginx (1.16.1-0ubuntu2.1) ..."
          ]
      }
      
      

      Managing Services

      Start a Service

      Use the service module to start a service on the managed node. This command will start and enable the NGINX service:

      ansible Client -m service -a 'name=nginx state=started enabled=yes' -u non_root_user --become -K
      
        
      node1 | SUCCESS => {
          "ansible_facts": {
              "discovered_interpreter_python": "/usr/bin/python"
          },
          "changed": false,
          "enabled": true,
          "name": "nginx",
          "state": "started",
          "status": {
              "ActiveEnterTimestamp": "Sat 2020-03-21 20:04:35 UTC",
              "ActiveEnterTimestampMonotonic": "1999615481",
              "ActiveExitTimestampMonotonic": "0",
              "ActiveState": "active",
              "After": "system.slice systemd-journald.socket network.target sysinit.target basic.target",
              "AllowIsolate": "no",
              "AmbientCapabilities": "",
              "AssertResult": "yes",
              "AssertTimestamp": "Sat 2020-03-21 20:04:35 UTC",
              "AssertTimestampMonotonic": "1999560256",
              "Before": "multi-user.target shutdown.target",
          }
      }
      
      

      Stop a Service

      When you change the state to stopped, the service will stop running.

      ansible Client -m service -a 'name=nginx state=stopped' -u non_root_user --become -K
      
        
      node1 | CHANGED => {
          "ansible_facts": {
              "discovered_interpreter_python": "/usr/bin/python"
          },
          "changed": true,
          "name": "nginx",
          "state": "stopped",
          "status": {
              "ActiveEnterTimestamp": "Sat 2020-03-21 20:04:35 UTC",
              "ActiveEnterTimestampMonotonic": "1999615481",
              "ActiveExitTimestampMonotonic": "0",
              "ActiveState": "active",
              "After": "system.slice systemd-journald.socket network.target sysinit.target basic.target",
              "AllowIsolate": "no",
              "AmbientCapabilities": "",
              "AssertResult": "yes",
              "AssertTimestamp": "Sat 2020-03-21 20:04:35 UTC",
      }
      }
      
      

      Gathering Facts

      The setup module can be used to gather information about your managed nodes:

      ansible Client -m setup
      
        
      node1 | SUCCESS => {
          "ansible_facts": {
              "ansible_all_ipv4_addresses": [
                  "192.0.2.4"
              ],
              "ansible_all_ipv6_addresses": [
                  "2400:8904::f03c:92ff:fee9:dcb3",
                  "fe80::f03c:92ff:fee9:dcb3"
              ],
              "ansible_apparmor": {
                  "status": "enabled"
              },
              "ansible_architecture": "x86_64",
              "ansible_bios_date": "04/01/2014",
              "ansible_bios_version": "rel-1.12.0-0-ga698c8995f-prebuilt.qemu.org",
              "ansible_cmdline": {
                  "BOOT_IMAGE": "/boot/vmlinuz-5.3.0-40-generic",
                  "console": "ttyS0,19200n8",
                  "net.ifnames": "0",
                  "ro": true,
                  "root": "/dev/sda"
              },
              "ansible_date_time": {
                  "date": "2020-03-21",
                  "day": "21",
                  "epoch": "1584821656",
                  "hour": "20",
                  "iso8601": "2020-03-21T20:14:16Z",
                  "iso8601_basic": "20200321T201416267047",
                  "iso8601_basic_short": "20200321T201416",
                  "iso8601_micro": "2020-03-21T20:14:16.267127Z",
                  "minute": "14",
                  "month": "03",
                  "second": "16",
                  "time": "20:14:16",
                  "tz": "UTC",
                  "tz_offset": "+0000",
                  "weekday": "Saturday",
                  "weekday_number": "6",
                  "weeknumber": "11",
                  "year": "2020"
              },
              "ansible_default_ipv4": {
                  "address": "192.0.2.4",
                  "alias": "eth0",
                  "broadcast": "192.0.2.255",
                  "gateway": "192.0.2.1",
                  "interface": "eth0",
                  "macaddress": "f2:3c:92:e9:dc:b3",
                  "mtu": 1500,
                  "netmask": "255.255.255.0",
                  "network": "192.0.2.0",
                  "type": "ether"
              },
              "gather_subset": [
                  "all"
              ],
              "module_setup": true
          },
          "changed": false
      }
      
      

      Filtering Facts

      Using the filter option with the setup module will limit what is returned by the module. This command lists the details of your managed nodes’ installed distributions:

      ansible Client -m setup -a "filter=ansible_distribution*"
      
        
      node1 | SUCCESS => {
          "ansible_facts": {
              "ansible_distribution": "Ubuntu",
              "ansible_distribution_file_parsed": true,
              "ansible_distribution_file_path": "/etc/os-release",
              "ansible_distribution_file_variety": "Debian",
              "ansible_distribution_major_version": "19",
              "ansible_distribution_release": "eoan",
              "ansible_distribution_version": "19.10",
              "discovered_interpreter_python": "/usr/bin/python"
          },
          "changed": false
      }
      
      

      This guide is published under a CC BY-ND 4.0 license.



      Source link