Chris F
Chris F

Reputation: 16803

In terraform, how can I pull a Docker image on the target?

Terraform v0.12.x

I'm creating an AWS EC2 instance with the aws_instance resource, and I want to pull a Docker image inside the target (I have it set up with the correct AWS credentials). I see the docker_image resource, but that pulls the image on my laptop and not on the target.

How can I pull a docker image on the target? I know I can use user_data, but is there another way?

Thanks.

Upvotes: 2

Views: 2619

Answers (1)

Amit Baranes
Amit Baranes

Reputation: 8142

This is possible, the following example is based on this repo.

main.tf -

provider "aws" {
    region = "ap-southeast-1"
}

# Creating key_pair for SSH in AWS instance

resource "tls_private_key" "createkey" {
  algorithm = "RSA"
  rsa_bits  = 4096
}


resource "aws_key_pair" "generated_key" {
  key_name   = "terraform-key"
  public_key = tls_private_key.createkey.public_key_openssh
}

resource "null_resource" "savekey"  {
  depends_on = [
    tls_private_key.createkey,
  ]
    provisioner "local-exec" {
        command = "echo  '${tls_private_key.createkey.private_key_pem}' > wordpress_key.pem"
    }
}



# Creating AWS EC2 Instance with previously created key pair and security group

resource "aws_instance" "webserver" {
  #  Change ami id according to your region
  #  https://github.com/losDaniel/spot-connect/blob/d474cbbf8c2aa02127c445c303d0ac435d88a0d2/build/lib/spot_connect/data/ami_data.csv
  ami           = "ami-0fe1ff5007e7820fd" 
  instance_type = "t2.micro"
  key_name = aws_key_pair.generated_key.key_name
  security_groups = [ "open" ] # your security group name

  connection {
    type     = "ssh"
    user     = "ec2-user"
    private_key = tls_private_key.createkey.private_key_pem
    host     = aws_instance.webserver.public_ip
  }

  provisioner "remote-exec" {
    inline = [
    "sudo yum update -y",
    "sudo yum install git -y",
    "sudo yum install docker -y",
    "sudo service docker start",
    "sudo usermod -a -G docker ec2-user",
    "sudo curl -L \"https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)\" -o /usr/local/bin/docker-compose",
    "sudo chmod +x /usr/local/bin/docker-compose",
    "docker pull mysql:5.7",
    "docker pull wordpress",
    "docker pull phpmyadmin/phpmyadmin",
    "mkdir wordpress_data"   
    ]
  }

  tags = {
    Name = "terraform-docker-pull"
  }

}

# Storing IP address in file
resource "null_resource" "getIp"  {
    provisioner "local-exec" {
        command = "echo  ${aws_instance.webserver.public_ip} > publicip.txt"
    }
}

In case you want to work against a different region, update the ami accordingly.

Verify docker pulled into the machine :

enter image description here

Upvotes: 3

Related Questions