-2

I just provisioned an EC2 instance using terraform. Now I'd like to install ansible on said machine in an automated way using terraform. Is there a way to do so?

F1ko
  • 3,326
  • 1
  • 9
  • 24
  • 3
    Please focus next time more on the question and especially on what you have done so far than telling volunteers that your question is more urgent than helping others – James Z Jun 13 '21 at 07:42
  • use a `provisioner "remote-exec"`: https://levelup.gitconnected.com/intro-to-terraform-provision-ec2-instance-and-install-jenkins-3ccb7e2d60f6 – luk2302 Jun 13 '21 at 08:35

1 Answers1

2

Just want to clarify:

Usually there is no need to install ansible on a machine after provisioning it since there isn't a daemon or agent required to be able to execute ansible tasks on a remote machine. The usual workflow would be to provision machines with terraform and then configure them via ansible from a remote machine that can reach the newly created ones. So it only ever needs one machine that has ansible installed (which could as well be your local machine in case you can directly connect to the provisioned instances).

However, to answer your question on how you can install ansible (or anything else) on a machine that you just provisioned with terraform:

There is a provisioner called remote-exec: https://www.terraform.io/docs/language/resources/provisioners/remote-exec.html

Just use it within your instance declaration. It comes with an argument called inline which you can use to write down your installation commands. There are many different ways of installing ansible, depending on your setup some of those may not even work, therefore I cannot tell you which one is the best for you.

However, to give you an example of how to use the provisioner:

resource "aws_instance" "my-instance" {
  instance_type = "t3.micro"
  # ...

  provisioner "remote-exec" {
    inline = [
      "apt update",
      "apt install <package>",
    ]
  }
}
F1ko
  • 3,326
  • 1
  • 9
  • 24
  • I will check it. Thank you for your reply. – vijay shankar Jun 13 '21 at 14:27
  • @vijayshankar : Great. Make sure to post what works for you or to accept the answer so that others know about it as well. – F1ko Jun 13 '21 at 18:47
  • provider aws { region = "ap-south-1" } resource "aws_instance" "terraansilinux" { ami = "ami-0ad704c126371a549" instance_type = "t2.micro" tags = { Name = "ec2instanceforansi" } provisioner "local-exec" { command = "sudo yum install python-pip -y" } provisioner "local-exec" { command = "sudo pip install ansible" } } – vijay shankar Jun 24 '21 at 11:51
  • this code works. Thanks for your help.provider aws { region = "ap-south-1" } resource "aws_instance" "terraansilinux" { ami = "ami-0ad704c126371a549" instance_type = "t2.micro" tags = { Name = "ec2instanceforansi" } provisioner "local-exec" { command = "sudo yum install python-pip -y" } provisioner "local-exec" { command = "sudo pip install ansible" } } – vijay shankar Jun 24 '21 at 11:51