Skip to content

Instantly share code, notes, and snippets.

@JohnnyNiu
Created September 16, 2016 07:17
Show Gist options
  • Save JohnnyNiu/c9b9b238c4287d7ef854e0b482fe5de5 to your computer and use it in GitHub Desktop.
Save JohnnyNiu/c9b9b238c4287d7ef854e0b482fe5de5 to your computer and use it in GitHub Desktop.
instance_profile_example.tf
provider "aws" {
access_key = ""
secret_key = ""
region = "ap-southeast-2"
}
resource "aws_s3_bucket" "test-ec2-iam-role-bucket" {
bucket = "test-ec2-iam-role-bucket"
acl = "private"
tags {
Name = "Bucket for test-ec2-iam-role-bucket"
Custodian = "Johnny"
}
}
resource "aws_iam_user_policy" "test-ec2-iam-role-policy" {
name = "test-ec2-iam-role-policy"
user = "johnnytest"
policy = "${data.aws_iam_policy_document.test-ec2-iam-role-policy-doc.json}"
}
data "aws_iam_policy_document" "test-ec2-iam-role-policy-doc" {
statement {
sid = "AutovueETLWriteToS3Bucket"
effect = "Allow"
actions = [
"s3:*"
]
resources = [
"arn:aws:s3:::${aws_s3_bucket.test-ec2-iam-role-bucket.bucket}"
]
}
}
data "aws_caller_identity" "current" {}
resource "aws_iam_role" "test-ec2-iam-role" {
name = "test-ec2-iam-role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_instance_profile" "test-ec2-iam-role-profile" {
name = "test-ec2-iam-role-profile"
roles = ["${aws_iam_role.test-ec2-iam-role.name}"]
}
resource "aws_iam_policy_attachment" "test-ec2-iam-role-attachment" {
name = "test-ec2-iam-role-attachment"
roles = ["${aws_iam_role.test-ec2-iam-role.name}"]
policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
}
data "aws_ami" "test-ami" {
most_recent = true
filter {
name = "name"
values = ["amzn-ami-hvm-2016.03.3.x86_64-gp2"]
}
}
resource "aws_instance" "test-ec2-iam-role-instance" {
ami = "${data.aws_ami.test-ami.id}"
instance_type = "t2.micro"
tags {
Name = "test-ec2-iam-role-instance"
}
key_name = "test-ec2-iam-role-instance"
security_groups = ["${aws_security_group.allow_all.name}"]
iam_instance_profile = "${aws_iam_instance_profile.test-ec2-iam-role-profile.name}"
}
resource "aws_security_group" "allow_all" {
name = "allow_all"
description = "Allow all inbound traffic"
ingress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags {
Name = "allow_all"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment