[英]Create Aws Security Group Inbound Rule from another security group in java
I have multiple AWS Security Groups and i want to create an inbound traffic rule in 1 security group from another security group. 我有多个AWS安全组 ,我想在另一个安全组的1个安全组中创建入站流量规则。 I can do that from the AWS Console but i want to automate it using java api.
我可以从AWS控制台执行此操作,但是我想使用java api将其自动化。 How can i do it?
我该怎么做?
For simple Rules with Cidr Blocks, I have used AuthorizeSecurityGroupIngressRequest , But in this i can't find a way to achieve this.
对于带有Cidr块的简单规则,我使用了AuthorizeSecurityGroupIngressRequest ,但是在这种情况下,我找不到实现此目的的方法。
Sample Code: 样例代码:
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest =new AuthorizeSecurityGroupIngressRequest();
authorizeSecurityGroupIngressRequest.withFromPort(securityGroupIngressRequestParam.getFromPort());
authorizeSecurityGroupIngressRequest.withIpProtocol(securityGroupIngressRequestParam.getIpProtocols().getName());
authorizeSecurityGroupIngressRequest.withToPort(securityGroupIngressRequestParam.getToPort());
authorizeSecurityGroupIngressRequest.withCidrIp(securityGroupIngressRequestParam.getCidrBlock());
authorizeSecurityGroupIngressRequest.setGroupId(securityGroupIngressRequestParam.getSecurityGroupId());
amazonEc2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
After some try and error with Aws Apis, I have found the solution with works for me. 经过与Aws Apis的反复尝试,我找到了适合我的解决方案。
We can use the model IpPermission instead of setting the rule details with provides the api to add sourceSecurityGroupId. 我们可以使用模型IpPermission来代替使用提供用于添加sourceSecurityGroupId的api来设置规则详细信息。
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();
IpPermission ipPermission = new IpPermission();
ipPermission.withFromPort(securityGroupIngressRequestParam.getFromPort()).withToPort(securityGroupIngressRequestParam.getToPort())
.withIpProtocol(securityGroupIngressRequestParam.getIpProtocols().getName());
if (!StringUtil.isEmpty(securityGroupIngressRequestParam.getCidrBlock())) {
ipPermission.withIpRanges(securityGroupIngressRequestParam.getCidrBlock());
} else if (!StringUtil.isEmpty(securityGroupIngressRequestParam.getSourceSecurityGroupId())) {
UserIdGroupPair userIdGroupPairs = new UserIdGroupPair();
userIdGroupPairs.setGroupId(securityGroupIngressRequestParam.getSourceSecurityGroupId());
ipPermission.withUserIdGroupPairs(userIdGroupPairs);
} else {
// TODO throw exception
}
authorizeSecurityGroupIngressRequest.withIpPermissions(ipPermission);
authorizeSecurityGroupIngressRequest.setGroupId(securityGroupIngressRequestParam.getSecurityGroupId());
amazonEc2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.