ansible – restart a (nginx) service only if it is running and the configuration is ok

Another ansible quick tip showing how to restart a program properly. We want to restart the program or the service only if it is running (because some system on executing restart may start the service even it is in the stopped state).
Here is what the ansible playbook do:

  1. Check if the program is running.
  2. Check the configuration of the program. Do not restart a program or service if it cannot start after a stop command because of bad configuration file(s).
  3. Restart the service (the program) only if the above two are true.

If you are a newbie in ansible you can check this article – First ansible use – install and execute a single command or multiple tasks in a playbook There you can see how to create your inventory file (and configure sudo if you remotely log in with unprivileged user) used herein the example.

Ansible YAML file

For our example we use the nginx webserver in the ansible playbook. Put the following code in a file and then execute ansible-playbook:

---
- hosts: all
  tasks:
            
    - name: Test for running nginx
      shell: ps axuf|grep 'nginx'|grep -v "grep" | tr -d "\n" | cat
      register: test_running_nginx
      changed_when: False
      tags: restart-nginx
      
    - name: First check the configuration
      shell: /usr/sbin/nginx -t
      register: test_nginx_config
      when: test_running_nginx.stdout != ""
      changed_when: False
      ignore_errors: True
      tags: restart-nginx
          
    - name: Restart nginx
      service: name=nginx state=restarted
      when: test_running_nginx.stdout != "" and test_nginx_config.rc == 0
      tags: restart-nginx

Here is how to run the above ansible playbook

myuser@srv ~ $ ansible-playbook -l srv2 -i ./inventory.ini ./playbook-example.yml -b

PLAY [all] *****************************************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [srv2]

TASK [Test for running nginx] **********************************************************************************************************************************************
ok: [srv2]

TASK [First check the configuration] ***************************************************************************************************************************************
ok: [srv2]

TASK [Restart nginx] *******************************************************************************************************************************************************
changed: [srv2]

PLAY RECAP *****************************************************************************************************************************************************************
srv2                       : ok=4    changed=1    unreachable=0    failed=0   

Here we add to the command line “-b”, which will escalate to root if it is needed (using sudo) because the remote connection is done with unprivileged user “myuser”. You can skip this option if you described the remote connection with the root user in the inventory file (or a system user, which has permissions to restart services).
Keep on reading!

ansible – insert after only if the pattern exists and the new insert is not there

Here is a quick ansible tip for system administrators for the ansible lineinfile. Imagine you want to insert a line after a word (or a predefined marker in your configuration file), but you want to insert the line ONLY if the word exists!
It could be done with lineinfile module but there is a limitation. The module will insert after the first occurrence of your marker or at the end of the file. Here is what the manual says: “If specified regular expression has no matches, EOF will be used instead.” And what if you what to insert some additional line to your structured configuration file? It will corrupt your configuration file, so we need something else!
Not only this! Imagine you have already inserted the line in a previous playbook run? It will be unwanted to add the line, again and again, each time the playbook is run. So here we propose the following solution:

  1. Test for existance of the file you want to insert text.
  2. Test for the existance of the marker (aka tag) in the file.
  3. Test for the existance of the line we want to insert.
  4. Insert the line after the marker (aka tag) if all of the above three conditions are true.

Here we use three ansible modules – stat, shell, lineinfile and variables and conditional checks.
If you are a newbie in ansible you can check this article – First ansible use – install and execute a single command or multiple tasks in a playbook There you can see how to create your inventory file (and configure sudo if you remotely log in with unprivileged user) used herein the example:

Ansible YAML file

---
- hosts: all
  tasks:
        - name: Test for nginx-config
          stat:
            path: /etc/nginx/nginx.conf
          register: test_exist_nginx_config
          tags: cors-insert-include
      
        - name: Test for \#FIRST-SRV-LOCATION tag
          shell: grep '#FIRST-SRV-LOCATION' /etc/nginx/nginx.conf | tr -d "\n" | cat
          register: test_first_srv_location
          when: test_exist_nginx_config.stat.exists
          changed_when: False
          tags: cors-insert-include

        - name: Test for cors-locations.loc inserted already
          shell: grep "cors-locations.loc" /etc/nginx/nginx.conf | tr -d "\n" | cat
          register: test_cors_locations_loc
          when: test_exist_nginx_config.stat.exists
          changed_when: False
          tags: cors-insert-include
          
        - name: Insert the includes after \#FIRST-SRV-LOCATION
          lineinfile:
            path: /etc/nginx/nginx.conf
            insertafter: '#FIRST-SRV-LOCATION'
            line: '                include /etc/nginx/conf.d/cors-locations.loc;'
            state: present
          when: test_exist_nginx_config.stat.exists and test_first_srv_location.stdout != "" and test_cors_locations_loc.stdout == ""
          tags: cors-insert-include

We want to insert a new include line after our predefined tag “#FIRST-SRV-LOCATION” in the nginx webserver’s main configuration file.

Here is how to run the above ansible playbook

Keep on reading!

su to user with no shell

Most users in our linux/unix system have no ability to login, because the shell is /sbin/nologin (or even /bin/false). But sometimes we need to execute a command or to get in the shell under those users and when we try to switch the user to let’s sat nginx or apache or nagios we get an error:

[root@srv ~]# su nginx
This account is currently not available.
[root@srv ~]# su apache
This account is currently not available.
[root@srv ~]# su nagios
This account is currently not available.
[root@srv ~]# su nrpe
This account is currently not available.

But still we need to run a command or commands from that user! So we can do it with instructing the su command which shell to execute for us not taking into account the one in /etc/passwd:

su nagios -s /bin/bash

And now we are user “nagios”:

[root@srv ~]# su nagios -s /bin/bash
bash-4.2$ whoami
nagios

Go and execute commands to see why something is not working under you nagios user…

Busybox ash, Debian dash and simulating bash arrays

Busybox ash (Almquist shell) shell and Debian dash (Debian Almquist shell) are lightweight Unix shell and they are a variant of System V.4 variant of the Bourne shell. Ash/dash shell is known to be very small and is used mainly in embedded (ash) devices and installation scripts (Debian/Ubuntu setup).
Unfortunately they do not support arrays, which could be really a problem in many cases. But we can simulate the arrays with eval function.
So if you need to write a ash/dash script let’s say for an installation script of Ubuntu or Debian or a script for an embedded device, which uses busybox or even you do not want to use arrays in bash, you can follow the consepts below – create variable with a “name” concatenated with a number.

  • 1) Set a variable

    It can be done with two ways:

    1. for myi in 0 1 2 ; do
          setvar mvar$myi "Payload: $myi"
      done
      
    2. for myi in 0 1 2 ; do
          eval mvar$myi=\"Payload: $myi\"
      done
      

    This will create variables with names:

    mvar1, mvar2, mvar3

    and they can be used in any place of your script after the creation of the variables using “eval” or accessing them with the names.

    * bash shell do not support the command “setvar”, so for bash scripts use only eval version.

  • 2) Use a variable

    1. using “eval”
      for myi in 0 1 2 ; do
          eval echo \$mvar$myi
      done
      
      myi=1
      eval newvar="\$mvar$myi"
      echo $newvar
      
    2. direct access
      echo $mvar2
      $mvar2="Payload 20"
      echo $mvar2