【问题标题】:How do we update aws security groups rules using Boto3我们如何使用 Boto3 更新 aws 安全组规则
【发布时间】:2021-11-05 04:50:06
【问题描述】:

有人知道如何使用 python boto3 更新 AWS 安全组规则吗?

我们在我的所有帐户中都有一个名为 office_sg 的安全组,例如,我需要用新的描述更新其中一条规则。

脚本如下;

import datetime
import boto3
import json
import itertools

AWS_Region='me-south-1'

session = boto3.Session(region_name=AWS_Region, profile_name='xxxxx')
org_client = session.client('organizations')
sts_client = session.client('sts')

awsaccount_list = [['123456465561', 'dev'], ['093556464361', 'staging']]

for aws_account in awsaccount_list:
    awsaccount = sts_client.assume_role(
        RoleArn=f'arn:aws:iam::{aws_account[0]}:role/SwitchRole',
        RoleSessionName='awsaccount_session'
    )

    ACCESS_KEY = awsaccount['Credentials']['AccessKeyId']
    SECRET_KEY = awsaccount['Credentials']['SecretAccessKey']
    SESSION_TOKEN = awsaccount['Credentials']['SessionToken']

    ec2_client = boto3.client('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, aws_session_token=SESSION_TOKEN, region_name=AWS_Region)
    describe_sg = ec2_client.describe_security_groups(
        Filters=[
            {
                'Name': 'group-name',
                'Values': [
                    '*office_sg*',
                ]
            },
        ],
    )

    for sg_res in describe_sg['SecurityGroups']:
        gpname = sg_res.get('GroupName')
        gpid = sg_res.get('GroupId')


        raw = [
            aws_account[1],
            gpname
        ]
        print(raw)

    sg_add_ing = ec2_client.authorize_security_group_ingress(
        GroupId=gpid,
        IpPermissions=[
            {
                'FromPort': 0,
                'IpProtocol': '-1',
                'IpRanges': [
                    {
                        'CidrIp': '10.1.8.12/32',
                        'Description': 'Scanner'
                    },
                    {
                        'CidrIp': '10.1.9.12/32',
                        'Description': 'Scanner'
                    },
                ],
                'ToPort': 0,
            },
            
    print(sg_add_ing)

这里出现预期错误;

    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidPermission.Duplicate) when calling the AuthorizeSecurityGroupIngress operation: the specified rule "peer: 10.1.8.12/32, ALL, ALLOW" already exists

那么我们可以使用 #overwrite 或任何其他键来避免这个问题吗?

【问题讨论】:

    标签: python amazon-web-services amazon-ec2 aws-security-group


    【解决方案1】:

    很遗憾,没有用于修改 sg 规则的 API。另请参阅https://stackoverflow.com/a/34595050/12259756 以获得有关如何处理此问题的更详细的答案。希望这可以进一步帮助您!

    【讨论】:

    • 感谢@LRutten
    猜你喜欢
    • 2016-04-11
    • 2017-08-10
    • 2018-08-25
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2020-06-19
    相关资源
    最近更新 更多