dotnet / aspire

An opinionated, cloud ready stack for building observable, production ready, distributed applications in .NET
https://learn.microsoft.com/dotnet/aspire
MIT License
3.61k stars 400 forks source link

Trying to use AddExecutable to launch sqlpackage on startup, fails because it can't resolve connection string #4940

Closed drdr-kr closed 1 month ago

drdr-kr commented 1 month ago

Is there an existing issue for this?

Describe the bug

I have a minimalist Aspire app up and running, which has SQL Server added using the Aspire hosting package

var sqldb = builder.AddSqlServer("sql")
    // Mount the init scripts directory into the container.
    .WithBindMount("./sqlserverconfig", "/usr/config")
    // Mount the SQL scripts directory into the container so that the init scripts run.
    .WithBindMount("./sqlsetup", "/docker-entrypoint-initdb.d")
    // Run the custom entrypoint script on startup.
    .WithEntrypoint("/usr/config/entrypoint.sh")
    .WithHealthCheck()
    ;

var addressBookDb = sqldb.AddDatabase("AddressBook");

I'm trying to launch sqlpackage as an executable during startup to bring the database up to the expected state like so

var sqlpackage = builder.AddExecutable("sqlpackage", "C:\\Dev\\Playground\\AspireApp1\\AspireApp1.AppHost\\sqlpackage\\sqlpackage.exe", Environment.CurrentDirectory, 
        "/Action:Publish", 
        "/SourceFile:../sqlsetup/db.dacpac",
        "/TargetConnectionString:\"%ConnectionStrings__AddressBook%\"")
    .WithReference(addressBookDb)
//.WaitFor(sqldb)
    ;

however, despite trying a few different formats I can't get sqlpackage to recognise the connection string. I think it's probably because the value is escaped when running it's not able to recognise the environment variable. I've tried

"/TargetConnectionString:\"%ConnectionStringsAddressBook%\"" "/TargetConnectionString:\"$ConnectionStringsAddressBook\"" "/TargetConnectionString:\"$ConnectionStrings__AddressBook$\""

image

image

Expected Behavior

No response

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version info

No response

Anything else?

No response

drdr-kr commented 1 month ago

I've dug a bit deeper, and figured out that I can execute sqlpackage via powershell doing something like this:

var sqlpackage = builder.AddExecutable("sqlpackage", "powershell", ".", $"{Environment.CurrentDirectory}\\sqlpackage.ps1")
    .WithReference(addressBookDb)
    .WaitFor(sqldb)
    ;

and then in the sqlpackage.ps1 script file I have the following

./sqlpackage.exe /Action:Publish /SourceFile:./sqlsetup/My.dacpac /TargetConnectionString:$env:ConnectionStrings__AddressBook

So, I think this is resolved using a workaround, it would be nice if this could be done a bit more neatly but thanks for all the work you're doing on Aspire :-)

ErikEJ commented 1 month ago

You could also have a look at: https://www.nuget.org/packages/MSBuild.Sdk.SqlProj.Aspire