How to create AWS AMI from created instance using terraform?

admin

Administrator
Staff member
I am setting up an aws instance with wordpress installation and want to create an AMI using created instance. Below I attach my code.

Code:
provider "aws" {

    region = "${var.region}"
    access_key = "${var.access_key}"
    secret_key = "${var.secret_key}"
}

resource  "aws_instance" "test-wordpress" {

    ami = "${var.image_id}"
    instance_type = "${var.instance_type}"
    key_name = "test-web"
    #associate_public_ip_address = yes

    user_data = <<-EOF

      #!/bin/bash

      sudo yum update -y
      sudo amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2
      sudo yum install -y httpd mariadb-server
      cd /var/www/html
      sudo echo "healthy" > healthy.html
      sudo wget https://wordpress.org/latest.tar.gz
      sudo tar -xzf latest.tar.gz
      sudo cp -r wordpress/* /var/www/html/
      sudo rm -rf wordpress
      sudo rm -rf latest.tar.gz
      sudo chmod -R 755 wp-content
      sudo chown -R apache:apache wp-content
      sudo service httpd start
      sudo chkconfig httpd on

      EOF


    tags = {
      Name = "test-Wordpress-Server"
    }
} 


resource  "aws_ami_from_instance" "test-wordpress-ami" {
    name               = "test-wordpress-ami"
    source_instance_id = "${aws_instance.test-wordpress.id}"

  depends_on = [
      aws_instance.test-wordpress,
      ]

  tags = {
      Name = "test-wordpress-ami"
  }

}

AMI will be created but When I use that AMI to create an another instance wordpress installation not in there. How can I solve this issue?