However, you can also retrieve these at any time using the Terraform command. For example, to get the public IP address, you can use the example command below. Terraform output publicip 94.237.45.221. The same way you could ask Terraform. Terraform commands cheat sheet. Terraform CLI Cheat Sheet, Unless terraform plan, apply, destroy and import will not work. The command terraform init will install: Terraform modules; Eventually a backend » Terraform Commands (CLI) For a hands-on tutorial, try.
- Terraform Commands Cheat Sheet 2020
- Terraform Plan Command
- Terraform Command Reference
- Terraform Command Line
Commands
This is used to download and configure providers in your terraform code:
Resource:https://learn.hashicorp.com/tutorials/terraform/eks
Run the terraform code
Destroy all terraform resources
List all resources
Resource:https://github.com/hashicorp/terraform/issues/12917
Remove something from state
This will remove packet_device
called worker from your existing state:
Resource:https://www.terraform.io/docs/cli/commands/state/rm.html
Cause rebuild
Resource:https://www.terraform.io/docs/cli/commands/taint.html
Makefile Template
Import existing resources
This particular example will import the OPTIONS method from an API gateway.
Put the following in main.tf
:
Then run this command to import it:
You can find the output by running this command:
Another example (import the POST gateway method):
put the following in main.tf
:
command to import:
One last example (import stage):
put the following in main.tf
:
command to import:
Example with security group
Terraform code:
Command to import:
To see the changes:
AWS
Secrets Manager
Create blank secret:
Resource:https://gist.github.com/anttu/6995f20e641d4f30a6003520f70608b3
Create IAM role to run on an instance and attach it
iam.tf
:
iam_role_policy.json
:
ec2_iam_role_policy.json
- this is going to be variable based on what you want your ec2 instance to do. Here's an eaxmple that allows it to do a bunch of logging stuff:
ec2.tf
:
Resources:
https://adrianhesketh.com/2016/06/27/creating-aws-instance-roles-with-terraform/
https://devopslearning.medium.com/aws-iam-ec2-instance-role-using-terraform-fa2b21488536
https://stackoverflow.com/questions/62953164/create-and-attach-iam-role-to-ec2-using-terraform
Import existing IAM role
- Create a directory and run
terraform init
- Create a placeholder like so
- Run this command to import the existing role:
- Run
terraform show
to get the block of terraform code that you'll want to implement
Resource:https://mklein.io/2019/09/30/terraform-import-role-policy/
GCP
GCS Backend
If you want to manage your terraform state with a remote backend (you do if you have multiple people managing the infrastructure), you will need to run a couple of command before your first terraform init
.
Create the bucket you'll be storing the state in:
Next, enable object versioning to avoid any corruption with your state file:
Finally, create a backend.tfvars
with the following commands:
Add this block to your terraform code:
At this point, you can run the following to init your terraform:
This will take the variables we defined in the backend.tfvar
we created previously and apply them to the gcs
backend in the above terraform code.
From here, feel free to run plan
and then apply
.
Resources:
https://betterprogramming.pub/effective-ways-of-managing-your-terraform-state-44bc53043d5 - great introduction to the concept of terraform state
https://medium.com/swlh/terraform-securing-your-state-file-f6c4e13f02a9 - walkthrough of how to set things up with gsutil
Create ansible hosts file
aws_instance.managed*
ansible_template_builder.tf
:
templates/hosts.tmpl
:
Resource:
https://www.linkbynet.com/produce-an-ansible-inventory-with-terraform
Packer
Create packer file
packer_builder.tf
:
templates/ami_name_to_use.json.tpl
:
Create security group with instance's public ip
If you need to specify a security group that relies on an instance's public IP address and you don't want to use an EIP, you can do the following:
Resource:https://stackoverflow.com/questions/38246326/cycle-error-when-trying-to-create-aws-vpc-security-groups-using-terraform - discovered aws_security_group_rule
from here
column
Split columns automatically and auto-align in a tabular format
Format whitespace delimited text as table:
Format colon delimited text as table:
Remove surrounding parenthesis
Remove non-printable characters
- https://stackoverflow.com/questions/8914435/awk-sed-how-to-remove-parentheses-in-simple-text-file
switch case
Validate variables
You can use -z
to test whether a variable is unset or empty:
I’ve used an extended test [[
, which means that I don’t need to use quotes around my variables. I’m assuming that you need all three variables to be defined in order to continue. The exit
in the if
branch means that the else
is superfluous.
The standard way to do it in any POSIX-compliant shell would be like this:
The important differences here are that each variable check goes inside a separate test and that double quotes are used around each parameter expansion.
Compare directories
Program detection in shell scripts
POSIX compatible:
For bash
specific environments:
Explanation
Avoid which
. Not only is it an external process you’re launching for doing very little (meaning builtins like hash
, type
or command
are way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.
Why care?
- Many operating systems have a
which
that doesn’t even set an exit status, meaning theif which foo
won’t even work there and will always report thatfoo
exists, even if it doesn’t (note that some POSIX shells appear to do this forhash
too). - Many operating systems make
which
do custom and evil stuff like change the output or even hook into the package manager.
So, don’t use which
. Instead use one of these:
(Minor side-note: some will suggest 2>&-
is the same 2>/dev/null
but shorter - this is untrue. 2>&-
closes FD 2 which causes an error in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))
If your hash bang is /bin/sh
then you should care about what POSIX says. type
and hash
’s exit codes aren’t terribly well defined by POSIX, and hash
is seen to exit successfully when the command doesn’t exist (haven’t seen this with type
yet). command
’s exit status is well defined by POSIX, so that one is probably the safest to use.
If your script uses bash
though, POSIX rules don’t really matter anymore and both type
and hash
become perfectly safe to use. In bash type
now has a -P
to search just the PATH
and hash
has the side-effect that the command’s location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.
As a simple example, here’s a function that runs gdate
if it exists, otherwise date
:
Note that hash will only look in PATH. If your user’s PATH does not include sbin, hash will not find the binary that lives there. If you want to run bash code with sudo, you need to invoke bash from sudo: if sudo bash -c ‘hash groupadd’; then …
True if file exists and is executable.
test -x filename[ -x filename ]
hash foo 2>/dev/null
: works with zsh, bash, dash and ash.
type -p foo
: it appears to work with zsh, bash and ash (busybox), but not dash (it interprets -p
as an argument).
command -v foo
: works with zsh, bash, dash, but not ash (busybox) (-ash: command: not found
).
Also note that builtin
is not available with ash
and dash
.
Create backup file
Get ISO date
Remove specific file extension
xargs failsafe
Bash variable tricks
Terraform Commands Cheat Sheet 2020
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.
If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.
If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.
This is referred to as Substring Expansion. It expands to up to length characters of the value of parameter starting at the character specified by offset. If parameter is ‘@’, an indexed array subscripted by ‘@’ or ‘*’, or an associative array name, the results differ as described below. If length is omitted, it expands to the substring of the value of parameter starting at the character specified by offset and extending to the end of the value. length and offset are arithmetic expressions (see Shell Arithmetic).
If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter. If length evaluates to a number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of characters, and the expansion is the characters between offset and that result. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the ‘:-’ expansion.
Here are some examples illustrating substring expansion on parameters and subscripted arrays:
If parameter is ‘@’, the result is length positional parameters beginning at offset. A negative offset is taken relative to one greater than the greatest positional parameter, so an offset of -1 evaluates to the last positional parameter. It is an expansion error if length evaluates to a number less than zero.
Terraform Plan Command
The following examples illustrate substring expansion using positional parameters:
If parameter is an indexed array name subscripted by ‘@’ or ‘*’, the result is the length members of the array beginning with ${parameter[offset]}
. A negative offset is taken relative to one greater than the maximum index of the specified array. It is an expansion error if length evaluates to a number less than zero.
These examples show how you can use substring expansion with indexed arrays:
Substring expansion applied to an associative array produces undefined results.
Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default. If offset is 0, and the positional parameters are used, $@ is prefixed to the list.
Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable. When ‘@’ is used and the expansion appears within double quotes, each variable name expands to a separate word.
If name is an array variable, expands to the list of array indices (keys) assigned in name. If name is not an array, expands to 0 if name is set and null otherwise. When ‘@’ is used and the expansion appears within double quotes, each key expands to a separate word.
The length in characters of the expanded value of parameter is substituted. If parameter is ‘’ or ‘@’, the value substituted is the number of positional parameters. If parameter is an array name subscripted by ‘’ or ‘@’, the value substituted is the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end of the array, and an index of -1 references the last element.
The word is expanded to produce a pattern just as in filename expansion (see Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with ‘/’, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with ‘#’, it must match at the beginning of the expanded value of parameter. If pattern begins with ‘%’, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If the nocasematch shell option (see the description of shopt in The Shopt Builtin) is enabled, the match is performed without regard to the case of alphabetic characters. If parameter is ‘@’ or ‘’, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.
This expansion modifies the case of alphabetic characters in parameter. The pattern is expanded to produce a pattern just as in filename expansion. Each character in the expanded value of parameter is tested against pattern, and, if it matches the pattern, its case is converted. The pattern should not attempt to match more than one character. The ‘^’ operator converts lowercase letters matching pattern to uppercase; the ‘,’ operator converts matching uppercase letters to lowercase. The ‘^^’ and ‘,’ expansions convert each matched character in the expanded value; the ‘^’ and ‘,’ expansions match and convert only the first character in the expanded value. If pattern is omitted, it is treated like a ‘?’, which matches every character. If parameter is ‘@’ or ‘’, the case modification operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the case modification operation is applied to each member of the array in turn, and the expansion is the resultant list.
The expansion is either a transformation of the value of parameter or information about parameter itself, depending on the value of operator. Each operator is a single letter:
Q
- The expansion is a string that is the value of parameter quoted in a format that can be reused as input.E
- The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $’…’ quoting mechansim.P
- The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string (see Controlling the Prompt).A
- The expansion is a string in the form of an assignment statement or declare command that, if evaluated, will recreate parameter with its attributes and value.a
- The expansion is a string consisting of flag values representing parameter’s attributes.
If parameter is ‘@’ or ‘’, the operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the operation is applied to each member of the array in turn, and the expansion is the resultant list.
Curl with certificate and basic authentication
SSH
Completely suppress key based authentication / Format for suSSHi:
user@@susshi.dc.domain.tld
: account with access granted by suSSHiroot@12.13.14.15
: actual target host/user
SMTP CLI clients
Terraform Command Reference
mailx
Terraform Command Line
AWK
If the 7nth field equals “security”, print field 3.