Question:
I’m using the ec2 module with ansible-playbook
I want to set a variable to the contents of a file. Here’s how I’m currently doing it.
- Var with the filename
- shell task to
cat
the file - use the result of the
cat
to pass to the ec2 module.
Example contents of my playbook.
1 2 3 4 5 6 7 8 9 10 11 12 |
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 }}" |
I assume there’s a much easier way to do this, but I couldn’t find it while searching Ansible docs.
Answer:
You can use lookups in Ansible in order to get the contents of a file, e.g.
1 2 |
user_data: "{{ lookup('file', user_data_file) }}" |
Caveat: This lookup will work with local files, not remote files.
Here’s a complete example from the docs:
1 2 3 4 5 6 |
- hosts: all vars: contents: "{{ lookup('file', '/etc/foo.txt') }}" tasks: - debug: msg="the value of foo.txt is {{ contents }}" |