2017-06-19 127 views
3

我們有許多Ansible角色的私人git回購。回購主機有所不同,從站點到站點,例如:我可以在ansible-galaxy和requirements.yml中使用變量替換嗎?

  • 站點1使用https://gitforsite1.ourdomain.com
  • 站點2使用https://gitforsite2.ourdomain.com

我要的是有一個單一requirements.yml文件,並替換正確的混帳回購協議。我能做到這一點的方法之一是有一個bash腳本設置環境變量:

#!/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 

和則替換requirements.yml這個值:

--- 

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

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

這種方法提供:ERROR! Unable to load data from the requirements file提示文件結構不正確。 (這可能是該方法的工作原理和我的語法錯誤。)

任何方法,讓我設置一個變量(環境,命令行,無論)是好的。或者,如果不支持,我是否需要在運行時重寫requirements.yml文件,也許使用sed

編輯1: 添加了ansible-galaxy線在bash腳本摘錄上面顯示是如何被使用的requirements.yml文件。我認爲這是問題所在:ansible-galaxy未展開變量替換,無論是否包含在group_vars/all或環境中。在Python 2.7.10中使用Ansible版本2.3.1.0。

編輯2: 發現in the docs有一個server選項指向另一個星系例如,在ansible.cfg,像這樣:

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

銀河確實使用此設置,它必須成爲完整的Galaxy網絡應用程序,因爲它叫https://gitforsite1.ourdomain.com/api。所以這對我也沒有幫助。

+0

爲什麼不把'REPO_ROOT'放到不同網站庫存的'group_vars/all'文件中? – Jack

+0

Ansible的哪個版本? 1.4和更高版本,您可以使用' - src:「{{ansible_env.REPO_ROOT}}/role1.git」'。 – Deathgrip

+0

@Jack謝謝 - 好主意,但似乎'ansible-galaxy'忽略了這些(請參閱編輯以張貼)。 – ChalkBoard

回答

1

當它們以{開頭時,應引用與源相關的映射中的值。如果不是YAML解析器會嘗試解析該值作爲一個流動式的映射,而不是一個標量:

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

既然你有你的標單引號和沒有雙引號,也沒有任何反斜槓(\),我在標量周圍使用雙引號。如果標量中沒有單引號或者有反斜槓,最好使用單引號。如果您有兩種類型的報價,請使用單引號,並在的標量內加倍單引號。下面將加載同上:

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

謝謝 - 您的重新格式化讓我通過了yaml解析器錯誤(並且您是對的,兩個表單等同於相同的結果),但是變量替換不會被'ansible-galaxy'擴展(請參閱編輯以發佈)。 – ChalkBoard

0

如果你做了這種方式:

#!/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 -s ${REPO_ROOT} 

和則替換要求此值。yml:

--- 

- src: role1.git 
    name: role1 

- src: role.git 
    name: role2 
相關問題