Issue
I am trying to put a shell script to check if there is a drift in terraform or not and I am filtering terraform plan to a variable and using grep trying to print if there is a drift. But echo is printing the whole variable output rather filtered output with grep condition.
i=environment
terraform init
tf_plan=$(terraform plan | grep -v "Refreshing state" | grep -v "data")
drift_check=`echo $tf_plan | grep -c 'to add\|to change\|to destroy'`
if [[ $drift_check -ge 1 ]]
then
echo "Drift detected in environment $i"
printf "%s:%s" "$i" "`echo $tf_plan | grep -E 'to add|to change|to destroy'`"
else
echo "No drift detected in environment $i"
printf "%s:%s" "$i" "`echo $tf_plan | grep -E 'No changes'`"
fi
ExpectedOutput assuming there is a drift
environment:Plan: 0 to add, 1 to change, 0 to destroy.
When I run these commands manually I am getting expected output like below
echo $tf_plan | grep -c 'to add\|to change\|to destroy'
1
echo $tf_plan | grep -E 'to add|to change|to destroy'
Plan: 0 to add, 1 to change, 0 to destroy.
printf "%s:%s" "$i":"`echo $tf_plan | grep -E 'to add|to change|to destroy'`"
environment:Plan: 0 to add, 1 to change, 0 to destroy
But through bash script its printing out whole terraform drift plan. Below is the output of tf_plan variable
echo $tf_plan
Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
~ update in-place
Terraform will perform the following actions:
# elasticstack_elasticsearch_index.idx1 will be updated in-place
~ resource "elasticstack_elasticsearch_index" "idx_salesorder_2019_v6" {
id = "xyzadcfgd/idx1"
~ mappings = jsonencode(
~ {
~ properties = {
~ address = {
~ properties = {
~ addressdetails = {
~ properties = {
- streetlocation = {
- fields = {
- keyword = {
- ignore_above = 256
- type = "keyword"
}
}
- type = "text"
}
# (30 unchanged attributes hidden)
}
}
# (1 unchanged attribute hidden)
}
}
# (3 unchanged attributes hidden)
}
}
)
name = "idx1"
# (8 unchanged attributes hidden)
# (9 unchanged blocks hidden)
}
Plan: 0 to add, 1 to change, 0 to destroy.
Solution
You should add quotes to the $tf_plan
variable, otherwise bash will print the variable content without the newlines, causing the grep to treat it as an entire line and match everything.
if [[ $drift_check -ge 1 ]]
then
echo "Drift detected in environment $i"
printf "%s:%s" "$i" "`echo "$tf_plan" | grep -E 'to add|to change|to destroy'`" # <-- tf_plan quoted here
else
echo "No drift detected in environment $i"
printf "%s:%s" "$i" "`echo "$tf_plan" | grep -E 'No changes'`"
fi
Answered By - opeonikute Answer Checked By - Mildred Charles (WPSolving Admin)