0

I added a new userdata script manually when there was an outage. I wanted to add this script back to terraform so that terraform state is up-to-date.

I'm not sure what is wrong here, its trying to recreate the instance.

What's wrong with my terraform changes?

Manually added user_data script in ec2 instance:

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash
iptables -F
echo "UserData is Executed"
--//

Existing config:

cloud-init.tpl

#cloud-config
---
package_update: true
packages:
  - docker

#This runs on every boot
bootcmd:
  - sh -c "sudo service docker start"

#These do not run on every boot
runcmd:
  - curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-Linux-x86_64" -o /usr/local/bin/docker-compose
  - chmod +x /usr/local/bin/docker-compose
  - sh -c "sudo service docker start"
  - mkdir /data
  - ${format_command}
  - echo "/dev/xvdf /data ext4 defaults,noatime 0 2" >> /etc/fstab
  - mount -a

#ihr-deployer key
ssh_authorized_keys:
  - ssh-rsa 
AAxxxx

data.tf

data "template_file" "cloud_init" {
  template = "${file("${path.module}/cloud-init.tpl")}"

  vars = {
    format_command = "${local.new_volume == 1 ? "sudo mkfs -t ext4 /dev/xvdf" : "echo DEVICE HAS ALREADY BEEN FORMATTED"}"
  }
}

data "template_cloudinit_config" "cloud_init" {
  part {
    content = "${data.template_file.cloud_init.rendered}"
  }
}

main.tf

  user_data                   = "${data.template_cloudinit_config.cloud_init.rendered}"

Changes:

data "template_cloudinit_config" "cloud_init" {
  part {
    content = "${data.template_file.cloud_init.rendered}"
  }

  part {
    filename     = "userdata.txt"
    content_type = "text/x-shellscript"
    content      = "iptables -F\necho \"UserData is Executed\"\n"
  }
}

Output:

user_data: "c3b472b9b74264b21237dd7e71f0ff89d76b83b2" => "231c0e27943da00a4c0df284bf194729020ed105" (forces new resource)

1 Answer 1

2

You'll need to ignore user_data changes:

resource "aws_instance" "blah" {
  ...
  lifecycle {
    ignore_changes = ["user_data"]
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.