一千萬個為什麽

搜索

如何從ansible playbook變量中獲取dict鍵?



以下是欲望輸出:

domain.com is in gh4.allserevers.com

想法是在playbook中傳遞域名,即 domain.com ,playbook將查找其 A記錄,然後根據預定義變量進行檢查。如果在變量中找到ip,則它將顯示相應的鍵。

這是我的ansible-playbook角色:

角色/測試/任務/ main.yml </強>

    ---
    - name: Simple A record (IPV4 address) lookup for domain.com
      set_fact:
         IP: "{{ lookup('dig', 'domain.com.')}}"
      register: output
      tags: test

    - name: checking if ip belongs to gh4
      debug:
        msg: "domain.com is in gh4"
      when:
        - IP in hosts.gh4
      tags: test

角色/測試/瓦爾/ main.yml </強>

    ---
    hosts:
      gh4: [127.0.0.1,127.0.0.2,127.0.0.3,127.0.0.4,127.0.0.5]
      gh5: [127.0.0.7,127.0.0.8]
      gh6: [127.0.0.10,127.0.0.11,127.0.0.12]

轉載註明原文: 如何從ansible playbook變量中獲取dict鍵?

一共有 1 個回答:

如果我正確理解您的問題,您希望通過域名來查找可能是物理位置或數據中心的內容。我希望這對你有所幫助!

角色/測試/瓦爾/ main.yml </強>

---
domains:
  gh4: [127.0.0.1,127.0.0.2,127.0.0.3,127.0.0.4,127.0.0.5]
  gh5: [127.0.0.7,127.0.0.8]
  gh6: [127.0.0.10,127.0.0.11,127.0.0.12]

角色/測試/任務/ main.yml </強>

---
# Make sure we have a domain passed in
- name: Ensure domain is defined
  assert: { that: domain is defined }

# Obtain the IP
- name: Simple A record (IPV4 address) lookup for {{domain}}
  set_fact:
      IP: "{{ lookup('dig', '+short', '{{domain}}')}}"
  register: output
  tags: test

# Check if the IP belongs to any location
- name: Checking location of IP
  set_fact:
    domain_location: "{{item}}"
  when:
     - IP in domains[item]
  with_items: "{{domains}}"

- debug:
    msg: "domain.com is in gh4.allserevers.com{{domain_location}}"
  when: domain_location is defined

Example Run With domain.com pointing to 127.0.0.12

[email protected]:/mnt/c/ansible/roles# ansible-playbook ../playbooks/test.yml  -e domain=domain.com
PLAY [127.0.0.1] ****************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************
ok: [localhost]

TASK [test : Ensure domain is defined] ******************************************************************************
ok: [localhost] => {
    "changed": false,
    "msg": "All assertions passed"
}

TASK [test : Simple A record (IPV4 address) lookup for domain.com] **************************************************
ok: [localhost]

TASK [test : Checking location of IP] *******************************************************************************
skipping: [localhost] => (item=gh4)
skipping: [localhost] => (item=gh5)
ok: [localhost] => (item=gh6)

TASK [test : debug] *************************************************************************************************
ok: [localhost] => {
    "msg": "domain.com is in gh6.allserevers.com"
}

PLAY RECAP **********************************************************************************************************
localhost                  : ok=5    changed=0    unreachable=0    failed=0