Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign an array to a variable in an Ansible-Playbook

Tags:

In a playbook I got the following code:

--- - hosts: db   vars:     postgresql_ext_install_contrib: yes     postgresql_pg_hba_passwd_hosts: ['10.129.181.241/32'] ... 

I would like to replace the value of postgresql_pg_hba_passwd_hosts with all of my webservers private ips. I understand I can get the values like this in a template:

{% for host in groups['web'] %}    {{ hostvars[host]['ansible_eth1']['ipv4']['address'] }} {% endfor %} 

What is the simplest/easiest way to assign the result of this loop to a variable in a playbook? Or is there a better way to collect this information in the first place? Should I put this loop in a template?

Additional challenge: I'd have to add /32 to every entry.

like image 413
Benjamin Avatar asked Jul 17 '14 08:07

Benjamin


People also ask

How do you assign variables in Ansible?

You can define these variables in your playbooks, in your inventory, in re-usable files or roles, or at the command line. You can also create variables during a playbook run by registering the return value or values of a task as a new variable.

How do you pass variables in Ansible playbook?

The easiest way to pass Pass Variables value to Ansible Playbook in the command line is using the extra variables parameter of the “ansible-playbook” command. This is very useful to combine your Ansible Playbook with some pre-existent automation or script.


1 Answers

You can assign a list to variable by set_fact and ansible filter plugin.

Put custom filter plugin to filter_plugins directory like this:

(ansible top directory) site.yml hosts filter_plugins/     to_group_vars.py 

to_group_vars.py convert hostvars into list that selected by group.

from ansible import errors, runner import json  def to_group_vars(host_vars, groups, target = 'all'):     if type(host_vars) != runner.HostVars:         raise errors.AnsibleFilterError("|failed expects a HostVars")      if type(groups) != dict:         raise errors.AnsibleFilterError("|failed expects a Dictionary")      data = []     for host in groups[target]:         data.append(host_vars[host])     return data  class FilterModule (object):     def filters(self):         return {"to_group_vars": to_group_vars} 

Use like this:

--- - hosts: all   tasks:   - set_fact:       web_ips: "{{hostvars|to_group_vars(groups, 'web')|map(attribute='ansible_eth0.ipv4.address')|list }}"   - debug:       msg: "web ip is {{item}}/32"     with_items: web_ips 
like image 112
Yuichiro Avatar answered Oct 24 '22 22:10

Yuichiro