Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables for file name and file contents in lineinfile module

I am trying to read the contents of a file, store these in a variable and then insert them into another file if they don't already exist.

So, how I'm attempting to go about this is as follows:

# Create a variable that represents the path to the file that you want to read from
ssh_public_key_file: '../../jenkins_master/files/{{ hostvars[inventory_hostname]["environment"] }}/id_rsa.pub'

# Create a variable that represents the contents of this file:
ssh_public_key: "{{ lookup('file', '{{ ssh_public_key_file }}') }}"

I then use these variables in my Ansible playbook as follows:

- name: Install SSH authorized key
  lineinfile: create=yes dest=~/.ssh/authorized_keys line=" {{ ssh_public_key }}" mode=0644

However, when I try and run the playbook, I get the following error message:

could not locate file in lookup: {{ ssh_public_key_file }}

Can anyone recommend a solution or suggest what I may have done wrong?

Thanks,

Seán

like image 314
Seán Avatar asked Feb 19 '15 15:02

Seán


People also ask

What Ansible module shall we use to add content to a file?

Creating a File With Content A quicker way is to use the copy module. Even though this module is used to copy a file from the control node to the remote host, you can include the content parameter to instantly add content to an empty file. In the file, we used: copy : Engages Ansible's copy module.

What does the Lineinfile module do?

The lineinfile is one of the most powerful modules in the Ansible toolbox. Ansible lineinfile module is used to insert a line, modify, remove, and replace an existing line.

How do I create an Ansible file with contents?

One way is to create an empty file using the above method and then using the blockinfile or lineinfile module to add content to it. But an easier method is to use the Ansible copy module to create a new file with content inside. The copy module is commonly used to copy a source file to a destination file.


1 Answers

You have to change the line to:

# Create a variable that represents the contents of this file:
ssh_public_key: "{{ lookup('file', ssh_public_key_file) }}"

If you need to concatenate variables and strings you can do it like this:

# Example with two variables
ssh_public_key: "{{ lookup('file', var_1+var_2) }}"

# Example with string and variable
ssh_public_key: "{{ lookup('file', '~/config/'+var_1) }}"

. .

like image 125
ByteNudger Avatar answered Sep 21 '22 19:09

ByteNudger