pwe
pwe

Reputation: 127

Conditionals in Ansible with dictionary

I think I might misunderstand something in Ansible.

I want to build a role for subversion.

Here is my hosts-file:

[locaton1]
server-location1.domain.com

[location2]
server-location2.domain.com

I have a vars-file like this:

- repos_location1:
    repo1:
      reponame: project1
      repogrp: grp-project1
    repo2:
      reponame: project2
      repogrp: grp-project2
      subrepo:
        reponame: subproject2
        repogrp: grp-subproject2

- repos_location2:
    repo1:
      reponame: project3
      repogrp: grp-project3
    repo2:
      reponame: project4
      repogrp: grp-project4

Then, I have my task-file. This is just a snippet:

- name: Build configuration
  template: src=subversion.conf.j2 dest=/etc/httpd/conf.d/subversion.conf
  with_dict: ????

Now comes the clue: I want to have a when statement, like: "When the host is in [location1], use repos_location1, but use repos_location2, when in [location2].

I hope, you understand my point. Otherwise I would have to make a role svn-location1 and svn-location2.

Additional I want to have a statement in my template file, like this:

"If "subrepo" exists, do something"

Upvotes: 1

Views: 109

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56947

You would be much better of using group variables instead here.

Instead you define your variable as a generic repos and set it for each group so you have something like this:

group_vars/location1:

repos:
    repo1:
      reponame: project1
      repogrp: grp-project1
    repo2:
      reponame: project2
      repogrp: grp-project2
      subrepo:
        reponame: subproject2
        repogrp: grp-subproject2

group_vars/location2:

repos:
    repo1:
      reponame: project3
      repogrp: grp-project3
    repo2:
      reponame: project4
      repogrp: grp-project4

You can then use it like this:

- name: Build configuration
  template: src=subversion.conf.j2 dest=/etc/httpd/conf.d/subversion.conf
  with_dict: repos

I would, however, suggest that you change your new repos variable to be a list of dictionaries to allow you to more easily iterate through it and add/remove repos to the variable. So something like this instead:

repos:

    - reponame: project3
      repogrp: grp-project3

    - reponame: project4
      repogrp: grp-project4

You'd then iterate through repos with a with_items iterator.

Upvotes: 2

Related Questions