terraform not updating content from user-data file

989 Views Asked by At

I have a user-data file attached to the main.tf. Whenever I make changes to the user-data file, and then run the terraform apply, the changes do not reflect on the server until I destroy and recreate the resources. Please is this the default operation or am I missing something. Thank you for answers.

After making the changes on the user date file, I expect that terraform apply will create a new instance with the updated user-data file content, but that is not happening.

2

There are 2 best solutions below

2
On

As documented on the aws_instance resource on terraform, you need to set the user_data_replace_on_change attribute to true. It is false by default.

user_data_replace_on_change - (Optional) When used in combination with user_data or user_data_base64 will trigger a destroy and recreate when set to true. Defaults to false if not set.

Also note that by default user_data is only applied at the time of instance creation so terraform will destroy and create the resource again when this flag is set.

0
On

Chris Doyle - thank you so much, yes I used the code below, it's working with a shell script.

resource "aws_instance" "ec2_instance" {
    ami = data.aws_ami.base_ami.id
    count = "1"
    subnet_id = "subnet-xxxxxxxx"
    instance_type = "t3a.medium"
    key_name = "keyname"
    user_data_replace_on_change = true
    user_data = "${file("init.sh")}"
    }
  }
}

Note: the below part is not working with the same config. So I used shell script.

<< EOF
      #!/bin/bash
      echo "echo the content"
      sudo yum install httpd -y && sudo service httpd start
EOF