Ansible - List Amazon Web Services (AWS) Security Groups using the ec2_security_group module
by
Jeremy Canfield |
Updated: July 31 2023
| Ansible articles
If you are not familiar with modules, check out Ansible - Getting Started with Modules.
Prerequisites
- Before you can use the Ansible Amazon Web Services (AWS) modules, you will need to install the AWS CLI tool on the hosts that will be using the Ansible Amazon Web Services (AWS) modules. Check out my article on Getting Started with the Ansible Amazon Web Services (AWS) modules.
- You will also need to set your Amazon Web Services (AWS) Profile Configurations. Check out my article Set Amazon Web Services (AWS) Profile Configurations.
- The aws_s3_bucket_info requires the following packages. Check out my article Resolve "boto3 required for this module".
- botocore version 1.25.0 or higher
- boto3 version 1.22.0 or higher
- Python 3.6 or higher must be used. The ansible --version command can be used to list the version of Python being used with Ansible. If your Ansible installation is used a version lower than Python 3.6, one solution would be to install Ansible in a Python virtual environment using Python 3.6 or higher.
- The amazon.aws collection will need to be installed. Check out my article on Install a collection using the ansible-galaxy collection install command.
ec2_security_group can be used to list your Amazon Web Services (AWS) Security Groups.
- If the Security Group already exists, JSON with the details of the Security Group will be returned
- If the Security Group does not exist, the Security Group will be created
---
- name: main play
hosts: localhost
tasks:
- name: return JSON for my-security-group
amazon.aws.ec2_security_group:
name: my-security-group
description: my-security-group
state: present
register: my_security_group
- debug:
var: my_security_group
...
Something like this should be returned.
ok: [localhost] => {
"aws_ec2_security_groups": {
"changed": true,
"description": "my-security-group",
"failed": false,
"group_id": "sg-048cff9f4800618f4",
"group_name": "my-security-group",
"ip_permissions": [],
"ip_permissions_egress": [
{
"from_port": 80,
"ip_protocol": "tcp",
"ip_ranges": [
{
"cidr_ip": "0.0.0.0/0",
"description": "allow HTTP from all"
}
],
"ipv6_ranges": [],
"prefix_list_ids": [],
"to_port": 80,
"user_id_group_pairs": []
},
{
"from_port": 22,
"ip_protocol": "tcp",
"ip_ranges": [
{
"cidr_ip": "0.0.0.0/0",
"description": "allow SSH from all"
}
],
"ipv6_ranges": [],
"prefix_list_ids": [],
"to_port": 22,
"user_id_group_pairs": []
},
{
"from_port": 443,
"ip_protocol": "tcp",
"ip_ranges": [
{
"cidr_ip": "0.0.0.0/0",
"description": "allow HTTPS from all"
}
],
"ipv6_ranges": [],
"prefix_list_ids": [],
"to_port": 443,
"user_id_group_pairs": []
}
],
"owner_id": "713542074252",
"tags": {
"Name": "my-security-group"
},
"vpc_id": "vpc-01412345a335dabcd"
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at