Inventory: a sudo password with ' in it reaches Ansible intact

hosts was written with YAML quoting ('' for a quote), but Ansible splits
inventory lines like a shell, so it read it'' as its and becoming root
failed. Values are now shell-quoted, the SSH host, user, port and key
too, and the importer reads lines back the same way Ansible does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vvvomitandClaude Opus 5.5 committed 2026-10-29 15:57:33 +03:30
1 parent 06dbed58b9
commit 1d8ebaea91
3 files changed
+77 -29

No files matched your search

+39
View File
@@ -1,7 +1,9 @@
package config
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
@@ -70,3 +72,40 @@ func TestLocalHostsUseSystemPython(t *testing.T) {
t.Errorf("ssh got %q", got)
}
}
// The inventory line is read back the way Ansible reads it, shell-style:
// a quote in the sudo password used to come out without it.
func TestHostsINIQuoting(t *testing.T) {
c := Default()
c.Domain = "example.org"
c.Target = Target{Mode: "ssh", Host: "192.0.2.1", User: "deploy", Port: "2222", SSHKey: "~/my keys/id", BecomePass: `it's "a" \pass #1`}
line := strings.Split(strings.TrimSpace(c.HostsINI()), "\n")
fields := splitHostLine(line[len(line)-1])
got := map[string]string{}
for _, f := range fields[1:] {
k, v, _ := strings.Cut(f, "=")
got[k] = v
}
for k, want := range map[string]string{"ansible_host": "192.0.2.1", "ansible_ssh_user": "deploy", "ansible_port": "2222",
"ansible_ssh_private_key_file": "~/my keys/id", "ansible_become_password": c.Target.BecomePass} {
if got[k] != want {
t.Errorf("%s = %q, want %q", k, got[k], want)
}
}
bin, err := exec.LookPath("ansible-inventory")
if err != nil {
return
}
dir := t.TempDir()
_ = os.WriteFile(filepath.Join(dir, "hosts"), []byte(c.HostsINI()), 0o644)
cmd := exec.Command(bin, "-i", "hosts", "--host", c.HostName())
cmd.Dir, cmd.Env = dir, append(os.Environ(), "ANSIBLE_HOME="+filepath.Join(dir, ".ansible"))
out, err := cmd.Output()
var vars map[string]any
if err != nil || json.Unmarshal(out, &vars) != nil {
t.Fatalf("ansible-inventory: %v\n%s", err, out)
}
if vars["ansible_become_password"] != c.Target.BecomePass || vars["ansible_ssh_private_key_file"] != "~/my keys/id" {
t.Errorf("Ansible reads %v", vars)
}
}
+28 -25
View File
@@ -523,7 +523,7 @@ func readHosts(path string, c *Config) error {
o := map[string]string{}
for _, f := range fields[1:] {
if k, val, ok := strings.Cut(f, "="); ok {
o[k] = unquote(val)
o[k] = val
}
}
if host == "" || fields[0] == c.HostName() {
@@ -566,53 +566,56 @@ func readHosts(path string, c *Config) error {
return nil
}
// splitHostLine splits an INI inventory line on spaces outside quotes.
// splitHostLine splits an INI inventory line the way Ansible does (a POSIX
// shell split): quotes group and are removed, \ escapes outside '...'.
func splitHostLine(line string) []string {
var out []string
var cur strings.Builder
var quote rune
word, esc := false, false
for _, r := range line {
switch {
case quote != 0:
case esc:
cur.WriteRune(r)
esc = false
case quote == '\'':
if r == quote {
quote = 0
} else {
cur.WriteRune(r)
}
case quote == '"':
switch r {
case '"':
quote = 0
case '\\':
esc = true
default:
cur.WriteRune(r)
}
cur.WriteRune(r)
case r == '\'' || r == '"':
quote = r
cur.WriteRune(r)
quote, word = r, true
case r == '\\':
esc, word = true, true
case r == ' ' || r == '\t':
if cur.Len() > 0 {
if word {
out = append(out, cur.String())
cur.Reset()
word = false
}
case r == '#':
if cur.Len() == 0 {
return out // a comment
}
cur.WriteRune(r)
case r == '#' && !word:
return out // a comment
default:
cur.WriteRune(r)
word = true
}
}
if cur.Len() > 0 {
if word {
out = append(out, cur.String())
}
return out
}
// unquote undoes the quoting of an inventory value, including the
// doubled ” that HostsINI writes for a quote inside single quotes.
func unquote(s string) string {
switch {
case len(s) >= 2 && s[0] == '\'' && s[len(s)-1] == '\'':
return strings.ReplaceAll(s[1:len(s)-1], "''", "'")
case len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"':
return s[1 : len(s)-1]
}
return s
}
// SuggestName picks a server name for an import: the first server if it
// was never set up, else one made from the domain.
func SuggestName(domain string) string {
+10 -4
View File
@@ -109,6 +109,12 @@ func indent(s, pad string) string {
return strings.Join(lines, "\n")
}
// iniQuote quotes a value for an INI inventory line, which Ansible splits
// like a shell does. shortcut: a value that reads as a number, list or
// {{ template }} is still converted by Ansible; a YAML host_vars file would
// keep it as typed, if a password like that ever matters.
func iniQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
// Quote renders s as a single-quoted YAML scalar.
func Quote(s string) string { return "'" + strings.ReplaceAll(s, "'", "''") + "'" }
@@ -376,19 +382,19 @@ func (c *Config) HostsINI() string {
parts = append(parts, "ansible_become=true", "ansible_become_user=root")
}
} else {
parts = append(parts, "ansible_host="+t.Host, "ansible_ssh_user="+t.User)
parts = append(parts, "ansible_host="+iniQuote(t.Host), "ansible_ssh_user="+iniQuote(t.User))
if t.Port != "" && t.Port != "22" {
parts = append(parts, "ansible_port="+t.Port)
parts = append(parts, "ansible_port="+iniQuote(t.Port))
}
if t.SSHKey != "" {
parts = append(parts, "ansible_ssh_private_key_file="+t.SSHKey)
parts = append(parts, "ansible_ssh_private_key_file="+iniQuote(t.SSHKey))
}
if t.User != "root" {
parts = append(parts, "ansible_become=true", "ansible_become_user=root")
}
}
if t.BecomePass != "" {
parts = append(parts, "ansible_become_password="+Quote(t.BecomePass))
parts = append(parts, "ansible_become_password="+iniQuote(t.BecomePass))
}
b.WriteString(strings.Join(parts, " ") + "\n")
return b.String()