Skip to content

f-cappelli/ansible_custom_module

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

sg_rule_manager

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.

Files

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

What It Does

  • 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

Prerequisites

  • Python 3
  • Ansible
  • boto3 (pip install boto3)
  • AWS credentials configured (via environment variables, ~/.aws/credentials, or IAM role)

Installation

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_LIBRARY or the library key in ansible.cfg

Usage

- 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/0

Run the playbook:

ansible-playbook update_sg_rules.yml

Module Parameters

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

Return Values

Key Type Description
changed bool true if rules were successfully modified
message string Human-readable status message

Security Note

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.

AWS Permissions Required

The IAM user or role running this module needs the following EC2 permissions:

  • ec2:DescribeInstances
  • ec2:AuthorizeSecurityGroupIngress
  • ec2:RevokeSecurityGroupEgress

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages