簡體   English   中英

使用Ansible向AWS安全組添加和刪除多個IP地址

[英]Adding and removing multiple IP address to AWS security group using Ansible

我試圖使用Ansible將IP地址添加到AWS安全組。

我想出了一個如下所示的任務語法:

- hosts: localhost
  gather_facts: False
  vars:
    ip_addresses:
      - 1.2.3.4/32
      - 2.3.4.5/32
  tasks:
    - ec2_group:
        name: security-group-name
        description: Security group description
        vpc_id: vpc-1234567
        region: us-east-1
        profile: profile-name
        purge_rules: false
        rules:
         - proto: tcp
           from_port: 123
           to_port: 123
           cidr_ip: "{{ item }}"
      with_items: ip_addresses

這並沒有完全符合我的要求,因為它基本上運行ec2_group任務多次,而不是僅僅循環規則。

如果我將purge_rules設置為true ,這也不起作用,因為它將清除每次迭代的所有現有規則,有效地刪除列表上除最后一個IP地址之外的所有規則。

我想知道是否有類似於with_items東西,我可以應用於rules屬性,為它提供一個IP地址列表,但只調用ec2_task一次?

這並沒有完全符合我的要求,因為它基本上運行ec2_group任務多次,而不是僅僅循環規則。

Ansible通過為循環中的每個項調用一次任務來實現循環,這是預期的行為。

我想知道是否有類似於with_items的東西,我可以應用於rules屬性,為它提供一個IP地址列表,但只調用ec2_task一次?

由於ec2_grouprules屬性實際上采用了一系列規則,因此您應該能夠執行以下操作:

- ec2_group:
    name: security-group-name
    description: Security group description
    vpc_id: vpc-1234567
    region: us-east-1
    profile: profile-name
    purge_rules: true
    rules:
     - proto: tcp
       from_port: 123
       to_port: 123
       cidr_ip: 1.2.3.4/32
     - proto: tcp
       from_port: 123
       to_port: 123
       cidr_ip: 2.3.4.5/32

或者,如果您想在示例中使用預定義的變量:

vars:
  my_rules:
     - proto: tcp
       from_port: 123
       to_port: 123
       cidr_ip: 1.2.3.4/32
     - proto: tcp
       from_port: 123
       to_port: 123
       cidr_ip: 2.3.4.5/32

tasks:
  - ec2_group:
      name: security-group-name
     description: Security group description
      vpc_id: vpc-1234567
      region: us-east-1
      profile: profile-name
      purge_rules: true
      rules: my_rules

您可以使用自定義過濾器插件實現所需。

在你的劇本叫的根目錄下創建目錄filter_plugins ,並在那里被稱為創建一個文件make_rules.py具有以下內容:

def make_rules(hosts, ports, proto):
    return [{"proto": proto,
             "from_port": port,
             "to_port": port,
             "cidr_ip": host} for host in hosts for port in map(int, ports.split(","))]

class FilterModule(object):
     def filters(self):
         return {'make_rules': make_rules}

然后你可以這樣做:

- hosts: localhost
  gather_facts: False
  vars:
    ip_addresses:
      - 1.2.3.4/32
      - 2.3.4.5/32
  tasks:
    - ec2_group:
        name: security-group-name
        description: Security group description
        vpc_id: vpc-1234567
        region: us-east-1
        profile: profile-name
        purge_rules: true
        rules: {{ ip_addresses | make_rules('123', 'tcp') }}

取自: https//gist.github.com/viesti/1febe79938c09cc29501

暫無
暫無

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

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