繁体   English   中英

我们如何使用 Boto3 更新 aws 安全组规则

[英]How do we update aws security groups rules using Boto3

有谁知道如何使用 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.2.3.4/32',
                        'Description': 'Sec'
                    },
                    {
                        'CidrIp': '10.5.6.7/32',
                        'Description': 'Sec'
                    },
                ],
                '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 的东西或任何其他键来避免这个问题吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM