nbering / terraform-provider-ansible

"Logical" provider for integrating with an Ansible Dynamic Inventory script.
https://nbering.github.io/terraform-provider-ansible/
Mozilla Public License 2.0
329 stars 64 forks source link

Use Dynamic Terraform State During Terraform Execution #35

Closed danielshiplett closed 3 years ago

danielshiplett commented 3 years ago

Is it possible to use this provider and the dynamic terraform.py inventory script during the execution of a 'terraform apply'? What I'd like to be able to do is some early provisioning of new instances during the execution of Terraform. I can do this now if I hard code a bootstrap inventory file with some matching host patterns. However, I'd like to make my Terraform more dynamic. I was trying to use this provisioner, but it looks like the Terraform state that it pulls does not include any changes made during the current execution. Is this just an inherent limit of Terraform?

For example, here's an Ansible host resource:

resource "ansible_host" "rke-cluster" {
  depends_on = [
    module.rke-cluster
  ]

  count = 1

  inventory_hostname = module.rke-cluster.tags[count.index]["Name"]

  groups = [
    "rke"
  ]

  vars = {
    ansible_host = module.rke-cluster.private_dns[count.index]
    ansible_ssh_common_args = "-o ProxyCommand=\"ssh -W %h:%p centos@${aws_eip.jumpbox-eip.public_ip}\""
  }
}

And later on, here is a local provisioner that attempts to get the dynamic inventory:

resource "null_resource" "bootstrap-rke-cluster" {
  depends_on = [
    ansible_host.rke-cluster
  ]

  count = 01

  provisioner "local-exec" {
    command = <<EOC
  ansible/terraform.py;
EOC
  }
}

But the output doesn't show the instance that was just added to the inventory (it should show a second host, but only shows a single host from a previous execution):

{
  "_meta": {
    "hostvars": {
      "jumpbox-00": {}
    }
  },
  "all": {
    "children": [],
    "hosts": [
      "jumpbox-00"
    ],
    "vars": {}
  },
  "jumpbox": {
    "children": [],
    "hosts": [
      "jumpbox-00"
    ],
    "vars": {}
  }
}
nbering commented 3 years ago

This is one of the limitations that probably isn't worth working around as a provider. Maybe as a provisioner? But there are other projects that attempt to run Ansible as a provisioner, and I didn't really like some of the trade-offs that come with that implementation.

I don't intend for Ansible to be run during terrraform apply. As the state is not settled, yet. The mechanics are much simpler if Terraform is just used for infrastructure provisioning, and Ansible is used as a follow-up to provision software.