Nico
Nico

Reputation: 13

Ansible - Write variable to config file

We have some redis configurations that only differs on port and maxmemory settings, so I'm looking for a way to write a 'base' config file for redis and then replace the port and maxmemory variables.

Can I do that with Ansible?

Upvotes: 0

Views: 5250

Answers (2)

Alfwed
Alfwed

Reputation: 3282

The best way i've found to do this (and i use the same technique everywhere) is to create a role redis with a default vars file and then override the vars when you call the role.

So in roles/redis/default/main.yml :

redis_bind: 127.0.0.1
redis_memory: 2GB
redis_port: 1337

And in your playbook :

- name: Provision redis node
  hosts: redis1

  roles:
    - redis:
      redis_port: 9999
      redis_memory: 4GB

- name: Provision redis node
  hosts: redis2

  roles:
    - redis:
      redis_port: 8888
      redis_memory: 8GB

Upvotes: -1

techraf
techraf

Reputation: 68609

For such operations usually lineinfile module works best; for example:

- name: Ensure maxmemory is set to 2 MB
  lineinfile:
    dest: /path/to/redis.conf
    regexp: maxmemory
    line: maxmemory 2mb

Or change multiple lines in one task with with_items:

- name: Ensure Redis parameters are configured
  lineinfile:
    dest: /path/to/redis.conf
    regexp: "{{ item.line_to_match }}"
    line: "{{ item.line_to_configure }}"
  with_items:
    - { line_to_match: "line_to_match", line_to_configure: "maxmemory 2mb" }
    - { line_to_match: "port", line_to_configure: "port 4096" }

Or if you want to create a base config, write it in Jinja2 and use a template module:

vars:
  redis_maxmemory: 2mb
  redis_port: 4096

tasks:
  - name: Ensure Redis is configured
    template:
      src: redis.conf.j2
      dest: /path/to/redis.conf

with redis.conf.j2 containing:

maxmemory {{ redis_maxmemory }}
port {{ redis_port }}

Upvotes: 3

Related Questions