ansible command for checking service - ansible

I am using Ansible and trying to make a simple playbook to check if a service is up.
service... account-daemon.service
part of my playbook which included this is as follows:
- name account daemon service get status
command: systemctl show -p SubState account-daemon
register: status
- debug: msg="{{ status.stout }}"
Please note there is no spaces between playbook.

You can use as below to check the status of services, example below for rscd
- name: populate service facts
service_facts:
- debug:
var: ansible_facts.services
- debug:
msg: "service is running"
when: ansible_facts.services['account-daemon.service'].state == "running"
Output:
ok: [localhost] => {
"msg": "service is running"
}
Reference: https://docs.ansible.com/ansible/latest/modules/service_facts_module.html
Edit:
- name: check rscd
stat:
path: /etc/init.d/rscd
register: serv
- name: populate service facts
service_facts:
- debug:
var: ansible_facts.services
- debug:
msg: "rscd is running"
when: serv.stat.exists and ansible_facts.services['rscd.service'].state == "running"

Related

Ansible to consolidate service status on multiple servers

Below playbook works where inventory groups has multiple servers and to check the status of each service and display its status on console.
Problem is, I wanted to consolidate the status of each service on every server and send in an email, but it seems array (uistatus_app, uistatus_status, uistatus_print) gets re-initiated for each server run.
Is there any way where I can store the status in the global variable of each run and display?
for example:
server1: nginx is active
server1: PHP is active
server2: nginx is active
server2: PHP is unknown
Thanks.
- name: checking services
shell: 'systemctl is-active {{item}}'
with_items:
- nginx
- php74-php-fpm
failed_when: false
register: uistatus
when: 'inventory_hostname in groups[''stg-ui]'
- name: get ui status in arrray
set_fact:
uistatus_app: '{{uistatus_app}}+[ ''{{item.item}}'']'
uistatus_status: '{{uistatus_app}}+[ ''{{item.stdout}}'']'
with_items: '{{ uistatus.results }}'
when: 'inventory_hostname in groups[''stg-ui]'
- name: consolidate
set_fact:
uistatus_print: '{{uistatus_print}}+{{inventory_hostname}}: {{item[0]}} is item[1]}}]'
loop: '{{ query(''together'',uistatus_app, uistatus.status }}'
when: 'inventory_hostname in groups[''stg-ui]'
Set the variable with the list of the statuses in each host, e.g.
- hosts: all
tasks:
- name: checking services
command: "echo {{ item }} is active"
loop:
- nginx
- php74-php-fpm
failed_when: False
register: uistatus
when: inventory_hostname in groups.stg_ui
- set_fact:
my_services: "{{ uistatus.results|default([])|
map(attribute='stdout')|
list }}"
- debug:
var: my_services
gives
ok: [server1] =>
my_services:
- nginx is active
- php74-php-fpm is active
ok: [server2] =>
my_services:
- nginx is active
- php74-php-fpm is active
Then run_once, extract the lists and create the dictionary all_services, e.g.
- set_fact:
all_services: "{{ dict(ansible_play_hosts|zip(stats)) }}"
vars:
stats: "{{ ansible_play_hosts|
map('extract', hostvars, 'my_services')|
list }}"
run_once: true
- debug:
var: all_services
run_once: true
gives
ok: [server1] =>
all_services:
server1:
- nginx is active
- php74-php-fpm is active
server2:
- nginx is active
- php74-php-fpm is active
The dictionary is available to all hosts in the playbook.

How to print command output in Ansible when there is a condition?

My ansible code looks something like the following. Problem is this only works when my inventory has dev,qa, perf and prod servers. For example, if my inventory has only dev servers then it fails. Is there any way to avoid this failure ?
I tried changing both cmd_dev_out and cmd_qa_out to cmd_out but that did not help either.
- name: Execute
hosts: all
tasks:
- name: Execute against dev
shell: some command
register: cmd_dev_out
when: ( servers are dev )
- debug: msg="{{ cmd_dev_out }}"
- name: Execute against qa
shell: some command
register: cmd_qa_out
when: ( servers are qa )
- debug: msg="{{ cmd_qa_out }}"
....... More conditions below .....
The best would be to use a block in here to logically group the execution of the command and the print of the output of the said command.
Because, if there is no command run, well, obviously you won't get anything as a result.
This is an example using block
- name: Execute
hosts: all
tasks:
- block:
- name: Execute against dev
shell: 'echo "dev"'
register: cmd_dev_out
- debug:
msg: "{{ cmd_dev_out }}"
when: "'dev' in inventory_hostname"
- block:
- name: Execute against qa
shell: 'echo "qa"'
register: cmd_qa_out
- debug:
msg: "{{ cmd_qa_out }}"
when: "'qa' in inventory_hostname"
Mind that this means that the condition when is now tied to the block and both the command and the debug will be skipped when the condition is false.
Example of recap:
PLAY [localhost] **************************************************
TASK [Execute against dev] ****************************************
skipping: [localhost]
TASK [debug] ******************************************************
skipping: [localhost]
TASK [Execute against qa] *****************************************
changed: [localhost]
TASK [debug] ******************************************************
ok: [localhost] =>
msg:
changed: true
cmd: echo "qa"
delta: '0:00:00.002641'
end: '2023-01-25 20:51:04.049532'
failed: false
msg: ''
rc: 0
start: '2023-01-25 20:51:04.046891'
stderr: ''
stderr_lines: []
stdout: qa
stdout_lines:
- qa
Another, but maybe less elegant solution would be to use the default Jinja filter on your command result in case the command was skipped.
- name: Execute
hosts: all
tasks:
- name: Execute against dev
shell: 'echo "dev"'
register: cmd_dev_out
when: "'dev' in inventory_hostname"
- debug:
msg: "{{ cmd_dev_out | default('cmd_dev was skipped') }}"
- name: Execute against qa
shell: 'echo "qa"'
register: cmd_qa_out
when: "'qa' in inventory_hostname"
- debug:
msg: "{{ cmd_qa_out | default('cmd_qa was skipped') }}"
Figured out another solution. Its given below (add the when condition to the debug statement) :
- name: Execute
hosts: all
tasks:
- name: Execute against dev
shell: some command
register: cmd_dev_out
when: ( servers are dev )
- debug: msg="{{ cmd_dev_out }}"
when: ( servers are dev )
- name: Execute against qa
shell: some command
register: cmd_qa_out
when: ( servers are qa )
- debug: msg="{{ cmd_qa_out }}"
when: ( servers are qa )
....... More conditions below .....

