hep*_*olu 12 ansible ansible-playbook
我是Ansible的新手,我正在尝试创建一个将文件复制到远程服务器的角色.每次我运行playbook时,本地文件都可以有不同的名称,但需要远程复制到同一名称,如下所示:
- name: copy file
copy:
src=*.txt
dest=/path/to/fixedname.txt
Run Code Online (Sandbox Code Playgroud)
Ansible不允许使用通配符,所以当我用主要剧本中的任务编写一个简单的剧本时,我可以这样做:
- name: find the filename
connection: local
shell: "ls -1 files/*.txt"
register: myfile
- name: copy file
copy:
src="files/{{ item }}"
dest=/path/to/fixedname.txt
with_items:
- myfile.stdout_lines
Run Code Online (Sandbox Code Playgroud)
但是,当我将任务移动到角色时,第一个操作不再起作用,因为相对路径是相对于角色,而playbook在'roles'目录的根目录中执行.我可以添加角色文件目录的路径,但有更优雅的方式吗?
Ram*_*nte 13
看起来您需要访问在本地查找信息的任务,然后将该信息用作复制模块的输入.
获取本地信息有两种方法.
在你的情况下,我会使用第二种方法lookup.你可以像这个例子一样设置它:
vars:
local_file_name: "{{ lookup('pipe', 'ls -1 files/*.txt') }}"
tasks:
- name: copy file
copy: src="{{ local_file_name }}" dest=/path/to/fixedname.txt
Run Code Online (Sandbox Code Playgroud)
或者,更直接地:
tasks:
- name: copy file
copy: src="{{ lookup('pipe', 'ls -1 files/*.txt') }}" dest=/path/to/fixedname.txt
Run Code Online (Sandbox Code Playgroud)
查找插件从任务的上下文(playbook vs role)运行.这意味着它的行为会有所不同,具体取决于它的使用位置.
在上面的设置中,任务直接从剧本中运行,因此工作目录将是:
/path/to/project - 这是您的剧本所在的文件夹.
如果您将任务添加到角色,则工作目录将是:
/path/to/project/roles/role_name/tasks
此外,file和pipe插件在角色/ files文件夹中运行(如果存在):
/path/to/project/roles/role_name/files - 这意味着你的命令是 ls -1 *.txt
每次访问变量时都会调用该插件.这意味着您无法信任调整Playbook中的变量,然后在角色稍后使用时依赖该变量具有相同的值!
我不知道,关于文件的用例,它位于项目ansible文件夹中,但事先并不知道谁的名字.这样的文件来自哪里?是不是可以在文件的生成和在Ansible中使用它或在固定的本地路径作为变量之间添加一个层?只是好奇 ;)
只是想提出一个额外的答案...我有同样的问题,我在那里建立一个ansible捆绑包并将工件(rpms)复制到角色的文件夹中,我的rpms在文件名中有版本.
当我运行ansible游戏时,我希望它安装所有rpms,无论文件名如何.
我通过使用with_fileglobansible中的机制解决了这个问题:
- name: Copy RPMs
copy: src="{{ item }}" dest="{{ rpm_cache }}"
with_fileglob: "*.rpm"
register: rpm_files
- name: Install RPMs
yum: name={{ item }} state=present
with_items: "{{ rpm_files.results | map(attribute='dest') | list }}"
Run Code Online (Sandbox Code Playgroud)
我发现它比查找机制更清晰一些.