· 9 years ago · Sep 16, 2016, 10:22 AM
1provider "aws" {
2 access_key = ""
3 secret_key = ""
4 region = "ap-southeast-2"
5}
6
7resource "aws_s3_bucket" "test-ec2-iam-role-bucket" {
8 bucket = "test-ec2-iam-role-bucket"
9 acl = "private"
10
11 tags {
12 Name = "Bucket for test-ec2-iam-role-bucket"
13 Custodian = "Johnny"
14 }
15}
16
17
18resource "aws_iam_user_policy" "test-ec2-iam-role-policy" {
19 name = "test-ec2-iam-role-policy"
20 user = "johnnytest"
21 policy = "${data.aws_iam_policy_document.test-ec2-iam-role-policy-doc.json}"
22}
23
24data "aws_iam_policy_document" "test-ec2-iam-role-policy-doc" {
25 statement {
26 sid = "AutovueETLWriteToS3Bucket"
27 effect = "Allow"
28 actions = [
29 "s3:*"
30 ]
31 resources = [
32 "arn:aws:s3:::${aws_s3_bucket.test-ec2-iam-role-bucket.bucket}"
33 ]
34 }
35}
36
37data "aws_caller_identity" "current" {}
38
39resource "aws_iam_role" "test-ec2-iam-role" {
40 name = "test-ec2-iam-role"
41 assume_role_policy = <<EOF
42{
43 "Version": "2012-10-17",
44 "Statement": [
45 {
46 "Action": "sts:AssumeRole",
47 "Principal": {
48 "Service": "ec2.amazonaws.com"
49 },
50 "Effect": "Allow",
51 "Sid": ""
52 }
53 ]
54}
55EOF
56}
57
58resource "aws_iam_instance_profile" "test-ec2-iam-role-profile" {
59 name = "test-ec2-iam-role-profile"
60 roles = ["${aws_iam_role.test-ec2-iam-role.name}"]
61}
62
63
64resource "aws_iam_policy_attachment" "test-ec2-iam-role-attachment" {
65 name = "test-ec2-iam-role-attachment"
66 roles = ["${aws_iam_role.test-ec2-iam-role.name}"]
67 policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
68}
69
70
71data "aws_ami" "test-ami" {
72 most_recent = true
73 filter {
74 name = "name"
75 values = ["amzn-ami-hvm-2016.03.3.x86_64-gp2"]
76 }
77}
78
79resource "aws_instance" "test-ec2-iam-role-instance" {
80 ami = "${data.aws_ami.test-ami.id}"
81 instance_type = "t2.micro"
82 tags {
83 Name = "test-ec2-iam-role-instance"
84 }
85 key_name = "test-ec2-iam-role-instance"
86 security_groups = ["${aws_security_group.allow_all.name}"]
87 iam_instance_profile = "${aws_iam_instance_profile.test-ec2-iam-role-profile.name}"
88}
89
90resource "aws_security_group" "allow_all" {
91 name = "allow_all"
92 description = "Allow all inbound traffic"
93
94 ingress {
95 from_port = 0
96 to_port = 65535
97 protocol = "tcp"
98 cidr_blocks = ["0.0.0.0/0"]
99 }
100 egress {
101 from_port = 0
102 to_port = 65535
103 protocol = "tcp"
104 cidr_blocks = ["0.0.0.0/0"]
105 }
106
107 tags {
108 Name = "allow_all"
109 }
110}