2016-12-29 28 views
0

为我们的Web服务创建部署手册。每个Web服务是在自己的目录,如:Ansible - 检查是否存在多个目录 - 如果是这样,请在每个目录上运行脚本 - 如何?

/webapps/service-one/ 
/webapps/service-two/ 
/webapps/service-three/ 

我要检查,看是否服务目录是否存在,如果是这样,我想运行正常停止服务的shell脚本。目前,我可以使用ignore_errors: yes完成此步骤。

- name: Stop services 
    with_items: services_to_stop 
    shell: "/webapps/scripts/stopService.sh {{item}}" 
    ignore_errors: yes 

尽管如此,但如果其中一个目录不存在或第一次部署服务,则输出非常混乱。我切实想类似的其中之一:

此:

- name: Stop services 
    with_items: services_to_stop 
    shell: "/webapps/scripts/stopService.sh {{item}}" 
    when: shell: [ -d /webapps/{{item}} ] 

或本:

- name: Stop services 
    with_items: services_to_stop 
    shell: "/webapps/scripts/stopService.sh {{item}}" 
    stat: 
    path: /webapps/{{item}} 
    register: path 
    when: path.stat.exists == True 

回答

3

我会收集事实首先,然后只做必要的事情。

- name: Check existing services 
    stat: 
    path: "/tmp/{{ item }}" 
    with_items: "{{ services_to_stop }}" 
    register: services_stat 

- name: Stop existing services 
    with_items: "{{ services_stat.results | selectattr('stat.exists') | map(attribute='item') | list }}" 
    shell: "/webapps/scripts/stopService.sh {{ item }}" 

还要注意,在with_items裸变量不因为Ansible 2.2工作,所以你应该模板它们。

+1

很好地使用了jinja过滤,特别是map()和list过滤器,这是我以前从未见过的方法。 –

+0

这对我所寻找的东西来说非常棒。谢谢! – R4F6

1

这将让你现有的目录名称列表到列表变量dir_names(使用recurse: no来读取webapps下的第一个级别):

--- 

- hosts: localhost 
    connection: local 
    vars: 
    dir_names: [] 

    tasks: 
    - find: 
     paths: "/webapps" 
     file_type: directory 
     recurse: no 
     register: tmp_dirs 
    - set_fact: dir_names="{{ dir_names+ [item['path']] }}" 
     no_log: True 
     with_items: 
     - "{{ tmp_dirs['files'] }}" 

    - debug: var=dir_names 

然后,您可以通过with_items在“停止服务”任务中使用dir_names。它看起来像你打算“的webapps”下使用的目录的唯一名称,以便您可能要使用的| basename的Jinja2过滤器来获取,所以是这样的:

- name: Stop services 
    with_items: "{{ dir_names }}" 
    shell: "/webapps/scripts/stopService.sh {{item | basename }}" 
+1

使用@康斯坦丁的jinja过滤器的例子,你可以跳过我的答案中的set_fact,并使用'“{{tmp_dirs ['files'] | map(attribute ='path')| list}}在停止服务任务 –

相关问题