Skip to content

Instantly share code, notes, and snippets.

@snandam
Last active November 15, 2022 19:43
Show Gist options
  • Save snandam/c7b4fdfee68340a597d398622da1eb74 to your computer and use it in GitHub Desktop.
Save snandam/c7b4fdfee68340a597d398622da1eb74 to your computer and use it in GitHub Desktop.
Terraform - Bootstrap ec2 machine with ansible, copy scripts and run playbook
#--------------------------------------------------------------
# Create an EC2 machine, bootstrap with ansible
#
resource "aws_instance" "ec2-linux" {
ami = "ami-a4c7edb2"
vpc_security_group_ids = ["${aws_security_group.allow-all-test-sg.id}"]
key_name = "${var.private_ssh_key}"
instance_type = "t2.nano"
count = "1"
subnet_id = "${var.subnet_id}"
associate_public_ip_address = true
ebs_optimized = false
root_block_device {
volume_type = "${var.ebs_root_volume_type}"
volume_size = 21
delete_on_termination = "true"
}
tags {
Name = "${var.application_name}-1"
Owner = "${var.owner}"
Terraform = "true"
}
user_data = ""
provisioner "remote-exec" {
connection {
type = "ssh"
user = "ec2-user"
private_key = "${file("${var.private_ssh_key_path}")}"
}
inline = [
"sudo pip install ansible",
]
}
}
#--------------------------------------------------------------
# Copy local files and run ansible on target machine
# uncomment the lifecyle block if you don't want to run ansible everytime
resource "null_resource" "ansible" {
triggers {
key = "${uuid()}"
}
// lifecycle {
// ignore_changes = ["*"]
// }
provisioner "local-exec" {
connection {
type = "ssh"
user = "ec2-user"
private_key = "${file("${var.private_ssh_key_path}")}"
}
command = "scp -o \"StrictHostKeyChecking no\" -i ${var.private_ssh_key_path} -r provisioning ec2-user@${aws_instance.ec2-linux.public_ip}:~/"
}
provisioner "remote-exec" {
connection {
type = "ssh"
host = "${aws_instance.ec2-linux.public_ip}"
user = "ec2-user"
private_key = "${file("${var.private_ssh_key_path}")}"
}
inline = [
"ansible-playbook -i 'localhost,' -c local ~/provisioning/ansible/playbooks/install-vault.yml",
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment