Add lineinfile create support

This commit is contained in:
Virgil 2026-04-01 22:56:14 +00:00
parent b67d9419a4
commit e793321e1e
2 changed files with 24 additions and 0 deletions

View file

@ -592,6 +592,7 @@ func (e *Executor) moduleLineinfile(ctx context.Context, client sshExecutorClien
regexp := getStringArg(args, "regexp", "")
state := getStringArg(args, "state", "present")
backrefs := getBoolArg(args, "backrefs", false)
create := getBoolArg(args, "create", false)
if state == "absent" {
if regexp != "" {
@ -602,6 +603,12 @@ func (e *Executor) moduleLineinfile(ctx context.Context, client sshExecutorClien
}
}
} else {
// Create the file first when requested so regexp-based updates have a
// target to operate on.
if create {
_, _, _, _ = client.Run(ctx, sprintf("touch %q", path))
}
// state == present
if regexp != "" {
// Replace line matching regexp.

View file

@ -1,6 +1,7 @@
package ansible
import (
"context"
"io/fs"
"testing"
@ -403,6 +404,22 @@ func TestModulesFile_ModuleLineinfile_Good_RegexpFallsBackToAppend(t *testing.T)
assert.True(t, mock.hasExecuted(`echo`))
}
func TestModulesFile_ModuleLineinfile_Good_CreateFile(t *testing.T) {
e, mock := newTestExecutorWithMock("host1")
result, err := e.moduleLineinfile(context.Background(), mock, map[string]any{
"path": "/etc/example.conf",
"regexp": "^setting=",
"line": "setting=value",
"create": true,
})
require.NoError(t, err)
assert.True(t, result.Changed)
assert.True(t, mock.hasExecuted(`touch "/etc/example\.conf"`))
assert.True(t, mock.hasExecuted(`sed -i`))
}
func TestModulesFile_ModuleLineinfile_Good_BackrefsReplaceMatchOnly(t *testing.T) {
e, mock := newTestExecutorWithMock("host1")