Last active
January 8, 2019 00:10
-
-
Save lehins/56968dd1a23dbc730e8755eea5475179 to your computer and use it in GitHub Desktop.
Setting up EC2 instance and S3 bucket for cache-s3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
terraform { | |
backend "s3" { | |
encrypt = "true" | |
bucket = "my-remote-tfstate-bucket" | |
key = "my-remote-tfstate/ec2/terraform.tfstate" | |
region = "us-east-1" | |
} | |
} | |
provider "aws" { | |
region = "us-east-1" | |
} | |
resource "aws_key_pair" "my-key" { | |
key_name = "my-key" | |
public_key = "${file("/home/user/.ssh/id_rsa.pub")}" | |
} | |
resource "aws_instance" "ec2" { | |
ami = "ami-cd0f5cb6" # Ubuntu 16.04 LTS AMI | |
instance_type = "t2.medium" | |
vpc_security_group_ids = ["${aws_security_group.ec2-sg.id}"] | |
associate_public_ip_address = true | |
iam_instance_profile = "${aws_iam_instance_profile.ec2-profile.id}" | |
key_name = "my-key" | |
tags { | |
Name = "my-test-ec2" | |
} | |
user_data = <<USER_DATA | |
#!/bin/bash | |
apt-get update | |
apt-get install -y libgmp-dev | |
CACHE_S3_VERSION="v0.1.6" | |
curl -f -L https://github.com/fpco/cache-s3/releases/download/$CACHE_S3_VERSION/cache-s3-$CACHE_S3_VERSION-linux-x86_64.tar.gz | tar xz -C ~/.local/bin 'cache-s3' | |
USER_DATA | |
} | |
resource "aws_security_group" "ec2-sg" { | |
name = "ssh-sg" | |
description = "Security group that allows SSH traffic." | |
ingress { | |
cidr_blocks = ["0.0.0.0/0"] | |
from_port = 22 | |
to_port = 22 | |
protocol = "tcp" | |
} | |
egress { | |
cidr_blocks = ["0.0.0.0/0"] | |
from_port = 0 | |
to_port = 0 | |
protocol = "-1" | |
} | |
} | |
resource "aws_s3_bucket" "bucket" { | |
bucket = "fpco-dev-my-ec2-test-bucket" | |
acl = "private" | |
} | |
module "s3-full-access" { | |
source = "github.com/fpco/terraform-aws-foundation/modules/s3-full-access-policy" | |
name = "my-ec2-test-s3-access" | |
bucket_names = ["${aws_s3_bucket.bucket.id}"] | |
} | |
resource "aws_iam_role_policy_attachment" "s3-full-access-attachment" { | |
role = "${aws_iam_role.ec2-role.name}" | |
policy_arn = "${module.s3-full-access.arn}" | |
} | |
resource "aws_iam_instance_profile" "ec2-profile" { | |
name = "my-ec2-profile" | |
role = "${aws_iam_role.ec2-role.name}" | |
} | |
resource "aws_iam_role" "ec2-role" { | |
name_prefix = "my-ec2-role-" | |
assume_role_policy = <<END_POLICY | |
{ | |
"Version": "2012-10-17", | |
"Statement": [ | |
{ | |
"Action": "sts:AssumeRole", | |
"Principal": { | |
"Service": "ec2.amazonaws.com" | |
}, | |
"Effect": "Allow", | |
"Sid": "" | |
} | |
] | |
} | |
END_POLICY | |
} | |
output "instance_ip" { | |
value = "${aws_instance.ec2.public_ip}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment