In my ansible palybook there is a task which runs a sql query saved in a jinja2 template on my database.
- hosts: "{{ hosts_list }}"
gather_facts: no
vars_files:
- vars/main.yml
- vars/my_hosts.yml
- vars/target_date.yml
tasks:
- name: generate report
community.postgresql.postgresql_copy:
login_host: '{{ db_host }}'
login_user: '{{ db_username }}'
login_password: '{{ db_password }}'
db: '{{ db_database }}'
port: '{{ db_database_port }}'
src: "{{ lookup('template', 'my_report_query.sql.j2') }}"
copy_to: /tmp/my_report.csv
options:
format: csv
delimiter: ';'
header: yes
The query is something like:
select * from mytable where date='2023-02-03';
Now, I would like to pass to the query a value of the date which is defined in my ansible playbook.
So, in case in my ansible playbook there would be a variable defined as
input_date: "2023-05-03"
saved in file playbooks/my_playbook/vars/target_date.yml
How can I edit my playbook and jinja2 template in order to pass that variable to the query?
2
Answers
As suggested by @β.εηοιτ.βε , it was sufficient to replace the hardcoded value of the date in jinja2 templates with the jinja2 "expression tags"
{{ ... }}
also, as indicated by @larsks, the query in the jinja2 template must not end with column (
;
)In Ansible, you don’t pass variables to your templates — a template has access to all variables that are currently in scope. In other words, you just need to make sure that you’ve sourced that
target_date.yml
file. For example, here we’re doing that with theinclude_vars
module:We could also read in the vars file:
By using the
-e
option on theansible-playbook
command line:By using the
vars_files
option in the play:By setting the
input_date
variable in an appropriate file in thegroup_vars
orhost_vars
directories.Etc.
Note that for your playbook to work, you’ll need to drop the
;
in your query template. With the terminal semicolon your copy task will fail with: