在复制时将with_fileglob用于多个src和目标

时间:2017-05-20 11:57:59

标签: ansible yaml

我需要它将多个配置文件部署到一系列目录。

- name: Deploy apache configuration files
  template: src={{ item.src }} dest=/etc/httpd/{{ item.dest }} mode=0644
  with_fileglob:
  - { src: "../templates/apache_templates/conf/*.conf", dest: 'conf' }
  - { src: "../templates/apache_templates/conf.d/*.conf", dest: 'conf.d' }

当我运行上述任务时,我收到以下错误。

An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 90, in run
items = self._get_loop_items()
File "/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 205, in _get_loop_items
items = mylookup.run(terms=loop_terms, variables=self._job_vars, wantlist=True)
File "/usr/lib/python2.7/site-packages/ansible/plugins/lookup/fileglob.py", line 34, in run
term_file = os.path.basename(term)
File "/usr/lib64/python2.7/posixpath.py", line 121, in basename
i = p.rfind('/') + 1
AttributeError: 'dict' object has no attribute 'rfind'

 fatal: [server1.example.com]: FAILED! => {
"failed": true, 
"msg": "Unexpected failure during module execution.", 
"stdout": ""

}

当我在上面的任务中将with_fileglob替换为with_items时,会抛出msg": "Unable to find '../templates/apache/conf/*.conf' in expected paths."错误,这个错误很奇怪,因为路径确实存在。

但是当我像下面那样对配置文件进行硬编码时,任务按预期工作。以这种方式编写任务会破坏循环的目的,因为我有多个配置文件要部署

- name: Deploy apache configuration files
  template: src={{ item.src }} dest=/etc/httpd/{{ item.dest }} mode=0644
  with_items:
  - { src: "../templates/apache_templates/conf/vhost1.conf", dest: 'conf' }
  - { src: "../templates/apache_templates/conf.d/example1.conf", dest: 'conf.d' }

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

In you question you are using two destination paths which can be extracted from your source path. So for above question you can use this. The config which you are using will not work. You can use it this way.

1. {{item | dirname | regex_replace('.*/','')}} this will return folder name, from the path. For example your path is ../templates/apache_templates/conf/*.conf then dirname filter will return ../templates/apache_templates/conf and regex_replace's regex replace all till /, then result will be conf

---
- hosts: your_host
  gather_facts: no
  tasks:
  - name: "Copy files from source to destination"
    copy:
     src: "{{item}}"
     dest: "{{item | dirname | regex_replace('.*/','')}}"
    with_fileglob:
    - "../templates/apache_templates/conf/*.conf"
    - "../templates/apache_templates/conf.d/*.conf"
---