Ansible Playbook to start services

Ansible Playbook to start services

We have already seen how to run Ansible Adhoc Command, now let’s focus on a playbook to start any service on your servers, In the example below I have started crond service but you can use it to suit your needs.

#Ansible Playbook to start service
-
  name: Start Services
  hosts: webservers

  become: true
  tasks:
    - name: Start Services
      service:
       name: crond
       state: started

If you have multiple host groups then replace hosts: webservers with below

 hosts: 
   - webserversUSA
   - webserversASIA
   - webserversEurope

You may have a situation where you want to start multiple services, In that case, you can use ansible loop the example playbook is as below.

#Ansible Playbook to start service
-
  name: Start Services
  hosts: webservers

  become: true
  tasks:
    - name: Start Services
      service:
        name: '{{ item }}'
        state: started
      loop:
        - httpd
        - crond
        - and-so-on
   

Disable host-key checking while using ansible adhoc command

If you want to disable host key checking for ansible adhoc command, first run the the command below.

 [root@server ~]# export ANSIBLE_HOST_KEY_CHECKING=False

Now, once you have disabled host key checking run your ansible ad-hoc command.

 [root@server ~]#  ansible all -i inventory -m shell -a 'uptime'

Run Ansible adhoc command with Sudo

[root@server ~]# ansible all -i inventory.yml -m shell -a 'service crond restart' -K --become

Script to format server list into ansible format.

Script to format list of servers into ansible format.
Example:
if you have a text file which has list of servers as below.

app.server.com
app2.server.com
web1.server.com
web2.server.com
[app]
app.server.com
app2.server.com
[web]
web1.server.com
web2.server.com

How to use it ?
create a file generateInventory.sh with the contents below and it the same directory create a file named raw_inventory.txt with list of the servers and run the script using ./generateInventory.sh and you will get ansible format Inventory file will generated.

# Script to format list of servers into ansible format.
file=raw_inventory.txt
 last=''
 while read nameX
 do label="${nameX%%[.0-9]*}"
    if [[ "$label" != "$last" ]]
    then echo "[$label]" # or printf "\n$label\n" for a separator line
         last="$label"
    fi
    echo "$nameX"
 done < $file > Inventory