One place for hosting & domains

      Modify

      How To Modify the Color of HTML Elements



      Part of the Series:
      How To Build a Website With HTML

      This tutorial series will guide you through creating and further customizing this website using HTML, the standard markup language used to display documents in a web browser. No prior coding experience is necessary but we recommend you start at the beginning of the series if you wish to recreate the site.

      At the end of this series, you should have a website ready to deploy to the cloud and a basic familiarity with HTML. Having a knowledge of how to write HTML will provide a strong foundation for learning additional front-end web development skills, such as CSS and JavaScript.

      You can use HTML to modify the color of some elements and pieces of content of a webpage. For example, you can change the color of text, a border, or—as demonstrated in the tutorial on HTML Content Division—of a <div> element. The method for changing the color values of these pieces of content varies from element to element.

      In this tutorial, you will learn how to change the color of text, image borders, and <div> elements using HTML color names.

      The color of text elements, such as <p> or <h1>, is modified by using the style attribute and the color property like so:

      <p style="color:blue;">This is blue text.</p>
      

      Try writing this code in your index.html file and loading it in the browser. (If you have not been following the tutorial series, you can review instructions for setting up an index.html file in our tutorial Setting Up Your HTML Project. For instructions on loading the file in your browser, see our tutorial here.)

      You should receive something like this:

      This is blue text.

      The color of a border is modified by using the style attribute and the border property:

      <img src="https://www.xpresservers.com/wp-content/uploads/2020/07/How-To-Modify-the-Color-of-HTML-Elements.jpeg" style="border: 10px solid green"/>
      

      Try writing this code in your index.html file and loading it in the browser. (Note that we are using an image that we are hosting online in this example. We have also specified that the border should be 10 pixels wide and solid (as opposed to dashed)).

      You should receive something like this:

      The color of a <div> container is modified by using the style attribute and the background-color property like so:

      <div style="width:200px;height:200px;background-color:yellow;"></div>
      

      Try writing this code in your index.html file and loading it in the browser. You should receive something like this:

      In these examples, the color value is defined by color names. Try changing the color of text, image borders and

      elements using the following color names: black, white, gray, silver, purple, red, fuchsia, lime, olive, green, yellow, teal, navy, blue, maroon, and aqua.

      Note that colors can also be specified by hexadecimal values. A hexadecimal color consists of six alphanumeric digits preceded by a pound symbol, such as #0000FF (blue), #40E0D0 (turquoise), or #C0C0C0 (silver). For this tutorial series, however, we will continue using color names.

      You should now have a basic familiarity with how to change the color of text, image borders, and <div> elements using color names. We will return to colors later on the tutorial series when we begin building our website.



      Source link

      How To Modify Attributes, Classes, and Styles in the DOM


      Introdução

      No tutorial anterior nesta série, “Como fazer alterações no DOM,” falamos sobre como criar, inserir, substituir e remover elementos do Modelo de Objeto de Documentos (DOM) com métodos integrados. Ao ampliar sua capacidade de gerenciar o DOM, você se tornará mais capacitado para utilizar as funcionalidades interativas do JavaScript e modificar elementos Web.

      Neste tutorial, vamos aprender como fazer mais alterações no DOM, modificando estilos, classes e outros atributos de nós do elemento HTML. Isso dará a você uma maior compreensão sobre como manipular elementos essenciais no DOM.

      Revisão de seleção de elementos

      Até recentemente, a biblioteca de JavaScript chamada jQuery era a mais usada para selecionar e modificar elementos no DOM. O jQuery simplificou o processo de selecionar um ou mais elementos e de aplicar alterações a todos eles ao mesmo tempo. Em “Como acessar os elementos no DOM,” analisamos os métodos DOM para apreender e trabalhar com nós no vanilla JavaScript.

      Para revisão, o document.querySelector() e o document.getElementById() são os métodos usados para acessar um único elemento. Ao usar um div com um atributo id no exemplo abaixo, poderemos acessar aquele elemento de qualquer maneira.

      <div id="demo-id">Demo ID</div>
      

      O método do querySelector() é mais robusto no ponto de que ele pode selecionar um elemento na página por qualquer tipo de seletor.

      // Both methods will return a single element
      const demoId = document.querySelector('#demo-id');
      

      Ao acessar um único elemento, podemos atualizar facilmente uma parte do elemento como o texto dentro dele.

      // Change the text of one element
      demoId.textContent = 'Demo ID text updated.';
      

      No entanto, ao acessar vários elementos por um seletor comum, como uma classe específica, precisamos percorrer todos os elementos na lista. No código abaixo, temos dois elementos div com um valor de classe comum.

      <div class="demo-class">Demo Class 1</div>
      <div class="demo-class">Demo Class 2</div>
      

      Vamos usar o querySelectorAll() para captar todos os elementos com demo-class aplicado a eles e usaremos o forEach()para percorrê-los e aplicar uma alteração. Também é possível acessar um elemento específico com o querySelectorAll() da mesma forma que você utilizaria um array — usando a notação entre parênteses.

      // Get a NodeList of all .demo elements
      const demoClasses = document.querySelectorAll('.demo-class');
      
      // Change the text of multiple elements with a loop
      demoClasses.forEach(element => {
        element.textContent = 'All demo classes updated.';
      });
      
      // Access the first element in the NodeList
      demoClasses[0];
      

      Esta é uma das diferenças mais importantes que você deve saber ao passar do jQuery para o vanilla JavaScript. Muitos exemplos de modificação de elementos não irão explicar o processo de aplicação desses métodos e propriedades a vários elementos.

      As propriedades e métodos neste artigo serão, muitas vezes, anexadas aos event listeners para responder aos métodos de seleção via cliques, passar o mouse ou outros gatilhos.

      Nota: os métodos getElementsByClassName() e o getElementsByTagName() retornarão coleções do HTML que não têm acesso ao método forEach() que o querySelectorAll() tem. Nestes casos, será necessário usar um padrão para for loop iterar na coleção.

      Modificando atributos

      Os atributos são valores que contêm informações adicionais sobre elementos do HTML. Normalmente, eles vêm em pares de nome/valor e podem ser essenciais dependendo do elemento.

      Alguns dos atributos do HTML mais comuns são os atributos src de uma tag img, o href de uma tag a, class, id e style. Para obter uma lista completa de atributos do HTML, veja a lista de atributos na Rede de Desenvolvedores da Mozilla. Os elementos personalizados que não fazem parte do padrão do HTML serão anexados no início com o data-.

      No JavaScript, temos quatro métodos para modificar atributos do elemento:

      Método Descrição Exemplo
      hasAttribute() Devolve valores lógicos boolianos do tipo true ou false element.hasAttribute('href');
      getAttribute() Retorna o valor de um atributo especificado ou null element.getAttribute('href');
      setAttribute() Adiciona ou atualiza o valor de um atributo especificado element.setAttribute('href', 'index.html');
      removeAttribute() Remove um atributo de um elemento element.removeAttribute('href');

      Vamos criar um novo arquivo de HTML com uma tag img com um atributo. Vamos vincular uma imagem pública disponível através de um URL, mas você pode trocá-la por uma imagem local alternativa se estiver trabalhando offline.

      attributes.html

      <!DOCTYPE html>
      <html lang="en">
      <body>
      
          <img src="https://js-tutorials.nyc3.digitaloceanspaces.com/shark.png">
      
      </body>
      
      </html>
      

      Quando carregar o arquivo de HTML acima em um navegador Web moderno e abrir o Console do desenvolvedor integrado, deverá ver algo assim:

      First rendering of classes.html

      Agora, podemos testar todos os métodos de atributo rapidamente.

      // Assign image element
      const img = document.querySelector('img');
      
      img.hasAttribute('src');                // returns true
      img.getAttribute('src');                // returns "...shark.png"
      img.removeAttribute('src');             // remove the src attribute and value
      

      Neste ponto, você terá removido o atributo src e o valor associado ao img, mas poderá redefinir aquele atributo e atribuir o valor para uma imagem alternativa com o img.setAttribute():

      img.setAttribute('src', 'https://js-tutorials.nyc3.digitaloceanspaces.com/octopus.png');
      

      Second rendering of classes.html

      Finalmente, podemos modificar o atributo diretamente atribuindo um novo valor ao atributo como uma propriedade do elemento, definindo o src de volta para o arquivo shark.png

      img.src = 'https://js-tutorials.nyc3.digitaloceanspaces.com/shark.png';
      

      Qualquer atributo pode ser editado desta maneira, bem como com os métodos acima.

      Os métodos hasAttribute() e getAttribute() são normalmente usados com declarações condicionais, e os métodos setAttribute() e removeAttribute() são usados para modificar diretamente o DOM.

      Modificando as classes

      O atributo classe corresponde aos seletores de classe CSS. Não pode ser confundido com as classes ES6, um tipo especial de função do JavaScript.

      As classes CSS são usadas para aplicar estilos a vários elementos, ao contrário das IDs que só podem existir uma vez por página. No JavaScript, temos as propriedades de className e de classListpara trabalhar com o atributo de classe.

      Método/Propriedade Descrição Exemplo
      className Obtém ou define o valor de classe element.className;
      classList.add() Adiciona um ou mais valores de classe element.classList.add('active');
      classList.toggle() Liga ou desliga uma classe element.classList.toggle('active');
      classList.contains() Verifica se o valor de classe existe element.classList.contains('active');
      classList.replace() Substitui um valor de classe existente com um novo valor de classe element.classList.replace('old', 'new');
      classList.remove() Remove um valor de classe element.classList.remove('active');

      Vamos fazer outro arquivo de HTML para trabalhar com os métodos de classe, com dois elementos e algumas classes.

      classes.html

      <!DOCTYPE html>
      <html lang="en">
      
      <style>
          body {
              max-width: 600px;
              margin: 0 auto;
              font-family: sans-serif;
          }
          .active {
              border: 2px solid blue;
          }
      
          .warning {
              border: 2px solid red;
          }
      
          .hidden {
              display: none;
          }
      
          div {
              border: 2px dashed lightgray;
              padding: 15px;
              margin: 5px;
          }
      </style>
      
      <body>
      
          <div>Div 1</div>
          <div class="active">Div 2</div>
      
      </body>
      
      </html>
      

      Quando abrir o arquivo classes.html em um navegador Web, receberá uma renderização parecida com a seguinte:

      First rendering of classes.html

      A propriedade className foi introduzida para evitar conflitos com a palavra-chave class encontrada no JavaScript e outras linguagens que têm acesso ao DOM. É possível usar o className para atribuir um valor diretamente à classe.

      // Select the first div
      const div = document.querySelector('div');
      
      // Assign the warning class to the first div
      div.className = 'warning';
      

      Atribuímos a classe warning definida nos valores CSS de classes.html para o primeiro div. Você receberá o seguinte resultado:

      Second rendering of classes.html

      Note que se alguma classe já existir no elemento, isso irá substituí-las. É possível adicionar várias classes com espaço delimitado usando a propriedade className, ou usá-las sem operadores de atribuição para obter o valor da classe no elemento.

      A outra maneira de modificar as classes é através da propriedade ](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)classList[, que vem com alguns métodos úteis. Estes métodos são semelhantes aos métodos do jQuery addClass, removeClass e toggleClass.

      // Select the second div by class name
      const activeDiv = document.querySelector('.active');
      
      activeDiv.classList.add('hidden');                // Add the hidden class
      activeDiv.classList.remove('hidden');             // Remove the hidden class
      activeDiv.classList.toggle('hidden');             // Switch between hidden true and false
      activeDiv.classList.replace('active', 'warning'); // Replace active class with warning class
      

      Após realizar os métodos acima, sua página Web se parecerá com esta:

      Final rendering of classes.html

      Ao contrário do exemplo className, usar classList.add() adicionará uma nova classe na lista de classes existentes. Também é possível adicionar várias classes como strings separadas por vírgula. Também é possível usar o setAttribute para modificar a classe de um elemento.

      Modificando os estilos

      A propriedade estilo representa os estilos embutidos em um elemento HTML. Muitas vezes, os estilos serão aplicados aos elementos através de uma folha de estilos, como fizemos anteriormente neste artigo. Porém, às vezes precisamos adicionar ou editar diretamente um estilo embutido.

      Vamos fazer um exemplo curto para demonstrar a edição de estilos com o JavaScript. Abaixo está um novo arquivo de HTML com um div que tem alguns estilos embutidos aplicados para mostrar um quadrado.

      styles.html

      <!DOCTYPE html>
      <html lang="en">
      
      <body>
      
          <div style="height: 100px;
                      width: 100px;
                      border: 2px solid black;">Div</div>
      
      </body>
      
      </html>
      

      Quando aberto em um navegador Web, o styles.html se parecerá com isso:

      First rendering of styles.html​

      Uma opção para editar os estilos é com o setAttribute().

      // Select div
      const div = document.querySelector('div');
      
      // Apply style to div
      div.setAttribute('style', 'text-align: center');
      

      No entanto, isso removerá todos os estilos embutidos do elemento. Uma vez que este provavelmente não é o efeito desejado, é melhor usar o atributo style diretamente.

      div.style.height = '100px';
      div.style.width = '100px';
      div.style.border = '2px solid black';
      

      As propriedades CSS são escritas em kebab-case, que são palavras minúsculas separadas por traços. É importante notar que as propriedades CSS em kebab-case não podem ser usadas na propriedade de estilo do JavaScript. Em vez disso, elas serão substituídas por seu equivalente em camelCase, que é quando a primeira palavra é minúscula e todas as palavras subsequentes são maiúsculas. Em outras palavras, em vez de text-align, vamos usar textAlign para a propriedade de estilo do JavaScript.

      // Make div into a circle and vertically center the text
      div.style.borderRadius = '50%';
      div.style.display = 'flex';
      div.style.justifyContent = 'center';
      div.style.alignItems = 'center';
      

      Após completar as modificações de estilo acima, sua versão final de styles.html mostrará um círculo:

      Final rendering of styles.html

      Se muitas alterações estilísticas tiverem que ser aplicadas a um elemento, o melhor a se fazer é aplicar os estilos para uma classe e adicionar uma nova classe. No entanto, existem alguns casos nos quais será necessário ou mais direto modificar o atributo estilo embutido.

      Conclusão

      Os elementos do HTML têm, frequentemente, informações adicionais atribuídas a eles na forma de atributos. Os atributos podem consistir em pares de nome/valor e alguns dos atributos mais comuns são de class e style.

      Neste tutorial, aprendemos como acessar, modificar e remover atributos em um elemento HTML no DOM usando o JavaScript simples. Também aprendemos como adicionar, remover, alternar e substituir as classes CSS em um elemento e como editar estilos de CSS embutidos. Para saber mais, verifique a documentação sobre atributos na Rede de Desenvolvedores da Mozilla.



      Source link

      Use and Modify Official SaltStack Formulas


      Updated by Linode Contributed by Linode

      Salt State Files

      The SaltStack Platform is made up of two primary components: A remote execution engine which handles bi-directional communication for any node within your infrastructure (master and minions), and a configuration management system which maintains all infrastructure nodes in a defined state. Salt’s configuration management system is known as the Salt State system. A Salt state is declared within a Salt State file (SLS) using YAML syntax and represents the information Salt needs to configure minions. A Salt Formula is a collection of related SLS files that will achieve a common configuration.

      SaltStack’s GitHub page contains Salt formulas for commonly needed configurations, like creating and managing SSL/TLS certificates, installing and configuring the Apache HTTP Server, installing and configuring a WordPress site and many other useful formulas. You can easily add any of these pre-written formulas to your own Salt state tree using GitHub.

      This guide will use GitHub to fork and modify SaltStack’s timezone formula and then use the formula on a Salt master to configure the time zone on two minions.

      Before You Begin

      1. If you are new to SaltStack, read A Beginner’s Guide to Salt to familiarize yourself with basic Salt concepts.

      2. Download Git on your local computer by following our How to Install Git on Linux, Mac or Windows guide.

      3. Familiarize yourself with Git using our Getting Started with Git guide.

      4. Make sure you have configured git on your local computer.

      5. Use the Getting Started with Salt – Basic Installation and Setup guide to set up a Salt Master and two Salt minions: one running Ubuntu 18.04 and the second running CentOS 7.

      6. Complete the sections of our Securing Your Server to create a standard user account, harden SSH access and remove unnecessary network services.

      Note

      The steps in this guide require root privileges. Be sure to run the steps below with the sudo prefix. For more information on privileges, see our Users and Groups guide.

      Overview of the SaltStack Time Zone Formula

      In this section, we will take a closer look at SaltStack’s timezone-formula, which can be used to configure a minion’s time zone. A high-level overview of all the formula’s state files and Jinja templates will be provided. Salt best practices recommends that formulas should separate the data that a state needs from the state itself to increase the flexibility and reusability of state files. We will observe how this is achieved in the time zone formula.

      1. In your browser, navigate to the timezone-formula on SaltStack’s GitHub page. The README file is displayed and contains basic information about the formula. It notes the following details:

        • The purpose of the formula: to configure the time zone.
        • The available states: timezone
        • The provided default values: timezone: 'Europe/Berlin' utc: True

        The repository’s FORMULA file includes additional details, including the supported OS families (Debian, RedHat, SUSE, Arch, FreeBSD), a summary, description and release number.

      2. Viewing the timezone-formula, click on the timezone directory to view its contents. You should see the following files:

        View the time zone formula files

      3. Take a look at the contents of the init.sls file that defines the timezone state:

        timezone/init.sls
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        
        # This state configures the timezone.
        
        {%- set timezone = salt['pillar.get']('timezone:name', 'Europe/Berlin') %}
        {%- set utc = salt['pillar.get']('timezone:utc', True) %}
        {% from "timezone/map.jinja" import confmap with context %}
        
        timezone_setting:
          timezone.system:
            - name: {{ timezone }}
            - utc: {{ utc }}
        
        timezone_packages:
          pkg.installed:
            - name: {{ confmap.pkgname }}
        
        timezone_symlink:
          file.symlink:
            - name: {{ confmap.path_localtime }}
            - target: {{ confmap.path_zoneinfo }}{{ timezone }}
            - force: true
            - require:
              - pkg: {{ confmap.pkgname }}
            

        Salt will interpret the name of this file as timezone, since any init.sls file in a subdirectory is referred to by the path of the directory.

        This state file contains three state declarations, timezone_setting, timezone_packages and timezone_symlink. Below is a description of the configuration each declaration will accomplish on a Salt minion.

        • timezone.system: This state uses Salt’s timezone state module to manage the timezone for the minion. The values for name and utc are derived from the corresponding Salt master’s Pillar file. This is accomplished in the two variable assignment at the top of the file: {%- set timezone = salt['pillar.get']('timezone:name', 'Europe/Berlin') %} and {%- set utc = salt['pillar.get']('timezone:utc', True) %}.

        • timezone_packages: This state ensures that the package needed to configure time zones is installed on the minion. This value is derived from the confmap variable that is imported from the map.jinja file. The import is declared at the top of the file with the {% from "timezone/map.jinja" import confmap with context %} import statement. Later in this section, you will inspect the map.jinja file.

        • timezone_symlink: This state creates a symbolic link from the path defined in name to the location defined in target. This state will only execute if the timezone_packages state is executed successfully. This requirement is denoted by the require statement.

      4. Next, inspect the map.jinja file:

        timezone/map.jinja
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        
        {% import_yaml "timezone/defaults.yaml" as defaults %}
        {% import_yaml "timezone/osfamilymap.yaml" as osfamilymap %}
        
        {% set osfam = salt['grains.filter_by'](
                                                osfamilymap,
                                                grain='os_family'
                                                ) or {} %}
        
        {% do salt['defaults.merge'](defaults, osfam) %}
        
        {%- set confmap = salt['pillar.get'](
                                        'timezone:lookup',
                                        default=defaults,
                                        merge=True,
                                        ) %}
              

        The map.jinja file allows the formula to abstract static defaults into a dictionary that contains platform specific data. The two main dictionaries are defined in the repository’s timezone/defaults.yaml and timezone/osfamilymap.yaml files. The defaults.yml file serves as a base dictionary containing values shared by all OSes, while the osfamilymap.yml file stores any values that are different from the base values. Any file throughout the formula could make use of these dictionary values by importing the map.jinja file. In addition, any dictionary values can be overridden in a Pillar file. Overidding dictionary values will be discussed in the Modify Your SaltStack Formula section.

      5. Open the timezone/defaults.yaml file and the timezone/osfamilymap,yaml file to view the data stored in those files:

        timezone/defaults.yaml
        1
        2
        3
        4
        
            path_localtime: /etc/localtime
            path_zoneinfo: /usr/share/zoneinfo/
            pkgname: tzdata
              
        timezone/osfamilymap.yaml
        1
        2
        3
        4
        5
        6
        7
        
            Suse:
              pkgname: timezone
            FreeBSD:
              pkgname: zoneinfo
            Gentoo:
              pkgname: sys-libs/timezone-data
              

        The values defined in these YAML files are used in the init.sls file.

      6. Open the pillar.example file to review its contents:

        pillar.example
        1
        2
        3
        4
        
          timezone:
            name: 'Europe/Berlin'
            utc: True
              

        This file provides an example for you to use when creating your own Pillar file on the Salt master. The init.sls file uses the values for name and utc in its timezone_setting state declaration. The value for name will set the time zone for your minion. The boolean value for utc determines whether or not to set the minion’s hardware clock to UTC.

        Refer to tz database time zones to view a list of all available time zones. Since Pillar files contain sensitive data, you should not version control this file. In the Create the Pillar section, you will create a Pillar file directly on your Salt master.

        Now that you understand the structure of the SaltStack time zone formula, in the next section you will fork the formula’s repository on GitHub and clone the forked formula to your local computer.

      Fork and Clone the SaltStack TimeZone Formula

      In this section you will fork the timezone-formula from the official SaltStack GitHub page to your GitHub account and clone it to a local repository.

      1. In your browser, navigate to the timezone-formula on SaltStack’s GitHub page. If you have not yet logged into your GitHub account, click on the Sign in link at the top of the page and log in.

      2. Fork the timezone-formula from the SaltStack formula’s GitHub page:

        Fork SaltStack timezone formula

        Once the formula has been forked, you will be redirected to your GitHub account’s own fork of the timezone formula.

      3. Viewing your fork of the timezone formula, click on the Clone or download button and copy the URL:

        Fork SaltStack timezone formula

      4. On your local computer, clone the timezone formula:

        git clone https://github.com/my-github/timezone-formula.git
        
      5. Move into the timezone-formula directory:

        cd timezone-formula
        
      6. Display the contents of the timezone-formula directory:

        ls
        

        You should see the following output:

          
              FORMULA        README.rst     pillar.example timezone
              
        
      7. When you clone a repository, Git will automatically set the origin remote to the location of the forked repository. Verify the configured remotes for your timezone-formula repository:

        git remote -v
        

        Your output should be similar to what is displayed below, however, it will point to your own fork of the timezone-formula repository:

          
          origin	https://github.com/my-github/timezone-formula.git (fetch)
          origin	https://github.com/my-github/timezone-formula.git (push)
              
        

        You can add the official SaltStack timezone formula as the upstream remote, so you can easily pull any changes made to the formula by the repository’s maintainers or contribute back to the project. This step is not required.

        git remote add upstream https://github.com/saltstack-formulas/timezone-formula
        

        You now have a local copy of your forked timezone-formula. In the next section, you will modify the formula to update the init.sls file.

      Modify Your SaltStack Formula

      In this section, you will modify the time zone formula to improve how the formula follows Salt best practices related to lookup dictionaries. You can similarly modify any SaltStack formula for your infrastructure’s specific requirements, if needed.

      As discussed in the Overview of the SaltStack Time Zone Formula section, the timezone/defaults.yaml file and the timezone/osfamily.map file provide dictionaries of values that are used by the init.sls state. These YAML file dictionary values can be overridden in a Pillar file that also stores any sensitive data needed by the init.sls state.

      When structuring Pillar data, Salt’s official documentation states that it is a best practice to make formulas expect all formula-related parameters to be placed under a second-level lookup key. Currently, the init.sls file’s timezone and utc variables expect the Pillar data to be structured differently. You will update these two variable statements to expect a second-level lookup key.

      1. Create a new branch in your local repository to begin modifying the timezone-formula:

        git checkout -b update-variable-statements
        
      2. Open the init.sls file in a text editor and modify its timezone and utc variable statements to match the example file:

        timezone/init.sls
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        
        # This state configures the timezone.
        
        {%- set timezone = salt['pillar.get']('timezone:lookup:name', 'Europe/Berlin') %}
        {%- set utc = salt['pillar.get']('timezone:lookup:utc', True) %}
        {% from "timezone/map.jinja" import confmap with context %}
        
        timezone_setting:
          timezone.system:
            - name: {{ timezone }}
            - utc: {{ utc }}
        
        timezone_packages:
          pkg.installed:
            - name: {{ confmap.pkgname }}
        
        timezone_symlink:
          file.symlink:
            - name: {{ confmap.path_localtime }}
            - target: {{ confmap.path_zoneinfo }}{{ timezone }}
            - force: true
            - require:
              - pkg: {{ confmap.pkgname }}
              

        The init.sls file now expects a second-level lookup key when retrieving the specified Pillar values. Following this convention will make it easier to override dictionary values in your Pillar file. You will create a Pillar file in the Installing a Salt Formula section of this guide.

      3. Use Git to view which files have been changed before staging them:

        git status
        

        Your output should resemble the following:

          
        On branch update-variable-statements
        Changes not staged for commit:
          &nbsp&nbsp(use "git add &ltfile&gt..." to update what will be committed)
          &nbsp&nbsp(use "git checkout -- &ltfile&gt..." to discard changes in working directory)
        
          &nbsp&nbspmodified:   timezone/init.sls
        
        no changes added to commit (use "git add" and/or "git commit -a")
            
        
      4. Stage and commit the changes you made to the init.sls file.

        git add -A
        git commit -m 'My commit message'
        
      5. Push your changes to your fork:

        git push origin update-variable-statements
        
      6. Navigate to your timezone formula’s remote GitHub repository and create a pull request against your fork’s master branch.

        Submit a pull request

        Make sure you select your own fork of the time zone formula as the base fork, otherwise you will submit a pull request against the official SaltStack timezone formula’s repository, which is not the intended behavior for this example.

        Create a pull request

        If you are satisfied with the changes in the pull request, merge the pull request into your master branch.

        Merge a pull request

      In the next section, you will add your forked timezone-formula to your Salt master, create a Pillar file for the timezone-formula and apply the changes to your minions.

      Install a Salt Formula

      There are two ways to use a Salt Formula: you can add the formula as a GitFS Remote, which will allow you to directly serve the files hosted on your GitHub account, or you can add the formula directly to the Salt master using Git’s clone mechanism. This section will cover both ways to use Salt formulas.

      Manually Add a Salt Formula to your Master

      1. Navigate to your fork of the timezone-formula, click on the Clone or download button and copy the repository’s URL to your clipboard.

      2. SSH into your Salt master. Replace the username with your limited user account and replace 198.51.100.0 with your Linode’s IP address:

        ssh username@198.51.100.0
        
      3. Create a formulas directory and go to the new directory:

        mkdir -p /srv/formulas
        cd /srv/formulas
        
      4. If your Salt master does not already have Git installed, install Git using your system’s package manager:

        Ubuntu/Debian

        apt-get update
        apt-get install git
        

        Centos

        yum update
        yum install git
        
      5. Clone the repository into the /srv/formulas directory. Make sure you replace git-username with your own username:

        git clone https://github.com/git-username/timezone-formula.git
        

      Add a Salt Formula as a GitFS Remote

      GitFs allows Salt to serve files directly from remote git repositories. This is a convenient way to use Salt formulas with the added flexibility and power that remote version control systems provide, like collaboration and easy rollback to previous versions of your formulas.

      1. On the Salt master, install the Python interface to Git:

        sudo apt-get install python-git
        
      2. Edit the Salt master configuration file to use GitFs as a fileserver backend. Make sure the lines listed below are uncommented in your master configuration file:

        /etc/salt/master
        1
        2
        3
        
        fileserver_backend:
          - gitfs
          - roots

        When using multiple backends, you should list all backends in the order you want them to be searched. roots is the fileserver backend used to serve files from any of the master’s directories listed in the file_roots configuration.

      3. In the same Salt master configuration file, add the location of your timezone formula’s GitHub repository. Ensure you have uncommented gitfs_remote:

        /etc/salt/master
        1
        2
        
        gitfs_remotes:
          - https://github.com/git-username/timezone-formula.git
      4. Uncomment the gitfs_provider declaration and set its value to gitpython:

        /etc/salt/master
        1
        
        gitfs_provider: gitpython
      5. Restart the Salt master to apply the new configurations:

        sudo systemctl restart salt-master
        

      Add a Salt Formula to the Top File

      To include your timezone formula in your Salt state tree, you must add it to your top file.

      1. Create the /srv/salt directory if it does not already exist:

        mkdir /srv/salt
        
      2. Add the timezone state declared in the timezone-formula to your top file:

        /srv/salt/top.sls
        1
        2
        3
        4
        
        base:
          '*':
            - timezone
            

        The example Top file declares one environment, the base environment that targets all minions and applies the timezone state to them. This top file could easily contain several states that already exist in your state tree, like an apache state, a wordpress state, etc., and several environments that target different minions. Any Salt formula can be easily dropped-in to the top file and will be applied to the targeted minions the next time you run a highstate.

      Create the Pillar

      1. Create a directory to store your formula’s Pillar file:

        mkdir -p /srv/pillar
        
      2. Create a Pillar file to store the data that will be used by your timezone formula:

        /srv/pillar/timezone.sls
        1
        2
        3
        4
        5
        6
        7
        8
        9
        
        timezone:
          lookup:
            {%- if grains['os_family'] == 'Debian' %}
            name: America/New_York
            {%- else %}
            name: 'Europe/Berlin'
            {%- endif %}
            utc: True
            

        The timezone.sls Pillar file was created from the pillar.example file provided in the SaltStack timezone formula. The example was modified to add Jinja control statements that will assign a different timezone on any minion that is a Debian family OS. You can replace any of the timezone name values to your preferred timezone or add additional Jinja logic, if necessary. For an introduction to Jinja, read the Introduction to Jinja Templates for Salt.

        You can also override any of the dictionary values defined in the timezone/defaults.yaml or timezone/osfamilymap.yaml in the Pillar file using Salt’s lookup dictionary convention. For example, if you wanted to override the pkgname value defined in timezone/defaults.yaml your Pillar file might look like the following example:

        /srv/pillar/timezone.sls
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        
        timezone:
          lookup:
            {%- if grains['os_family'] == 'Debian' %}
            name: America/New_York
            {%- else %}
            name: 'Europe/Berlin'
            {%- endif %}
            utc: True
            pkgname: timezone
            
      3. If you cloned the timezone-formula to your master instead of adding the formula as a GitFS remote, add the timezone-formula’s directory to the Salt master’s file_roots configuration:

        /etc/salt/master
        1
        2
        3
        4
        5
        
        file_roots:
          base:
            - /srv/salt/
            - /srv/formulas/timezone-formula
            
      4. Add the Pillar to the Pillar’s top file:

        /srv/pillar/top.sls
        1
        2
        3
        4
        
        base:
          '*':
            - timezone
            
      5. Configure the location of the Pillar file:

        /etc/salt/master
        1
        2
        3
        4
        
        pillar_roots:
          base:
            - /srv/pillar
            
      6. Restart the Salt master for the new configurations to take effect on the Salt master:

        sudo systemctl restart salt-master
        
      7. Run a highstate to your minion to apply the state defined in the timezone formula:

        sudo salt '*' state.apply
        

      Next Steps

      To learn how to create your own Salt formulas and how to organize your formula’s states in a logical and modular way, read our Automate Static Site Deployments with Salt, Git, and Webhooks guide.

      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.

      Find answers, ask questions, and help others.

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



      Source link