0
votes

I'm initiating new AWS EC2 instance using terraform main.tf for Centos AMI. I'm able to create and connect the AWS instance.

but I have below problem

  • When, I start simple python 3 based http server which is simply printing "hello world", I can't able to run python script using file function from terraform. can anyone help me how to execute. shall I use function or use resource "null_resource" "cluster" { using interpreter?
  • from the outside world, I can't able to connect the public domain:exposed port(using curl http://publicip:8080). Though I have created a security group.

Can anyone help me out...Is there any possibilities, to check in terraform that these resources are indeed created in AWS EC2 instance. like some kind of debugging log.

PS: my EC2 instance has default python2.7 installed so in main.tf I tried to install python3 using to execute python script and this python script works fine in my local.

Or is there any best approach to execute this. I'm still learning AWS using terraform.

simple-hello-world.py

from http.server import BaseHTTPRequestHandler, HTTPServer


# HTTPRequestHandler class
class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):

    # GET
    def do_GET(self):
        # Send response status code
        self.send_response(200)

        # Send headers
        self.send_header('Content-type', 'text/html')
        self.end_headers()

        # Send message back to client
        message = "Hello world!"
        # Write content as utf-8 data
        self.wfile.write(bytes(message, "utf8"))
        return


def run():
    print('starting server...')

    # Server settings
    # Choose port 8080, for port 80, which is normally used for a http server, you need root access
    server_address = ('127.0.0.1', 8081)
    httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
    print('running server...')
    httpd.serve_forever()


run()

main.tf


provider "aws" {
  region = "us-east-2"
  version = "~> 1.2.0"
}

resource "aws_instance" "hello-world" {
  ami = "ami-ef92b08a"
  instance_type = "t2.micro"

  provisioner "local-exec" {
    command = <<EOH
      sudo yum -y update
      sudo yum install -y python3.6
    EOH
  }

  user_data = "${file("${path.module}/simple-hello-world.py")}"

  tags {
    Name = "my-aws-terraform-hello-world"
  }
}

resource "aws_security_group" "allow-tcp" {
  name = "my-aws-terraform-hello-world"
  ingress {
    from_port = 8080
    to_port = 8080
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
1

1 Answers

0
votes

1 - You are uploading the script, but you are not executing it. You will have to call it just like you did to install python, using local-exec.

2 - You opened port 8080, but your application runs on 8081.