Terraform Variable

  • Variable helps in centralize and manage values in the configuration.
  • The variable block consist of
    • Type
    • Description
    • Default values.
  • We can create a file variable.tf or default file name terraform.tfvars. We can also specify flag for variable files.
  • For any other file name used to define variable, use the command flag, –var-file. You can specify more than one file, but they will be executed in sequence.
  • All environment variables are defined using prefix TF_VAR_<variable name>
  • Terraform as a built in variable called as PATH it’s basically used in modules.
  • We can have below variable types in Terraform
    • String – Can be Boolean True or False or simple string
    • Map – A collection type (Associate array or Hash Table, similar to dictonary of Python)
    • List – A collection type (List of item, starting with index Zero).
  • We can call variables four ways,Through command prompt
    • Environment variables
    • Default variables
    • Variable defined in files
  • Variables have name and optional parameters,
    • Type – if type is omitted then terraform consider it as by default string.
    • Default
    • Description
  • Variables definition,
  • To call the variable in terraform main file. We need to use the keyword var as prefix
  • Syntax : var.<variable_name>
  • Calling the variables in main terraform file,

AWS Terraform Authentication

  • To run terraform on your local system for your AWS, you will need to first configure AWS on your local system.
  • Create a folder .aws/credential and store the AWS credential details at C:\Users\<yourhome folder>\.aws
  • You can do the above also through AWS command line > aws configure
  • You can define credentials in four different ways,
    • Static
    • Environment Variable
    • Shared Credential file
    • EC2 Role 
  • Static – it is basic method, we directly hard code the credentials in the .tf file provider section.
  • Environment Variable – Run the below command for windows machine, for Linux system use export commands.
  • Once configured the environmental variables, you can all the keys through provider sections.

  • Shared Credential files – You can access the credential files created using aws configure command. The file is by default at location $HOME/.aws/credentials.  You can call the shared file like below in the provider section.
  • EC2 Role – If running under EC2, then you can directly create and assign role to EC2, this avoids use of hard coded credentials.
  • Assume role – We can provide role ARN, terraform will attempt this role. You can call the role ARN in provider section.