這裏是我的打法:何時填充hostvars數據以及如何訪問?
- name: Tag ec2 instances
hosts: localhost
tasks:
- name: Print Hosts
debug: var=hostvars[item]['ec2_id']
with_inventory_hostnames: all
- name: Print Hosts 2
debug: msg={{hostvars[item]['ec2_id']}}
with_inventory_hostnames: all
- name: Tag Hosts
ec2_tag:
resource: "{{ hostvars[item]['ec2_id'] }}"
region: ap-southeast-2
args:
tags: {mytag: 'myvalue'}
with_inventory_hostnames: all
任何人都可以解釋爲什麼第二個任務失敗,出現以下錯誤,第一個是成功的?如果什麼等號的右邊是未定義
...
ok: [localhost] => (item=172.31.11.37) => {
"hostvars[item]['ec2_id']": "i-xxxxxx",
"item": "172.31.11.37"
}
TASK [Print Hosts 2] ***********************************************************
fatal: [localhost]: FAILED! => {"failed": true, "msg": "'dict object' has no attribute 'ec2_id'"}
無法理解!兩個任務使用同一個對象,但第二個任務失敗。 –
感謝user2864740。我明白你的意思。將問題標題更改爲「何時填充Hostvars數據以及如何訪問?」 有關如何解決此問題的任何建議嗎? –
得到它的工作: ' - 名稱:標籤EC2實例 主機:本地主機 任務: - 名稱:打印主機 調試:VAR = HOSTVARS [項目] [ 'ec2_id'] with_inventory_hostnames:所有 寄存器:醜 # - 名稱:新的打印主機 #調試:味精= {{項目[ 「HOSTVARS [項目] [ 'ec2_id']」]}} #with_items:ugly.results - 名稱:標籤主機 ec2_tag: 狀態:目前 資源:「{{item [\」hostvars [item] ['ec2_id'] \「]}}」 region:ap-southeast-2 標籤: ShutDownAfterHours:沒有 with_items:ugly.results' –