Keychain operations failed with XCodebuild, but succeed with Xcode.app

I'm having issue with keychain access for my SWIFT project. The keychain operations succeed while I run the test with Xcode.app (GUI), but failed when I run the test through command line tool xcodebuild. I assume I did something wrong with the environment. Is there any suggestion or instruction about how should I setup for the xcodebuild command line tool?

Here is my unit test.

static func run_shell(_ command: String) -> String {
        let task = Process()
        let pipe = Pipe()
        
        task.standardOutput = pipe
        task.standardError = pipe
        task.arguments = ["-c", command]
        task.launchPath = "/bin/zsh"
        task.standardInput = nil
        task.launch()
        
        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = String(data: data, encoding: .utf8)!
        
        return output
    }
    
    func testSecurityDefaultKeychain() throws
    {
        print(TLSContextTests.run_shell("security default-keychain"));
    }

Other things I have tried:

  1. I got the same result if I use SecKeychainCopyDefault instead of the security command.

  2. If I directly run security command in my terminal, it worked fine.

> security default-keychain
    "/Users/runner/Library/Keychains/login.keychain-db"
  1. I also tried with sudo xcodebuild & chmod a+x xcodebuild to make sure the tool has permission to access keychain, but it was not helpful.

I had a post about the same issue a month ago. At that time I thought it was an issue for CI environment only. However, it turns out it was the xcodebuild. https://forums.developer.apple.com/forums/thread/747794

Replies

Update: Resolved. It turned out to be issue for my environment variable. The env var "HOME" was set to a different value in the terminal.