我需要它来将多个配置文件部署到一系列目录。
- 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' 在预期路径中。”
错误,这很奇怪,因为该路径确实存在。
但是,当我像下面那样对配置文件进行硬编码时,任务会按预期进行。以这种方式编写任务违背了循环的目的,因为我有多个配置文件要部署
- 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.
{{item | dirname | regex_replace('.*/','')}}
this will return folder name, from the path. For example your path is../templates/apache_templates/conf/*.conf
thendirname
filter will return../templates/apache_templates/conf
andregex_replace
's regex replace all till/
, then result will beconf
---
- 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"
---
关于ansible - 复制时对多个源和目标使用 with_fileglob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44085585/