Managing Applications and Infrastructure with Terraform-Deploying Infrastructure with Terraform-(2)Terraform for AWS-(11)Compute Part 3: User Data and Template Files

2018年10月04日


Managing Applications and Infrastructure with Terraform-Deploying Infrastructure with Terraform
2. Terraform for AWS
11. Compute Part 3: User Data and Template Files

Edit the compute/main.tf file.

#---compute/main.tf

data "aws_ami" "server_ami" {
    most_recent = true
    owners = ["amazon"]

    filter {
        name = "owner-alias"
        values = ["amazon"]
    }
    
    filter {
        name = "name"
        values = ["amzn-ami-hvm*-x86_64-gp2"]
    }
}

resource "aws_key_pair" "tf_auth" {
    key_name = var.key_name
    public_key = file(var.public_key_path)
}

data "template_file" "user-init" {
    count = 2
    template = file("${path.module}/userdata.tpl")
    
    vars = {
        firewall_subnets = element(var.subnet_ips, count.index)
    }
}

resource "aws_instance" "tf_server" {
    count = var.instance_count
    instance_type = var.instance_type
    ami = data.aws_ami.server_ami.id
    tags = {
        Name = "tf_server-${count.index +1}"
    }
    key_name = aws_key_pair.tf_auth.id
    vpc_security_group_ids = [var.security_group]
    subnet_id = element(var.subnets, count.index)
    user_data = data.template_file.user-init.*.rendered[count.index]
}

Edit the userdata.tpl file.
#!/bin/bash
yum install httpd -y
echo "Subnet for Firewall: ${firewall_subnets}" >> /var/www/html/index.html
service httpd start
chkconfig httpd on

Edit the compute/variables.tf file.
#---compute/variables.tf

variable "key_name" {
    default = "tfkey"
}

variable "public_key_path" {
    default = "/home/ec2-user/.ssh/id_rsa.pub"
}

variable "subnet_id" {
    type = list
}

variable "instance_count" {}

variable "instance_type" {}

variable "security_group" {}

variable "subnets" {}



Category: orchestration Tags: public

Upvote


Downvote