129

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.

TesterJeff
  • 1,626
  • 2
  • 16
  • 20

4 Answers4

144

You can use lookups in Ansible in order to get the contents of a file on local machine, 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 }}"
Tms91
  • 3,456
  • 6
  • 40
  • 74
jabclab
  • 14,786
  • 5
  • 54
  • 51
41

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 }}"
johntellsall
  • 14,394
  • 4
  • 46
  • 40
Gert van den Berg
  • 2,448
  • 31
  • 41
9

You can use fetch module to copy files from remote hosts to local, and lookup module to read the content of fetched files.

Taha Jahangir
  • 4,774
  • 2
  • 42
  • 49
  • 9
    I'm totally new to ansible, but why not use slurp for this? It seems to work on the remote to pull in the contents of a file. – mlissner Sep 15 '16 at 21:48
-1

lookup only works on localhost. If you want to retrieve variables from a variables file you made remotely use include_vars: {{ varfile }} . Contents of {{ varfile }} should be a dictionary of the form {"key":"value"}, you will find ansible gives you trouble if you include a space after the colon.

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
DR1979
  • 55
  • 3
  • 9
    This is nonsense. `include_vars` works locally on the control machine, not with files on the target. – techraf Nov 20 '17 at 08:52