Seán
Seán

Reputation: 663

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

Upvotes: 23

Views: 35299

Answers (2)

ByteNudger
ByteNudger

Reputation: 1561

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) }}"

. .

Upvotes: 37

Bruce P
Bruce P

Reputation: 20759

First I would make sure that your ssh_public_key_file variable is set up properly. If you add a task like the following what does it show?

- name: display variable
  debug: var=ssh_public_key_file

If the output looks something like this then the variable isn't defined properly (eg. the "environment" fact doesn't exist for the host):

ok: [localhost] => {
    "ssh_public_key_file": "../../jenkins_master/files/{{ hostvars[inventory_hostname][\"environment\"] }}/id_rsa.pub"
}

However if everything is defined properly then your output should show the variables replaced with their correct values:

ok: [localhost] => {
    "ssh_public_key_file": "../../jenkins_master/files/foo/id_rsa.pub"
}

Once you've verified that then I would do the same thing with your ssh_public_key variable. Just output its value using the debug module. It should display as the contents of the public key file.

One other thing I would strongly suggest is to avoid using lineinfile altogether. Since you're working with SSH keys I would recommend you use the authorized_key module instead. It's a much cleaner way of managing authorized_keys files.

Upvotes: 2

Related Questions