Using AWS security groups with Terraform

Amazon's security groups are similar to traditional firewalls, with ingress (incoming traffic) and egress (outgoing traffic) rules applied to EC2 instances. Those rules can be updated on-demand. We'll create an initial security group allowing ingress Secure Shell (SSH) traffic only for our own IP address, while allowing all outgoing traffic.

Getting ready

To step through this recipe, you will need the following:

  • A working Terraform installation
  • An AWS provider configured in Terraform (refer to the previous recipe)
  • An Internet connection

How to do it…

The resource we're using is called aws_security_group. Here's the basic structure:

resource "aws_security_group" "base_security_group" {
  name        = "base_security_group"
  description = "Base Security Group"

  ingress { }

  egress { }

}

We know we want to allow inbound TCP/22 for SSH only for our own IP (replace 1.2.3.4/32 with yours!), and allow everything outbound. Here's how it looks:

ingress {
  from_port   = 22
  to_port     = 22
  protocol    = "tcp"
  cidr_blocks = ["1.2.3.4/32"]
 }

egress {
  from_port   = 0
  to_port     = 0
  protocol    = "-1"
  cidr_blocks = ["0.0.0.0/0"]
}

You can add a name tag for easier reference later:

tags {
  Name = "base_security_group"
}

Apply this and you're good to go:

$ terraform apply
aws_security_group.base_security_group: Creating...
[…]
aws_security_group.base_security_group: Creation complete

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

You can see your newly created security group by logging into the AWS Console and navigating to EC2 Dashboard | Network & Security | Security Groups:

How to do it…

Another way of accessing the same AWS Console information is through the AWS command line:

$ aws ec2 describe-security-groups --group-names base_security_group
{...}

There's more…

We can achieve the same result using Ansible. Here's the equivalent of what we just did with Terraform in this recipe:

---
  - name: base security group
    ec2_group:
      name: base_security_group
      description: Base Security Group
      rules:
        - proto: tcp
          from_port: 22
          to_port: 22
          cidr_ip: 1.2.3.4/32
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.252.56