簡體   English   中英

需要使用 ansible 劇本從 aws 帳戶中刪除未使用的彈性 IP

[英]need to delete unused elastic IP from aws account with ansible playbook

我寫了一個劇本如下:


tasks:
    
   - name: List of all EIP
     ec2_eip_info:
            region: "{{ region }}"
     register: list_of_eip
     
  - name: initiate EIP list
    set_fact:
         eip_list: [] 

   - name: List of all unused EIP
     set_fact: 
         eip_list: "{{ list_of_eip.addresses | json_query(jmesquery) }}"
     vars: 
       jmesquery: "[?instance_id== None].allocation_id"

   - name: Release IP         
     command: aws ec2 release-address --allocation-id {{ eip_list }} --region {{ region }}
     vars:
       jmesquery: "[?instance_id== None].allocation_id"

在 output 中,我在任務Release IP中遇到錯誤:

aws ec2 release-address --allocation-id [u'eipalloc-xxxxxxxxxxxxxxx'] --region us-east-1",找不到分配 ID。

我需要將分配 ID 作為eipalloc-xxxxxxxxxxxxxxx傳遞,我不知道如何解決上述問題。 另外,如果我有多個 EIP,有人能指出我如何循環的正確方向嗎?

您正在構建一個列表。 您的命令需要一個字符串元素。 您只需要傳遞該單個元素即可。 由於無論如何您都希望該列表中有多個元素,因此顯而易見的解決方案是遍歷您的列表,以便您可以以完全相同的方式管理一個或多個元素(如果列表為空,實際上也為 0,在這種情況下沒有循環迭代將發生)。

此外,無需使用 jmespath(非常適合復雜的 json 查詢,但我們不是那種情況)或設置事實來使您的劇本復雜化。

以下應滿足您的要求。 我沒有您的數據示例,也無法訪問 aws 帳戶來親自嘗試,因此它未經測試,您可能必須根據您的確切輸入數據調整rejectattr中的過濾器(如果更容易,可能切換到selectattr ) . 參見 ansible 文檔中的數據操作,jinja2 文檔中的rejectattr / selectattr

注意:對於你的下一個問題,請考慮制作一個正確的最小、完整、可驗證的示例

    - name: List of all EIP
      ec2_eip_info:
        region: "{{ region }}"
      register: list_of_eip

    - name: Release IP         
      command: aws ec2 release-address --allocation-id {{ item }} --region {{ region }}
      loop: "{{ list_of_eip.addresses | rejectattr('instance_id') | map(attribute='allocation_id') }}"

暫無
暫無

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

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