2
votes

I am attempting to dynamically reference j2 templates pulled from artifactory. The following code works:

  - name: Confiure the sqoop templates
    template: src="{{ item }}" dest="{{ local_root }}/{{ FEED_NAME }}/{{ FEED_SCHEMA }}/sqoopgen_jobs/{{ item|replace(\"/tmp/tardis/\", \"\") }}" mode=0744
    with_fileglob:
    - "/tmp/{{ FEED_NAME }}/*.j2"

The following does not:

  - name: Confiure the sqoop templates
    template: src="{{ item }}" dest="{{ local_root }}/{{ FEED_NAME }}/{{ FEED_SCHEMA }}/sqoopgen_jobs/{{ item|replace(\"/tmp/{{ FEED_NAME }}/\", \"\") }}" mode=0744
    with_fileglob:
    - "/tmp/{{ FEED_NAME }}/*.j2"

Failing with error:

failed: [host_ip] => (item=/tmp/tardis/forecast.j2) => {"changed": true, "failed": true, "invocation": {"module_args": {"backup": false, "content": null, "delimiter": null, "dest": "/path/tardis/tardis/sqoopgen_jobs//tmp/tardis/forecast.j2", "directory_mode": null, "follow": true, "force": true, "group": null, "mode": "0744", "original_basename": "forecast.j2", "owner": null, "regexp": null, "remote_src": null, "selevel": null, "serole": null, "setype": null, "seuser": null, "src": "/home/jenkins/.ansible/tmp/ansible-tmp-1457719702.84-279730849155325/source", "validate": null}}, "item": "/tmp/tardis/forecast.j2", "msg": "Destination directory /path/tardis/tardis/sqoopgen_jobs//tmp/tardis does not exist"}

I'm reading this as a case of ansible not expanding a variable within a variable: such as here

What is the best approach to take in this situation? I want to keep the playbook as generic as possible.

ansible 2.0.1.0

thanks

1

1 Answers

1
votes

You can not nest Jinja expressions like so:

{{ item|replace("/tmp/{{ FEED_NAME }}/", "") }}

What you want is to concatenate strings.

{{ item|replace("/tmp/" ~ FEED_NAME ~ "/", "") }}

See "Other Operators" in the Jinja2 docs:

~

Converts all operands into strings and concatenates them.

{{ "Hello " ~ name ~ "!" }} would return (assuming name is set to 'John') Hello John!.

  - name: Configure the sqoop templates
    template:
      src: "{{ item }}"
      dest: "{{ local_root }}/{{ FEED_NAME }}/{{ FEED_SCHEMA }}/sqoopgen_jobs/{{ item|replace('/tmp/' ~ FEED_NAME ~ '/', '') }}"
      mode: 0744
    with_fileglob:
      - "/tmp/{{ FEED_NAME }}/*.j2"