Jaeger
Jaeger

Reputation: 1754

How can I loop around an array in this situation?

I have the following variables in my playbook:

frontends:
  - domain01.fr
  - domain02.fr
  - domain03.fr
  - domain04.fr

I need to be able to write the following in a file via an Ansible playbook step:

tcp://domain01.fr:11211,tcp://domain02.fr:11211,tcp://domain03.fr:11211,tcp://domain04.fr:11211

I came up with the following solution, but I'm not pleased with it.

- name: Setting up Apache (2/2)
  lineinfile:
    path: /etc/opt/rh/rh-php56/php.ini
    regexp: '^session.save_path ='
    line: "session.save_path = 'tcp://{{ frontends | join(':11211,tcp://') }}'"

I can't hardwrite the domains inside the lineinfile method, because it depends a lot, plus there are situations where I only have 2 domains instead of 4.

Is it possible to have something like the following:

- name: Setting up Apache (2/2)
  lineinfile:
    path: /etc/opt/rh/rh-php56/php.ini
    regexp: '^session.save_path ='
    line: "session.save_path = '{% for frontend in frontends %} tcp://{% frontend %}:11211,{% endfor %}'"

Thank you in advance

Upvotes: 0

Views: 25

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

Yes. It's possible. The line below

regexp: '^session.save_path ='
line: >-
  session.save_path ={% for frontend in frontends %}
  tcp://{{ frontend }}:11211{% if not loop.last %},{% endif %}{% endfor %}

gives

session.save_path = tcp://domain01.fr:11211, tcp://domain02.fr:11211, tcp://domain03.fr:11211, tcp://domain04.fr:11211

Upvotes: 1

Related Questions