Score:0

Ansible - how to loop through services present in inventory file

vn flag

winapp.example.comHello, I have an inventory file that holds both windows application servers, web servers and only respective services which need to stopped or restarted. Requirement is only specific services should be stopped for group of hosts. For e.g. appservers hosts should use services under appservers:vars

Appreciate your help !!!

Inventory\hosts.ini file contains

[appservers]
winapp1.example.com
winapp2.example.com

[appservers:vars]
  services:
    - WorkflowService
    - ConfigurationService
    - SyncService
    - ParentConfigurationService

[slaveappservers]
winslvapp1.example.com
winslvapp2.example.com

[slaveappservers:vars]
  services:
    - SyncService
    - ParentConfigurationService

[webservers] 
webser1.ent.wfb.bank.corp

[webservers:vars]
  services:
    - WorkflowService
    - SyncService
    - ParentConfigurationService

[allservers:children]
appservers
slaveappservers
webservers

service_stop.yml

---
- name:  SHRP service stop Demo
  hosts: all
  gather_facts: false

  tasks:
  - name: Pause a service
    win_service:
      name: "{{ item }}"
      state: stopped
    loop: 
      - "{{ services }}"
Score:1
cn flag

Your already have one solution. Define a variable with the same name, but group specific values. Use that one variable name in plays that can run on both groups.

Several syntaxes exist to get group specific values.

  • Defining a variable in inventory for a group
  • In group_vars files adjacent to playbook or inventory.
  • A lookup expression or dict indexed by group name.

Yours is an example of the first.

vn flag
I thought I provided a variable name as "services" to make it common across groups. With above settings I get an error when play is executed as "services" not defined. Appreciate your help !!!
John Mahowald avatar
cn flag
Please edit your question to add the error.
vn flag
I have the same code mentioned above and When I ran the playbook, I got the following error. { "msg": "Invalid data passed to 'loop', it requires a list, got this instead: services. Hint: If you passed a list/dict of just one element, try adding wantlist=True to your lookup invocation or use q/query instead of lookup.", "_ansible_no_log": null }
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.