Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use variable substitution with ansible-galaxy and requirements.yml?

We have private git repos for a number of Ansible roles. The repo hosts vary from site to site, for example:

  • Site1 uses https://gitforsite1.ourdomain.com
  • Site2 uses https://gitforsite2.ourdomain.com

What I want is to have a single requirements.yml file and substitute the correct git repo. One way I could do this is to have a bash script set an environment variable:

#!/bin/bash
...
if [ "$1" = "site1" ]; then
    export REPO_ROOT="https://gitforsite1.ourdomain.com"
fi
if [ "$1" = "site2" ]; then
    export REPO_ROOT="https://gitforsite2.ourdomain.com"
fi
... error checking if the value is not site1 or site2 ...
# Then install the roles
ansible-galaxy install -f -r config/requirements.yml -p roles

and then substitute this value in requirements.yml:

---

- src: {{ lookup('env', 'REPO_ROOT') }}/role1.git
  name: role1

- src: {{ lookup('env', 'REPO_ROOT') }}/role.git
  name: role2

This approach gives: ERROR! Unable to load data from the requirements file suggesting that the file structure is incorrect. (It may be that the approach works and I've got the syntax wrong.)

Any approach that lets me set a variable (environment, command line, whatever) is fine. Alternatively, if this is not supported, do I need to rewrite the requirements.yml file at runtime, maybe using sed?

EDIT 1: Added the ansible-galaxy line in the bash script excerpt above to show how the requirements.yml file is being used. I think that this is the problem: ansible-galaxy is not expanding the variable substitutions, whether included in group_vars/all or the environment. Using Ansible version 2.3.1.0 with Python 2.7.10.

EDIT 2: Discovered in the docs there is a server option to point to another Galaxy instance, in ansible.cfg, like so:

[galaxy]  
server=https://gitforsite1.ourdomain.com

Galaxy does use this setting, but it must be a full Galaxy web app, because it calls https://gitforsite1.ourdomain.com/api. So that doesn't help me either.

like image 455
ChalkBoard Avatar asked Jun 19 '17 20:06

ChalkBoard


1 Answers

When they begin with {, you should quote the values in the mappings associated with source. If not the yaml parser will try and parse that value as a flow-style mapping instead of a scalar:

- src: "{{ lookup('env', 'REPO_ROOT') }}/role1.git"
  name: role1

Since you have single quotes in your scalar and no double quotes, nor any backslashes (\), I used double quotes around the scalar. You better use single quotes if you have no single quotes in your scalar or if you have any backslashes. If you have both types of quotes, use single quotes and double any single quotes within the scalar. The following will load the same as the above:

- src: '{{ lookup(''env'', ''REPO_ROOT'') }}/role1.git'
  name: role1
like image 183
Anthon Avatar answered Sep 27 '22 19:09

Anthon