我正在使用ec2模块,ansible-playbook
我想将变量设置为文件的内容.这是我目前正在做的事情.
Var用文件名
shell任务到cat
文件
使用cat
传递给ec2模块的结果.
我的剧本的示例内容.
vars: amazon_linux_ami: "ami-fb8e9292" user_data_file: "base-ami-userdata.sh" tasks: - name: user_data_contents shell: cat {{ user_data_file }} register: user_data_action - name: launch ec2-instance local_action: ... user_data: "{{ user_data_action.stdout }}"
我假设有一个更简单的方法来做到这一点,但我在搜索Ansible文档时找不到它.
您可以使用slurp模块:(感谢@mlissner建议)
vars: amazon_linux_ami: "ami-fb8e9292" user_data_file: "base-ami-userdata.sh" tasks: - name: Load data slurp: src: "{{ user_data_file }}" register: slurped_user_data - name: Decode data and store as fact # You can skip this if you want to use the right hand side directly... set_fact: user_data: "{{ slurped_user_data.content | b64decode }}"
您可以在Ansible中使用查找以获取文件的内容,例如
user_data: "{{ lookup('file', user_data_file) }}"
警告:此查找将与本地文件一起使用,而不是远程文件.
以下是文档中的完整示例:
- hosts: all vars: contents: "{{ lookup('file', '/etc/foo.txt') }}" tasks: - debug: msg="the value of foo.txt is {{ contents }}"
您可以使用fetch模块将文件从远程主机复制到本地,并使用查找模块读取已获取文件的内容.