command: adjust exit code of state rm (#22300)

* command: adjust exit code of state rm and state mv

Commands `state rm` and `state mv` will now exit with code 1 when the
target resource is not found in the current state.
This is consistent with `terraform state show non_existent_resource`.

Fixes #17800
This commit is contained in:
João G. Packer 2020-06-24 15:03:23 -03:00 committed by GitHub
parent 9f455bfc55
commit fd47260fdc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 11 deletions

View File

@ -109,15 +109,21 @@ func (c *StateRmCommand) Run(args []string) int {
return 1
}
if len(diags) > 0 {
if len(diags) > 0 && isCount != 0 {
c.showDiagnostics(diags)
}
if isCount == 0 {
c.Ui.Output("No matching resource instances found.")
} else {
c.Ui.Output(fmt.Sprintf("Successfully removed %d resource instance(s).", isCount))
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
"Invalid target address",
"No matching objects found. To view the available instances, use \"terraform state list\". Please modify the address to reference a specific instance.",
))
c.showDiagnostics(diags)
return 1
}
c.Ui.Output(fmt.Sprintf("Successfully removed %d resource instance(s).", isCount))
return 0
}

View File

@ -276,14 +276,9 @@ func TestStateRmNonExist(t *testing.T) {
"-state", statePath,
"test_instance.baz", // doesn't exist in the state constructed above
}
if code := c.Run(args); code != 0 {
t.Fatalf("expected exit status %d, got: %d", 0, code)
if code := c.Run(args); code != 1 {
t.Fatalf("expected exit status %d, got: %d", 1, code)
}
if msg := ui.OutputWriter.String(); !strings.Contains(msg, "No matching resource instances found") {
t.Fatalf("unexpected output:\n%s", msg)
}
}
func TestStateRm_backupExplicit(t *testing.T) {