An Ansible custom module for managing AWS EC2 Security Group rules. Given an EC2 instance ID, it automatically looks up the associated security group and applies ingress/egress rule changes in a single task.
| File | Description |
|---|---|
sg_rule_manager.py |
Custom Ansible module that interfaces with the AWS EC2 API via boto3 |
update_sg_rules.yml |
Example Ansible playbook demonstrating module usage |
- Looks up the security group attached to a given EC2 instance
- Adds a specified ingress rule to that security group
- Removes a specified egress rule from that security group
- Python 3
- Ansible
- boto3 (
pip install boto3) - AWS credentials configured (via environment variables,
~/.aws/credentials, or IAM role)
Place sg_rule_manager.py in one of the following locations so Ansible can find it:
- A
library/directory adjacent to your playbook - A path listed in
ANSIBLE_LIBRARYor thelibrarykey inansible.cfg
- name: Update Security Group Rules
hosts: localhost
tasks:
- name: Add ingress rule and remove egress rule
sg_rule_manager:
instance_id: i-1234567890abcdef0
ingress_rule:
IpProtocol: tcp
FromPort: 22
ToPort: 22
IpRanges:
- CidrIp: 0.0.0.0/0
egress_rule:
IpProtocol: tcp
FromPort: 80
ToPort: 80
IpRanges:
- CidrIp: 0.0.0.0/0Run the playbook:
ansible-playbook update_sg_rules.yml| Parameter | Type | Required | Description |
|---|---|---|---|
instance_id |
string | Yes | The EC2 instance ID whose security group will be modified |
ingress_rule |
dict | Yes | An inbound rule to add, in AWS IpPermissions format |
egress_rule |
dict | Yes | An outbound rule to remove, in AWS IpPermissions format |
The ingress_rule and egress_rule dicts follow the AWS IpPermissions structure, for example:
IpProtocol: tcp
FromPort: 22
ToPort: 22
IpRanges:
- CidrIp: 10.0.0.0/8| Key | Type | Description |
|---|---|---|
changed |
bool | true if rules were successfully modified |
message |
string | Human-readable status message |
The example playbook uses 0.0.0.0/0 (open to all IPs) for demonstration purposes. In production, restrict CIDR ranges to only the IPs that require access.
The IAM user or role running this module needs the following EC2 permissions:
ec2:DescribeInstancesec2:AuthorizeSecurityGroupIngressec2:RevokeSecurityGroupEgress