Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Set variable to file content

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.

  1. Var with the filename
  2. shell task to cat the file
  3. use the result of the cat to pass to the ec2 module.

Example contents of my playbook.

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.

like image 901
TesterJeff Avatar asked Jun 02 '14 21:06

TesterJeff


People also ask

How do I read Ansible file content?

You can use lookups in Ansible in order to get the contents of a file, e.g. Caveat: This lookup will work with local files, not remote files. Note that lookup runs locally, while the cat command in @TesterJeff's example is running on the remote machine.


2 Answers

You can use lookups in Ansible in order to get the contents of a file, e.g.

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:

- hosts: all   vars:      contents: "{{ lookup('file', '/etc/foo.txt') }}"   tasks:      - debug: msg="the value of foo.txt is {{ contents }}" 
like image 93
jabclab Avatar answered Sep 21 '22 08:09

jabclab


You can use the slurp module to fetch a file from the remote host: (Thanks to @mlissner for suggesting it)

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 }}" 
like image 26
Gert van den Berg Avatar answered Sep 24 '22 08:09

Gert van den Berg