Skip to content

Instantly share code, notes, and snippets.

@lehins lehins/cache-s3-ec2.tf
Last active Jan 8, 2019

Embed
What would you like to do?
Setting up EC2 instance and S3 bucket for cache-s3
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
You can’t perform that action at this time.