dutsnekcirf
dutsnekcirf

Reputation: 273

Create a new list from an existing list in Ansible

This has got to be a simple question but I can't seem to find the answer anywhere.

I have the following list:

yum_repo_ip_addrs: ['172.16.130.4', '172.16.130.1']

I want to dynamically create a list called yum_baseurls where I copy in these values into the list along with the rest of the url. The list should ultimately look like this when run successfully:

yum_baseurls:
  - "http://172.16.130.4/repos/elrepo-8-x86_64"
  - "http://172.16.130.1/repos/elrepo-8-x86_64"

Instead, I'm finding that after the first iteration of my loop it's pasting in the variables literally.

Here's my playbook:

---

- name: Print the list of baseurl IP addresses.
  debug:
    msg: "{{ yum_repo_ip_addrs }}"

- name: Create the list of baseurls.
  set_fact:
    yum_baseurls: "{{ yum_baseurls + ['http://{{ item }}/repos/elrepo-{{ ansible_distribution_major_version }}-{{ ansible_userspace_architecture }}'] }}"
  with_items:
    - "{{ yum_repo_ip_addrs }}"

- name: print the list of baseurls.
  debug:
    msg: "{{ yum_baseurls }}"

And here's the output I get when I run it:

TASK [yum : Print the list of baseurl IP addresses.] ***************************************************************************************
ok: [ansibletarget3.jnk.sys] => {
    "msg": [
        "172.16.130.4", 
        "172.16.130.1"
    ]
}

TASK [yum : Create the list of baseurls.] **************************************************************************************************
ok: [ansibletarget3.jnk.sys] => (item=172.16.130.4)
ok: [ansibletarget3.jnk.sys] => (item=172.16.130.1)

TASK [yum : print the list of baseurls.] ***************************************************************************************************
ok: [ansibletarget3.jnk.sys] => {
    "msg": [
        "http://172.16.130.1/repos/elrepo-8-x86_64", 
        "http://{{ item }}/repos/elrepo-{{ ansible_distribution_major_version }}-{{ ansible_userspace_architecture }}"
    ]
}

Is there a better way to generate my list?

Upvotes: 1

Views: 1753

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68044

I'd remove it from the code and put it somewhere into the vars, e.g.

yum_repo_ip_addrs: [172.16.130.4, 172.16.130.1]
version: 8
architecture: x86_64
yum_baseurls:
  {% filter from_yaml %}
  {% for ip in yum_repo_ip_addrs %}
  - http://{{ ip }}/repos/elrepo-{{ version }}-{{ architecture }}
  {% endfor %}
  {% endfilter %}

Upvotes: 2

Related Questions