-2

I want to make new instance with "user1" rather than ec2-user(AWS) default.i want achieve this by terraform. Like in azure terraform it can be done by "os_profile{}", but how can i do in aws by terraform scripts?

1

AWS AMIs come with a default username - which username it is depends on the specific AMI that is launched. Amazon Linux AMIs use ec2-user, CentOS uses centos, and there's other combinations too.

If you want to create your own user on instance launch, you can use EC2 User Data for this, which essentially entails passing a custom script that will be run at launch time.

The user_data argument is supported by Terraform's aws_instance resource. You can specify a script inline, but for most cases you'll probably want to use an external file or template.

For example:

create-user.sh:

#!/usr/bin/env bash

useradd mytestuser

# Anything else you want to do to set up your user account

main.tf:

resource "aws_instance" "main" {
  ...
  user_data = "${file("create-user.sh")}"
}

Alternatively, there's an example on rendering a template here, which is useful if you want to pass through custom values rather than just provide a static file.

Or, as an alternative to writing your own shell script, you could try rendering a cloudinit config file using template_cloudinit_config. Some resources that might be useful for this include this blog post and this part of the cloudinit documentation.

  • Thanks,this is working..But i want know hoe we can pass the arguments in terraform while executing bash script>beacause i want to pass the RSA key through arguments.e.g.provisioner "local-exec" { command = "user2.sh '${aws_key_pair.key.public_key}' " } – MeetGadhiya Jun 30 '18 at 8:36
  • I covered that in the second last para - see the link there to the example on rendering a template. – Tim Malone Jun 30 '18 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.