簡體   English   中英

我可以在 ansible-galaxy 和 requirements.yml 中使用變量替換嗎?

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

我們有許多 Ansible 角色的私有 git 存儲庫。 存儲庫主機因站點而異,例如:

  • Site1 使用https://gitforsite1.ourdomain.com
  • Site2 使用https://gitforsite2.ourdomain.com

我想要的是有一個requirements.yml文件並替換正確的 git repo。 我可以這樣做的一種方法是讓 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 ERROR! Unable to load data from the requirements file提示文件結構不正確。 (可能是這種方法有效,而我的語法錯誤。)

任何讓我設置變量(環境、命令行等)的方法都可以。 或者,如果這不受支持,我是否需要在運行時重寫requirements.yml文件,也許使用sed

編輯 1:在上面的 bash 腳本摘錄中添加了ansible-galaxy行以顯示requirements.yml文件的使用方式。 我認為這是問題所在: ansible-galaxy沒有擴展變量替換,無論是包含在group_vars/all還是包含在環境中。 在 Python 2.7.10 中使用 Ansible 版本 2.3.1.0。

編輯 2: 在文檔中發現有一個指向另一個 Galaxy 實例的server選項,在ansible.cfg ,如下所示:

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

Galaxy確實使用此設置,它必須是完整的 Galaxy Web 應用程序,因為它調用https://gitforsite1.ourdomain.com/api 所以這對我也沒有幫助。

當它們以{開頭時,您應該引用與 source 關聯的映射中的值。 如果不是,yaml 解析器將嘗試將該值解析為流樣式映射而不是標量:

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

由於您的標量中有單引號且沒有雙引號,也沒有任何反斜杠 ( \\ ),因此我在標量周圍使用了雙引號。 如果標量中沒有單引號或有任何反斜杠,則最好使用單引號。 如果您有這兩種類型的引號,使用單引號和標量雙任何單引號。 以下將加載與上述相同的內容:

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

如果你這樣做會怎么樣:

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

然后在 requirements.yml 中替換這個值:

---

- src: role1.git
  name: role1

- src: role.git
  name: role2

我有一個解決方法。 如果您不介意執行時間,請參考:

- name: geerlingguy.docker
- name: geerlingguy.docker
  src: https://my-private-server-1/path/is/not/important/docker.tar.gz
- name: geerlingguy.docker
  src: https://my-private-server-2/path/is/not/important/docker.tar.gz

並執行 ansible-galaxy 像:

$ ansible-galaxy install --ignore-errors -r requirements.git-cache.yml

這個例子實現了如果我們有互聯網中斷,它將安裝下一個相同的角色。

一旦安裝了同一個角色之一,同一個角色的安裝將被跳過。

當然,您可以根據需要更改角色的順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM