I'm trying to read all lines in a .txt file except the lines starting with two forward slashes '//' and empty lines using lookup in my yaml code, this is what my code looks like:
---
- name: playbook for API release deployment
hosts: api
become: yes
ignore_errors: true
vars:
date: "{{ lookup('pipe', 'date %Y.%m.%d-%H.%M') }}"
tasks:
- name: deploy-api | upgrade Addons using loop
command: "{{ module_install }} -u {{ item }} --stop-after-init"
args:
chdir: /opt/app/
with_items:
- "{{ lookup('file', 'addons.txt') | grep -v '^(//)' }}"
This is what the .txt file looks like:
// Comment 1
// Commment 2
// Comment 3
// Comment 4
addons 1
addons 2
addons 3
Ansible throws me an error:
fatal: FAILED! => {"msg": "template error while templating string: expected token 'end of print statement', got 'string'. String: {{ lookup('file', 'addons.txt') | grep -v '^(//)' }}"}
I'm not sure on how to do this, how should I escape those lines starting with '//' and empty lines?
CodePudding user response:
Consider rethinking your code. Instead of addons.txt
just use a proper Ansible array variable.
// inventory/all/all.yml
# comment
addons:
- addons 1
- addons 2
- addons 3
// playbook.yml
with_items: '{{ addons }}'
Anyway, untested, something like the following can make you started:
with_items: "{{
lookup('file', 'addons.txt').splitlines() |
reject('match', '^//') |
join('\n')
}}"
CodePudding user response:
Q: "How should I escape lines starting with '//' and empty lines?"
A: reject matching lines. See Testing strings. For example,
lines: "{{ lookup('file', 'addons.txt').splitlines()|
reject('regex', '^//')|
reject('regex', '^$') }}"
gives
lines:
- addons 1
- addons 2
- addons 3
Example of a complete playbook for testing
- hosts: localhost
vars:
module_install: install
lines: "{{ lookup('file', 'addons.txt').splitlines()|
reject('regex', '^//')|
reject('regex', '^$') }}"
tasks:
- debug:
var: lines
- debug:
msg: "{{ module_install }} -u {{ item }} --stop-after-init"
loop: "{{ lines }}"
gives
PLAY [localhost] *****************************************************************************
TASK [debug] *********************************************************************************
ok: [localhost] =>
lines:
- addons 1
- addons 2
- addons 3
TASK [debug] *********************************************************************************
ok: [localhost] => (item=addons 1) =>
msg: install -u addons 1 --stop-after-init
ok: [localhost] => (item=addons 2) =>
msg: install -u addons 2 --stop-after-init
ok: [localhost] => (item=addons 3) =>
msg: install -u addons 3 --stop-after-init
PLAY RECAP ***********************************************************************************
localhost: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0