简体   繁体   English

使用 Boto3 修改给定 EC2 安全组的规则

[英]Modifying rules for a given EC2 security group with Boto3

I have recently been working on programatically adding and removing ingress rules to security groups on my EC2 server.我最近一直致力于以编程方式向我的 EC2 服务器上的安全组添加和删除入口规则。 However, I now seem to have hit a bit of a wall.但是,我现在似乎有点碰壁了。

I would like to be able to modify existing rules through a python script, but I haven't been able to find any guidance on the Boto3 docs.我希望能够通过 python 脚本修改现有规则,但我无法在 Boto3 文档上找到任何指导。

Is there any way in which this can be done?有什么办法可以做到这一点?

Thanks谢谢

Seems like there are no way to modify security group rule. 好像没有办法修改安全组规则。 You have to delete the old one: 你必须删除旧的:

security_group.revoke_ingress(IpProtocol="tcp", CidrIp="0.0.0.0/0", FromPort=3306, ToPort=3306)

and add the new one: 并添加新的:

security_group.authorize_ingress(IpProtocol="tcp",CidrIp="0.0.0.0/0",FromPort=3306,ToPort=3306)

Hope it help. 希望它有所帮助。

AWS has added new API( modify_security_group_rules ) wherein security group rule can be modified. AWS 添加了新的 API ( modify_security_group_rules ),其中可以修改安全组规则。 Below code for reference:以下代码供参考:

import boto3
client = boto3.client('ec2')
sg_rules_list = [{'SecurityGroupRuleId': 'sgr-07de36a0521f39c8b',
                  'SecurityGroupRule': {
                      'IpProtocol': 'tcp',
                      'FromPort': 22,
                      'ToPort': 22,
                      'CidrIpv4': '3.3.3.3/32',
                      'Description': 'added ssh port'
                  }
                  }
                 ]
response = client.modify_security_group_rules(GroupId='sg-00f3b9232325b20fb',
                                              SecurityGroupRules=sg_rules_list)

More details on this on AWS blog: Easily Manage Security Group Rules with the New Security Group Rule ID AWS 博客上的更多详细信息: 使用新的安全组规则 ID 轻松管理安全组规则

See Boto3:SecurityGroup 请参阅Boto3:SecurityGroup

There is no API to modify a rule in SG. 没有API来修改SG中的规则。 You have to revoke the rule first and then add the rule with the modified parameters using authorize. 您必须先撤消规则,然后使用authorize添加带有修改参数的规则。 The link also has code snippets. 该链接还包含代码段。

  • authorize_egress() authorize_egress()
  • authorize_ingress() authorize_ingress()
  • revoke_egress() revoke_egress()
  • revoke_ingress() revoke_ingress()

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

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