我正在使用Ansiblecopy
模块,如下所示:
src: folder/file.cert
dest: file_dest.cert
以上适用于文件。但如果我想对某些库存使用Ansible Tower,我会提供file.cert作为变量
现在src
不再工作,我需要使用以下内容:
content: file_cert_variable
dest: file_dest.cert
到目前为止还不错。但现在我想将这两个世界结合起来,这样我就不必添加条件,以防我们在某些环境中使用Tower变量,在其他环境中使用文件作为证书的源
是否有一种方法可以用一个Ansible命令同时覆盖这两种情况?
实际的"ansiblish;描述远程状态的方法是根据var的存在与否进行一个操作:
- name: Copy certificate from variable if set
copy:
content: "{{ file_cert_variable }}"
dest: file_dest.cert
when: file_cert_variable is defined
- name: Copy certificate from local file when no variable is provided
copy:
src: folder/file.cert
dest: file_dest.cert
when: file_cert_variable is not defined
如果你真的无法忍受"重复",有一些方法可以将其"缩短"为一次复制任务。但是,您仍然需要根据内容变量的存在做出决定。最终,您将不会真正拥有任何性能优势,而且解决方案可能最终可读性较差,更难维护,在某些情况下甚至更冗长。下面是我能想到的两个例子。请注意,第二种做法被认为是一种不良做法,会发出警告(即Using a variable for a task's 'args' is unsafe in some situations
(。还要注意,这两个都是部分剧本摘录,都是现场编写的,没有单独测试。
取1:双省略
- name: define our source name when no var is provided
# Note: defining the following var elsewhere will break this example
set_fact:
source_file: folder/file.cert
when: file_cert_variable is not defined
- name: copy file/content to destination
copy:
src: "{{ source_file | default(omit) }}"
content: "{{ file_cert_variable | default(omit) }}"
dest: file_dest.cert
Take2:动态任务dict
vars:
copy_params_defaults:
dest: file_dest.cert
copy_params_additional:
from_var:
content: "{{ file_cert_variable | default('') }}"
from_file:
src: folder/file.cert
copy_from: "{{ file_cert_variable is defined | ternary('from_var', 'from_file') }}"
copy_params: "{{ copy_params_defaults | combine(copy_params_additional[copy_from]) }}"
tasks:
- name: "Copy certificate {{ copy_from }}"
copy: "{{ copy_params }}"