Ansible - how to concatenate file contents into a variable

How can I concatenate the contents of multiple files into a variable?

Here's the problem: I'm trying to install public keys for a user on a remote machine. Example from authorized_key documentation , which almost works:

- name: Set up authorized_keys for the deploy user authorized_key: user=deploy key="{{ item }}" with_file: - public_keys/doe-jane - public_keys/doe-john 

But in fact, I need to use exclusive=yes , so after updating all unprotected public keys are deleted.

If exclusive=yes provided, then only the last public key remains in the .ssh/authorized_keys file (also reported as an error ) ..

My current approach:

 - name: create empty temporary keys file local_action: "shell > /tmp/auth_keys" - name: concat keys to temporary file local_action: "shell echo {{ item }} >> /tmp/auth_keys" with_file: - public_keys/doe-jane - public_keys/doe-john - name: set up authorized_keys authorized_key: user=deploy key="{{ lookup('file', '/tmp/auth_keys') }}" exclusive=yes 

This works, but the first two commands always produce “modified” ones. I also think that for this there should be a more elegant solution.

So, is there a way to combine the contents of several files into a variable? Or is there a better approach overall for this task?

+5
source share
1 answer

In the first option, you are not mistaken, and then, as your comment mentions, simply using changed_when: False to admit that this is not what bothers you, the result of changing it is a valid option.

To answer the actual title of the question, you can, as indicated on GitHub the “problem” that you have associated, simply connect the queries directly in the task like this:

 - name: set up authorized_keys authorized_key: user=deploy key="{{ lookup('file', 'public_keys/doe-jane') + lookup('file', 'public_keys/doe-john')}}" exclusive=yes 

However, a cleaner option would be to use a module assembly to combine your keys.

This will change your current approach to something more:

 - name: create concatenated keys file local_action: "assemble src=roles/ssh_keys/files/ssh_keys/ dest=/tmp/ssh_keys_file" - name: set up authorized_keys authorized_key: user=deploy key="{{ lookup('file', '/tmp/ssh_keys_file' }}" exclusive=yes 

This will only be marked as changed if the destination file has completely changed, so running it again and again leaves a beautiful green wall.

It depends on your ssh keys, all of which are files in the same folder (assembly is usually used to turn conf.d directories into a single .conf file for programs that do not use conf.d style configuration), but this is probably the most reasonable way to keep them.

The advantage of this is that you can simply add / remove ssh keys from the specified folder, and it will be selected in the next playback without the need to add / remove keys explicitly defined in the task itself.

+6
source

Source: https://habr.com/ru/post/1233318/


All Articles