试图以某种方式解决这个问题:
deploy.yml:
- vars:
site_name: "{{ lookup('env', 'MY_SITE') }}"
hosts: "{{ site_name }}"
roles:
- { role: deploy, tags: ["release"] }
拥有group_vars文件:
mysite1:
- name: 'mysite1'
docroot: '/var/www/mysite1.com'
codebase: ''
db_host: '192.168.1.100'
db_user: 'myuser'
db_pass: 'mypass'
db_name: 'mydb'
和剧本任务文件:
---
- debug: "msg='Host site name {{ item.name }} db_host {{ item.db_host }}'"
with_items: site_name
用以下方式运行剧本:
export MY_SITE=mysite1 ; ansible-playbook -i myinventory deploy.yml -e @group_vars/sites.yml
然而这是不对的,得到:
fatal: [myhost]: FAILED! => {"failed": true, "msg": "'unicode object' has no attribute 'name'"}
当然变量" site_name"包含值" mysite1"我想从集团变量中获得mysite1的价值...... 任何人都能指出我正确的方向吗? (就我在文档中读到变量中的变量或者评估变量还不可能......) 谢谢!
答案 0 :(得分:0)
您可能需要尝试host_vars吗? 举个例子:
#tree
├── deploy-playbook.yml
├── hosts
├── host_vars
│ ├── mysite1.yml
│ └── mysite2.yml
└── roles
└── deploy
└── tasks
└── main.yml
#cat hosts
[sites]
mysite1
mysite2
#cat deploy-playbook.yml
---
- vars:
site_name: "{{ lookup('env', 'MY_SITE') }}"
hosts: "{{ site_name }}"
roles:
- { role: deploy }
#cat host_vars / mysite1.yml
---
name: 'mysite1'
db_name: 'mydb1'
test:
name: 'test_mysite1'
db_name: 'test_mydb1'
#cat host_vars / mysite2.yml
---
name: 'mysite2'
db_name: 'mydb2'
test:
name: 'test_mysite2'
db_name: 'test_mydb2'
#cat roles / deploy / tasks / main.yml
---
- debug: msg='{{ name }} - {{ test['name'] }} - {{ db_name }} - {{ test['db_name'] }}'
结果:
#export MY_SITE = mysite1; ansible-playbook -i hosts deploy-playbook.yml
PLAY [mysite1] *****************************************************************
TASK [setup] *******************************************************************
ok: [mysite1]
TASK [deploy : debug] **********************************************************
ok: [mysite1] => {
"msg": "mysite1 - test_mysite1 - mydb1 - test_mydb1"
}
PLAY RECAP *********************************************************************
mysite1 : ok=2 changed=0 unreachable=0 failed=0
#export MY_SITE = mysite2; ansible-playbook -i hosts deploy-playbook.yml
PLAY [mysite2] *****************************************************************
TASK [setup] *******************************************************************
ok: [mysite2]
TASK [deploy : debug] **********************************************************
ok: [mysite2] => {
"msg": "mysite2 - test_mysite2 - mydb2 - test_mydb2"
}
PLAY RECAP *********************************************************************
mysite2 : ok=2 changed=0 unreachable=0 failed=0