Thursday, 17 November 2016

SED cheat sheet


This article is exactly what the title says. It's a cheat sheet. IF you are looking for information how to learn to use sed with detailed explanation of the usage examples then this article is not the best avenue. However, if you are looking for a lot of usage examples with brief descriptions then this is the right place.



SED ExpressionDescription
sed 's/sahil/{&&&}/' somedata.txt [put the matched string in parenthesis & replicate it as many times as & is specified]
sed '2,3 s/sahiltech/Admin/' somedata.txt [replace string on 2nd & 3rd line. If there is a $ after , then replace till last line]
sed '/linux/ s/unix/Admin/' somedata.txt [do replace on lines matching a pattern]
sed -n '5,10p' somedata.txt [print lines 5 to 10 only]
sed '20,35d' somedata.txt [print the file omitting lines 20 to 35]
sed -n -e '5,7p' -e '10,13p' somedata.txt [print non consecutive line ranges]
sed 's/version/story/gi' somedata.txt [case insensitive search & replace]
ip route show | sed 's/  */ /g' [replace multiple blank spaces using a single space]
sed '30,40 s/version/story/g' somedata.txt [search & replace within a given range of lines]
sed 's/[Zz]ip/rar/g' somedata.txt [using regex in search & replace]
sed -n '/^Jul 1/ p' /var/log/secure [view lines containing a given pattern]
sed -e '/^#/d' -e '/^$/d' somedata.txt [remove comments & blank lines]
sed 'G;G' somedata.txt [inset 2 blank lines between each lines]
sed '0~2 a\\' somedata.txt | tr -d '\\' [insert a blank line after every 2 lines]
sed -i'.orig' 's/this/that/gi' somedata.txt [take backup of orignal file as filename.orig & perform replace on original file]
sed -i 's/old/new/g' somedata.txt [modify original file]
sed -ibak 's/old/new/g' somedata.txt [backup & modify original file]
sed -n 's/old/new/gpw output' somedata.txt [write changes to new file called output]
sed 's/\-.*//g' somedata.txt [empty everything after the - charector]
sed 's/...$//' somedata.txt [delete last 3 charectors from each line]
sed -e 's/#.*//' somedata.txt [eliminate comments from a file]
sed -e 's/#.*//;/^$/d' somedata.txt [eliminate comments & empty lines from a lines, -e to execute multiple sed commands separated by ;]
sed -e '1w out' -e ' 2w out' -e ' $w out' somedata.txt [wwrite 1st, 2nd & last line to new file called out]
sed '1,5w out' somedata.txt [write lines 1 to 5 to a file out]
sed -n -e '/Storage/w output.txt' somedata.txt [write lines with pattern Storage to a new file]
sed -n '/Storage/,+2w output.txt' somedata.txt [write lines matching pattern plus next two lines to a new file]
sed '1,3 s/^/hello: \t/g' somedata.txt [add hello to the start of 1st 3 lines]
sed -e '4d' -e '2d' somedata.txt [delete 4th & 2nd line from file]
sed -n -e '/Software/p' -e '/Storage/p' somedata.txt [search & print matching pattern only]
sed -e '1d' -e '$d' -e '/^$/d' somedata.txt [delete 1st, last & all blank lines]
sed 's/\([^:]*\).*/\1/' /etc/passwd [extract usernames from password file]
sed '3 a Cool gadgets and websites' somedata.txt[append a line after the 3rd line of file]
sed '/vsun001*/a still testing sed' somedata.txt [insert line after every line with matching patter]
sed '2 i this is sed insert test' somedata.txt [insert a line before 2nd line of file]
sed '/vsun001*/i insert testing' somedata.txt [insert a line before every line matching the pattern]
sed '/this is/c is this a test' somedata.txt [replace lines mathing pattern 'this is' with line 'is this a test']
sed '2c not found' somedata.txt [replace 2nd line in file somedata.txt with the line not found]
sed '=' somedata.txt [print line number above line being printed]
sed -n '/vsun0012/=' somedata.txt [print line number containing the pattern vsun0012]
sed 's/0\{3\}//g' somedata.txt [remove 3 zeros from numbers in the file. For example, 7.000 will become 7.]
sed '0~3 s/$/\nMy Text/g' somedata.txt [insert the line My Text after every 3 lines. In 0~3, 0 is the first addition & 3 denotes after how many lines the subsequent text is to be inserted]
sed 's/.\{2\}/&#/g' somedata.txt [insert a # character after every 2 characters in the file]
sed 'N;s/\n/ /g'[join 2 line. replace newline with a space]
sed 'N;N;s/\n/ /g'[join 3 consecutive lines]
sed -e '{N;s/\n/@/}' somedata.txt[join 2 consecutive lines & place a @ symbol b/w the lines]
sed 's/sahil/Linux Admin/2g' somedata.txt [replace from 2nd occurnace till end of line in the file]

Monday, 14 November 2016

Re-executing shell commands from history


The ability to re-execute a previously typed command can be very useful if the concerned command was a  long one like a complex find search. Bash's ability to store command history is indispensable to any system administrator. In this article, I'll briefly showcase tapping into the shell history to avoid re-typing commands.

Before getting to the commands I would like to mention that the history of shell commands you typed during a session is written to your .bash_history file only after you've gracefully terminated your session. Before that the command history is stored in memory. So, in case you are working on the command line & someone restarts the system or there is a panic event, your session command history will probably not be written to .bash_history file & you won't be able to retrieve it for future reference.

With that gotcha said & done let's get started with the 'how to's'.

To re-execute a command you just executed, press the up arrow key, you'll see the command again & press enter. You can also type !! on the command line to re-execute the last command you type. For example:

[root@cserver ~]# uname -a
Linux cserver 3.10.0-123.el7.x86_64 #1 SMP Mon Jun 30 12:09:22 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
[root@cserver ~]#
[root@cserver ~]# !!
uname -a
Linux cserver 3.10.0-123.el7.x86_64 #1 SMP Mon Jun 30 12:09:22 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
[root@cserver ~]#
[root@cserver ~]#


Another interesting feature available in bash while executing the last executed command is that we can change the characters/words that were part of the previous command.
For example, we ran a find command on a directory location & we want to run the find command again but on a different directory. Instead of typing the complete command again we can use bash's built in features to just substitute the new directory location & execute find again.

In order to replace a single character like a 1 with a 2, we use the following expression on the command line:

!:gs/1/2/ [!:gs/old/new/]

If we want to replace an entire word, we use the following expression:

^old^new

Here are a couple of examples to demonstrate this:

[sahil@localhost ~]#touch test1 user1
[sahil@localhost ~]#!:gs/1/2/
touch test2 user2
[sahil@localhost ~]#^test^t
touch t2 user2


Another quick trick comes to mind in case we need to re-execute a command with arguments. In case we want to repeat the last command but with a different set of arguments we can use !:0 !:<arg_num> where arg_num is argument number on the command line. Her's an example:

[sahil@local ~]#echo a b c d
a b c d
[sahil@local ~]#!:0 !:3
echo c
c
[sahil@local ~]#!:0 e
echo e

e


To move through the history further use the up arrow key to move up & the down arrow key to move down in the history of previously executed shell commands.
We can type history followed by a number to display the number of commands in descending order beginning with the last command going up. For example, typing history 10 will display the last 10 commands that were executed.
When we run the history command it shows us list of available commands in history preceded by a number. If we wish to execute a command at a particular number, we just need to type the ! (bang symbol) followed by the number to re-run the command.

In the below example, I've re-executed the uname -a command by typing the command number preceded by the ! symbol.

[root@cserver ~]# history 10
  204  ./congif -l 0  -o fast.gif foo.t foo.d
  205  ls
  206  rm foo.d foo.t
  207  mv fast.gif ~
  208  ls
  209  history
  210  uname -a
  211  cd
  212  uname -a
  213  history 10
[root@cserver ~]#
[root@cserver ~]# !212
uname -a
Linux cserver 3.10.0-123.el7.x86_64 #1 SMP Mon Jun 30 12:09:22 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
[root@cserver ~]#


Now, we seen how we can re-execute the last command with !! & the nth command in shell history via !n. But what if I want to execute commands number 150 through 200 again.
We do not need to type !n fifty times! For such cases we use the fc command.

Here's how it works. We just type fc followed by the first & last numbers of the history commands that we'd like the shell to re-run. This will open up a tmp file with our selected commands typed in. We can make changes to any of the commands as we see fit & then do :wq! as we do to save changes to a file edited with vi editor. As soon as the file closes, the selected commands will be re-executed on the terminal.

Demo:

In this demonstration, I've selected commands 52 to 57 by typing fc 52 57, saved the contents of the tmp file generated by typing :wq! & the commands get executed as soon as the file closes.



Script to convert script command output to animated GIF

While looking around for some nice terminal recording tools for the Linux terminal I came across a neat script on github which could take in the timing information & command output files from the popular script command & convert it to a neat GIF file.

The script has two dependencies:

  1. It runs only from within a terminal opened under x-windows direct console GUI.
  2. It requires ImageMagick-c++ & ImageMagick to be installed.


Here is the script:


#!/bin/bash

# origin from http://blog.fedora-fr.org/metal3d/post/typescript-to-gif
# modified by tgic to specified output file


# http://www.imagemagick.org/script/command-line-options.php#limit
CONVERTARG="-limit memory 32MiB -limit map 64MiB"

TIMING=$1
SCRIPT=$2
OUTPUT=$3
W=$WINDOWID

if [ ! -f "$TIMING" ] || [ ! -f "$SCRIPT" ] || [ "$OUTPUT" == "" ]
then
    echo "usage: $0 TIMING SCRIPT OUTPUT"
    exit
fi

if [ "$W" == "" ]
then
    echo 'No window found use xvtypescripttogif instead'
    exit
fi

WORKDIR=$(mktemp -d)

t=$(mktemp)
cp $SCRIPT $t

#remove first line
sed -i '1d' $t

#clear screen
clear

#read timing file one by one
curr=0
i=0
while read line
do
    #capture time and chars to read
    cols=($line)
    chars=${cols[1]}

    #read from current char the number of chars to read
    dd if=$t bs=1 skip=$curr count=$chars 2>/dev/null

    #convert to gif frame with a nice frame-number
    n=$(printf "%010d" $i)
    import -window $WINDOWID $WORKDIR/$n.gif

    #and move to next position
    curr=$((curr+chars))
    i=$((i+1))
done <$TIMING
rm -f $t

#now, set gif with delay per frame
i=1
while read line
do
    cols=($line)
    timing=${cols[0]}
    #get next image
    file=$(ls -1 $WORKDIR | head -n $i | tail -n 1)
    timing=$(echo "$timing*100" | bc -l | awk '{print int($0)}')
    command=$command" -delay $timing $WORKDIR/$file"

    i=$((i+1))
done < $TIMING


convert $CONVERTARG $command $WORKDIR/anim-notoptim.gif
convert $CONVERTARG $WORKDIR/anim-notoptim.gif -coalesce -layers Optimize $OUTPUT

rm -rf $WORKDIR


To use it, first run the script command as follows:

[root@cserver ~]# script -t 2> time.txt cmd.txt
Script started, file is cmd.txt
[root@cserver ~]# echo "lets see how this goes"
lets see how this goes
[root@cserver ~]# echo "testing the typescript"
testing the typescript
[root@cserver ~]# exit
exit
Script done, file is cmd.txt


Now supply the time.txt & cmd.txt files as arguments to the conversion script & specify out.gif as the output file.

./typeconv.sh time.txt cmd.txt out.gif

This will replay the commands & create an out.gif file.

Here is the out.gif file created a result of the execution of the script:


Note that the resulting gif does not execute in a infinite loop. It runs only once.

Using TermRecord for recording terminal sessions

I recently used TermRecord & found it to be an awesome lightweight & fast tool for terminal recording.The installation was fairly simple. TermRecord is a program that wraps the script command. It automatically detects your terminal size, records your session, and stores the output as either JSON, embeddable JavaScript, or a static HTML file. The HTML is completely self-contained, embedding all necessary dependencies in one file and can be shipped to anyone that has a modern browser.
You can store these files as your own notes or use them as instructional examples, or whatever you want! 

I downloaded the source code from https://pypi.python.org/pypi/TermRecord.

I extracted the source code:

[root@cserver ~]# cd TermRecord-1.2.4/
[root@cserver TermRecord-1.2.4]# ls
bin  MANIFEST.in  PKG-INFO  setup.cfg  setup.py  termrecord  TermRecord.egg-info

Then I ran setup.py to install the package:

[root@cserver TermRecord-1.2.4]# python setup.py install
running install
running bdist_egg
running egg_info
writing requirements to TermRecord.egg-info/requires.txt
writing TermRecord.egg-info/PKG-INFO
writing top-level names to TermRecord.egg-info/top_level.txt
writing dependency_links to TermRecord.egg-info/dependency_links.txt
reading manifest file 'TermRecord.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'TermRecord.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
creating build
creating build/lib
creating build/lib/termrecord
copying termrecord/__init__.py -> build/lib/termrecord
creating build/lib/termrecord/templates
copying termrecord/templates/dynamic.jinja2 -> build/lib/termrecord/templates
copying termrecord/templates/base.jinja2 -> build/lib/termrecord/templates
copying termrecord/templates/static.jinja2 -> build/lib/termrecord/templates
creating build/bdist.linux-x86_64
creating build/bdist.linux-x86_64/egg
creating build/bdist.linux-x86_64/egg/termrecord
copying build/lib/termrecord/__init__.py -> build/bdist.linux-x86_64/egg/termrecord
creating build/bdist.linux-x86_64/egg/termrecord/templates
copying build/lib/termrecord/templates/dynamic.jinja2 -> build/bdist.linux-x86_64/egg/termrecord/templates
copying build/lib/termrecord/templates/base.jinja2 -> build/bdist.linux-x86_64/egg/termrecord/templates
copying build/lib/termrecord/templates/static.jinja2 -> build/bdist.linux-x86_64/egg/termrecord/templates
byte-compiling build/bdist.linux-x86_64/egg/termrecord/__init__.py to __init__.pyc
creating build/bdist.linux-x86_64/egg/EGG-INFO
installing scripts to build/bdist.linux-x86_64/egg/EGG-INFO/scripts
running install_scripts
running build_scripts
creating build/scripts-2.7
copying and adjusting bin/TermRecord -> build/scripts-2.7
changing mode of build/scripts-2.7/TermRecord from 644 to 755
creating build/bdist.linux-x86_64/egg/EGG-INFO/scripts
copying build/scripts-2.7/TermRecord -> build/bdist.linux-x86_64/egg/EGG-INFO/scripts
changing mode of build/bdist.linux-x86_64/egg/EGG-INFO/scripts/TermRecord to 755
copying TermRecord.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO
copying TermRecord.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying TermRecord.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying TermRecord.egg-info/requires.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying TermRecord.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
zip_safe flag not set; analyzing archive contents...
termrecord.__init__: module references __file__
creating dist
creating 'dist/TermRecord-1.2.4-py2.7.egg' and adding 'build/bdist.linux-x86_64/egg' to it
removing 'build/bdist.linux-x86_64/egg' (and everything under it)
Processing TermRecord-1.2.4-py2.7.egg
creating /usr/lib/python2.7/site-packages/TermRecord-1.2.4-py2.7.egg
Extracting TermRecord-1.2.4-py2.7.egg to /usr/lib/python2.7/site-packages
Adding TermRecord 1.2.4 to easy-install.pth file
Installing TermRecord script to /usr/bin

Installed /usr/lib/python2.7/site-packages/TermRecord-1.2.4-py2.7.egg
Processing dependencies for TermRecord==1.2.4
Searching for Jinja2==2.7.2
Best match: Jinja2 2.7.2
Adding Jinja2 2.7.2 to easy-install.pth file

Using /usr/lib/python2.7/site-packages
Searching for MarkupSafe==0.11
Best match: MarkupSafe 0.11
Adding MarkupSafe 0.11 to easy-install.pth file

Using /usr/lib64/python2.7/site-packages
Finished processing dependencies for TermRecord==1.2.4


The TermRecord binary was copied to /usr/bin.

Using TermRecord is fairly simple. Just specify the TermRecord command followed by -o & path to the output html file. Run the commands you'd like to record & type exit.

[root@cserver TermRecord-1.2.4]# TermRecord -o /tmp/test.html
Script started, file is /tmp/tmp4C9Aj3
[root@cserver TermRecord-1.2.4]# echo "This is strictly a test"
This is strictly a test
[root@cserver TermRecord-1.2.4]# echo "testing to see if TermRecord works!!"
echo "testing to see if TermRecord worksecho "This is strictly a test""
testing to see if TermRecord worksecho This is strictly a test
[root@cserver TermRecord-1.2.4]# exit
exit
Script done, file is /tmp/tmp4C9Aj3

Sunday, 13 November 2016

Getting started with Saltstack part 5 (expanding states with jinja2, pillar & introducing highstates)

Jinja 2 is a templating language used in pyhton. It allows use code blocks to serve files with dynamic content. There are 2 ways to use jinja 2 templates in Salt state files. The first type is variable wherein a variable is enclosed within a set of double curly braces. For example, {{ myvar }}. We can use basic conditional statements in jinja 2 templates providing some conditional flow control. Syntax for using conditional statement is using % symbol at beginning & end of the curly braces like {{% some_condition %}}. This can help make our state files platform agnostic.

Consider the apache state file that was used in the previous article. We know that apache is installed as httpd in RedHat OS variants & as apache2 in Debian variants. Let's use jinja 2 to modify the state file such that httpd is installed for RedHat & apache2 for Debian variants respectively.

install_apache:
 pkg.installed
{{% if grains['os_family'] == 'RedHat' %}}
   - name: httpd
{{% elif grains['os_family'] == 'Debian' %}}
   - name: apache2
{{% endif %}}

ensure apache is started:
 service.running:
{{% if grains['os_family'] == 'RedHat' %}}
   - name: httpd
{{% elif grains['os_family'] == 'Debian' %}}
   - name: apache2
{{% endif %}}
   - enable: True
   - require:
      - pkg: install apache


Understanding pillars:

Using pillars is a means of providing access to certain data to selected minions only so that the data is 'need to know basis only' for the minions. We define our pillar files in /srv/pillar directory with the .sls extension. Once we've defined pillar in .sls files, we need to write a topfile top.sls to inform the salt master which minions will have access to which pillar data. Given below is an example topfile:

base:
  '*':
    - pill1
  'os_family:debian':
    - match: grain
    - pill2

The above top file states that all minions will have access to data in pillar file pill1 but only minions running debian OS variant will have access to date in pill2. Pillar data distributed in this manner can be used in state files in combination with jinja 2 templates.

To sync pillar data across minions we use saltutil.refresh_pillar command like the example below:

salt '*' pillar.refresh_pillar

To view pillar items distributed accross the minions use pillar.items command:

salt '*' pillar.items


Highstates:

The concept of highstates allows us to apply different state state files to different minions together in one go thereby exetending the different desired state of configurations across multiple minions via the execution of a single salt command.
To apply a highstate configuration we use the state.highstate module.

salt '*' state.highstate

The state.highstate command executes the declared desired configuration state as described in the top file which is also used for distributing pillar data.

So, to implement a highstate an example top file is shown below:

base:
 '*":
  - state1
'os_family:RedHat':
  - state2

When we run the highstate, the state1 configuration is applied across all minions & the state2 configuration is applied only on minions running a RedHat OS variant.

Getting started with Saltstack part 4 (Configuration management using states)

We implement Salt's configuration management aspect via states. A state in Salt terminology is a file which basically represents the desired state of configuration that we need our minions to be in. By default, state files are stored in /srv/salt directory. Any Salt specific file that is not a python script has a .sls extension.

I've created a state file apache.sls in /srv/salt directory with the following content:

[root@cserver salt]# cat apache.sls
install_apache:
 pkg.installed:
  - name: httpd

ensure apache is started:
 service.running:
  - name: httpd
  - enable: True

Implementation of this state will install httpd service on the minions, start eh service & make sure that service starts on system boot.

To execute the state, use the state.sls module:

[root@cserver salt]# salt '*' state.sls apache
secondminion:
----------
          ID: install_apache
    Function: pkg.installed
        Name: httpd
      Result: True
     Comment: Package httpd is already installed
     Started: 06:03:24.373785
    Duration: 606.13 ms
     Changes:
----------
          ID: ensure apache is started
    Function: service.running
        Name: httpd
      Result: True
     Comment: The service httpd is already running
     Started: 06:03:24.980703
    Duration: 37.723 ms
     Changes:

Summary for secondminion
------------
Succeeded: 2
Failed:    0
------------
Total states run:     2
Total run time: 643.853 ms


Like the modules we used for remote execution, we can get information on modules pertaining to state executions by querying them using the sys module as shown below:

[root@cserver salt]# salt '*' sys.list_state_functions pkg
secondminion:
    - pkg.group_installed
    - pkg.installed
    - pkg.latest
    - pkg.mod_aggregate
    - pkg.mod_init
    - pkg.mod_watch
    - pkg.purged
    - pkg.removed
    - pkg.uptodate
firstminion:
    - pkg.group_installed
    - pkg.installed
    - pkg.latest
    - pkg.mod_aggregate
    - pkg.mod_init
    - pkg.mod_watch
    - pkg.purged
    - pkg.removed
    - pkg.uptodate
[root@cserver salt]# salt '*' sys.list_state_functions service
secondminion:
    - service.dead
    - service.disabled
    - service.enabled
    - service.mod_watch
    - service.running
firstminion:
    - service.dead
    - service.disabled
    - service.enabled
    - service.mod_watch
    - service.running
[root@cserver salt]#


To view documentation related to a module using sys.state_doc module.

[root@cserver salt]# salt '*' sys.state_doc service
secondminion:
    ----------
    service:

        Starting or restarting of services and daemons
        ==============================================

        Services are defined as system daemons typically started with system init or
        rc scripts. The service state uses whichever service module that is loaded on
        the minion with the virtualname of ``service``. Services can be defined as
        running or dead.

        If you need to know if your init system is supported, see the list of supported
        :mod:`service modules <salt.modules.service.py>` for your desired init system
        (systemd, sysvinit, launchctl, etc.).

        Note that Salt's service execution module, and therefore this service state,
        uses OS grains to ascertain which service module should be loaded and used to
        execute service functions. As existing distributions change init systems or
        new distributions are created, OS detection can sometimes be incomplete.
        If your service states are running into trouble with init system detection,
        please see the :ref:`Overriding Virtual Module Providers <module-provider-override>`
        section of Salt's module documentation to work around possible errors.

        Note:
            The current status of a service is determined by the return code of the init/rc
            script status command. A status return code of 0 it is considered running.  Any
            other return code is considered dead.

            httpd:
              service.running: []

        The service can also be set to be started at runtime via the enable option:

            openvpn:
              service.running:
                - enable: True


The basic structure of a state file is as follows:

<ID Declaration>:  
<State Module>.<Function>:   
   - name: <name>    
   - <Function Arg>   
   - <Function Arg>    
   - <Function Arg>    
  - <Requisite Declaration>:     
   - <Requisite Reference> 

The file are written in YAML so syntax is very important.

The ID declaration is the description of the state. Next is the execution module that we'll be using followed by the name of the item which will serve as the input to the execution module. The final part is the requisite declaration which can be used to enforce dependencies. 

The require requisite:
The require requisite is useful in enforcing dependencies between states & an order of execution.
For example in the state file created earlier we can put a require dependency to ensure that the state responsible for starting the httpd service is executed only when the state responsible for installing the package is executed successfully.

make sure apache is running: 
 service.running:    
  - name: apache2    
  - enable: True    
  - require:      
    - pkg: install_apache

install_apache:  
 pkg.installed:    
 - name: apache


The watch requisite:
The watch requisite is similar to the require requisite such that the watching state gets executed only if the watched state gets successfully executed first.

The _in requisite:
This also sets a dependency but slightly differently. The common for of the _in requisite in require_in. Here is a example of how I modified the apache.sls state file to use require_in instead of the require requisite:

make sure apache is running: 
 service.running:    
  - name: apache2    
  - enable: True    

install_apache:  
 pkg.installed:    
 - name: apache
 - require_in:
   - service: make sure apache is running

The above code is functionally equivalent to the example described earlier using the require requisite.

Saturday, 12 November 2016

Getting started with Saltstack part 3 (Writing custom modules)

Apart from the plethora of execution modules already available, Salt gives us the tools to write our own custom modules as well. Salt uses python under the hood to provide all the system administration functionality features distributed in the form of execution modules. We can leverage these existing salt modules by calling them in our custom made module.  When Salt loads all of the execution modules, it creates a dictionary with references to each execution module function. This dictionary is available as __salt__.

I've written one such custom module to illustrate this feature & will describe it's usage in this article.

Salt looks in directory path /srv/salt/_modules for custom modules to sync & use. These custom modules are essentially python scripts.

Let's get started by creating the directory path:

mkdir /srv/salt/_modules
cd /srv/salt/_modules

Now we write our script named atest.py

[root@cserver _modules]# cat atest.py
def reserv():
    '''
    Test module to reload a service
    CLI Example:
    .. code-block:: bash
    salt '*' test_comm.reserv
    '''
    source = '/etc/ssh/ssh_config'
    destination= '/tmp/'
    copy_file = __salt__['rsync.rsync'] (source, destination)
    ser_name = 'sshd'
    test_comm = __salt__['service.reload'](ser_name)
    return copy_file
    return test_comm


The above script will do two things. It'll copy the ssh_config file to the /tmp directory & reload the ssh service across the minions on which it is being executed.
The script is using the rsync & service modules.
The ''' are used to enclose text that will serve as documentation if someone runs sys.doc against the custom module.

After writing the script we need to sync it across the minions by typing saltutils.sync_all;

[root@cserver _modules]# salt '*' saltutil.sync_all
firstminion:
    ----------
    beacons:
    engines:
    grains:
    log_handlers:
    modules:
        - modules.atest
    output:
    proxymodules:
    renderers:
    returners:
    sdb:
    states:
    utils:
secondminion:
    ----------
    beacons:
    engines:
    grains:
    log_handlers:
    modules:
        - modules.atest
    output:
    proxymodules:
    renderers:
    returners:
    sdb:
    states:
    utils:


We need to run this command while we are in the /srv/salt/_modules directory.

After the sync is complete we can test the module by running it across minions:

[root@cserver _modules]# salt '*' atest.reserv
secondminion:
    ----------
    pid:
        16678
    retcode:
        0
    stderr:
    stdout:
        sending incremental file list
        ssh_config

        sent 1132 bytes  received 31 bytes  2326.00 bytes/sec
        total size is 2123  speedup is 1.83
firstminion:
    ----------
    pid:
        51866
    retcode:
        0
    stderr:
    stdout:
        sending incremental file list
        ssh_config

        sent 1132 bytes  received 31 bytes  2326.00 bytes/sec
        total size is 2123  speedup is 1.83


& it works!

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...