diff --git a/example-ttps/actions/change-directory/runtime-created-directory.yaml b/example-ttps/actions/change-directory/runtime-created-directory.yaml new file mode 100644 index 00000000..5d8b0c23 --- /dev/null +++ b/example-ttps/actions/change-directory/runtime-created-directory.yaml @@ -0,0 +1,28 @@ +--- +api_version: 2.0 +uuid: c15da914-de49-4297-a281-9c81b4fea413 +name: change_directory_example_with_runtime_created_directory +description: | + This TTP shows you how to use the change_directory action type to change the + working directory for all future actions, even if the directory doesn't exist until + this TTP is ran. +args: + - name: cd_destination + description: this argument is where we will try to cd to + default: /tmp/this_doesnt_exist_yet +steps: + - name: "Initial directory" + inline: | + echo "Current working directory is: \"$(pwd)\"" + - name: "Create directory" + inline: | + mkdir {{.Args.cd_destination}} + cleanup: + inline: | + rm -rf {{.Args.cd_destination}} + - name: "cd" + cd: {{.Args.cd_destination}} + cleanup: default + - name: "New directory" + inline: | + echo "Current working directory is: \"$(pwd)\"" diff --git a/pkg/blocks/changedirectory.go b/pkg/blocks/changedirectory.go index abdc8cc1..590e88ce 100644 --- a/pkg/blocks/changedirectory.go +++ b/pkg/blocks/changedirectory.go @@ -63,21 +63,6 @@ func (step *ChangeDirectoryStep) Validate(_ TTPExecutionContext) error { return err } - // Check if cd is a valid directory - fsys := step.FileSystem - if fsys == nil { - fsys = afero.NewOsFs() - } - - exists, err := afero.DirExists(fsys, step.Cd) - if err != nil { - return err - } - - if !exists { - return fmt.Errorf("directory \"%s\" does not exist", step.Cd) - } - return nil } @@ -96,6 +81,25 @@ func (step *ChangeDirectoryStep) Execute(ctx TTPExecutionContext) (*ActResult, e step.Cd = step.PreviousCDStep.PreviousDir } + // Check if cd is a valid directory + fsys := step.FileSystem + if fsys == nil { + if step.PreviousCDStep != nil && step.PreviousCDStep.FileSystem != nil { + fsys = step.PreviousCDStep.FileSystem + } else { + fsys = afero.NewOsFs() + } + } + + exists, err := afero.DirExists(fsys, step.Cd) + if err != nil { + return nil, err + } + + if !exists { + return nil, fmt.Errorf("directory \"%s\" does not exist", step.Cd) + } + logging.L().Infof("Changing directory to %s", step.Cd) if step.Cd == "" {