how to use when condition in ansible

I have the part of the script:
- name: To Display SPLUNK Status
shell: service splunk status | grep PID
register: STATUS
- name: Showing SPLUNK Status
debug: var=STATUS.stdout_lines
- name: Getting Process IDs of the SPLUNK
shell: ps -ef|grep -i splunk
register: pids_of_SPLUNK
- name: Printing the process IDs obtained
debug: var=pids_of_SPLUNK.stdout_lines
#- name: SPLUNK is NOT running
- debug: msg="Splunk is NOT running"
when: not STATUS.stat.exists
#- name: SPLUNK is Running
- debug: msg="Splunk is Restarted and Running"
that line getting me the error: when: not STATUS.stat.exists
when splunk is running it has the status:
Splunk status:
splunkd is running (PID: 7198).
splunk helpers are running (PIDs: 7200).
When splunk is not running:
Splunk status:
splunkd is not running.
how I can use: when condition for it ?
Thank you.
Use service_facts. For example
vars:
my_services:
- 'splunk'
- 'apache2'
- 'ssh'
tasks:
- service_facts:
- debug:
msg: "Service {{ item }} is not available."
loop: "{{ my_services }}"
when: item not in ansible_facts.services.keys()|list
- debug:
msg: "Service {{ item }} is available."
loop: "{{ my_services }}"
when: item in ansible_facts.services.keys()|list
- debug:
msg: "{{ item }} is {{ ansible_facts.services[item].state }}"
loop: "{{ my_services }}"
when: item in ansible_facts.services.keys()|list
give
"msg": "Service splunk is not available."
"msg": "Service apache2 is available."
"msg": "Service ssh is available."
"msg": "apache2 is stopped"
"msg": "ssh is running"

How to check any services exists by Ansible?

I want to check the service exists in the terminal host.
So, I just did the playbook as below.
---
- hosts: '{{ host }}'
become: yes
vars:
servicename:
tasks:
- name: Check if Service Exists
stat: 'path=/etc/init.d/{{ servicename }}'
register: servicestatus
with_items: '{{ servicename }}'
- name: Show service service status
debug:
msg: '{{ servicename }} is exists.'
with_items: '{{ servicename }}'
when: servicestatus.stat.exists
Then, I try to execute this playbook to my host that was running Nginx already as below.
ansible-playbook cheknginxservice.yml -i /etc/ansible/hosts -e 'host=hostname' -e 'servicename=nginx'
And I got the error like this.
FAILED! => {"failed": true, "msg": "The conditional check 'servicestatus.stat.exists' failed. The error was: error while evaluating conditional (servicestatus.stat.exists): 'dict object' has no attribute 'stat'\n\nThe error appears to have been in '/home/centos/cheknginxservice.yml': line 13, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n with_items: '{{ servicename }}'\n - name: Show service servicestatus\n ^ here\n"}
to retry, use: --limit #/home/centos/cheknginxservice.retry
So, I think the problem is about stat module when using the condition involved.
Why are you using with_items? You plan to pass multiple services? It matters because the results will be a list if you use with_items. Just remove with_items and it will work. If you want to pass multiple services, then you have to loop through with_items and use item instead of servicename.
- name: Check if Service Exists
stat: 'path=/etc/init.d/{{ servicename }}'
register: servicestatus
- name: Show service service status
debug:
msg: '{{ servicename }} is exists.'
when: servicestatus.stat.exists
There is no native way in Ansible to check the status of a service. You can use the shell module. Notice I used sudo. Your case may be different.
- name: check for service status
shell: sudo service {{ servicename }} status
ignore_errors: true
register: servicestatus
- name: Show service service status
debug:
msg: '{{ servicename }} exists.'
when: servicestatus.rc | int == 0

ansible playbook when: condition ec2 tag is set

Folks,
I'd like to run a simple command, lets say setting a hostname, if an ec2 tag is set on an instance. Consider the following:
- name: Gather facts
action: ec2_facts
- name: Get instance ec2 facts
action: ec2_facts
register: ec2_facts
- name: Get resource tags from ec2 facts
sudo: false
local_action: ec2_tag resource={{ec2_facts.ansible_facts.ansible_ec2_instance_id}} region={{ec2_facts.ansible_facts.ansible_ec2_placement_region}} state=list
register: ec2_tags
- debug: msg="{{ ec2_tags.tags }}"
Output:
TASK: [foo | debug msg="{{ ec2_tags.tags }}"] *****************************
ok: [10.1.15.119] => {
"msg": "{'role': 'foo', 'Name': 'YAY', 'service': 'web', 'env': 'dev'}"
}
So now, I'd like to do the following:
Set a hostname, if the ec2_tags.tags.Name exists. How do i use this in a playbook ? This seems to fail:
- name: friendly hostname
hostname: name={{ec2_tags.tags.Name}}
when: {{ec2_tags.tags.Name}}
Thanks!
when: ec2_tags.tags.Name is defined should do it

Resources