Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for passing secrets as docker build args #232

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/Writerside/topics/Build-Command.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,5 @@ The command will first create the manifest file, however, this can be overridden
| --runtime-identifier | | `ASPIRATE_RUNTIME_IDENTIFIER` | Sets the runtime identifier for project builds. Defaults to `linux-x64`. |
| --compose-build | | | Can be included one or more times to set certain dockerfile resource building to be handled by the compose file. This will skip build and push in aspirate. |
| --launch-profile | -lp | 'ASPIRATE_LAUNCH_PROFILE' | The launch profile to use when building the Aspire Manifest. |
| --use-secrets | | 'ASPIRATE_USE_SECRETS' | Will unlock the secrets so their values can be used for docker build arguments |
| --secret-password | | `ASPIRATE_SECRET_PASSWORD` | If using secrets, or you have a secret file - Specify the password to decrypt them. Required if `--use-secrets` and `--non-interactive` are set |
2 changes: 1 addition & 1 deletion src/Aspirate.Commands/Commands/BaseCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ private void LoadSecrets(TOptions options, ISecretService secretService, TOption
DisableSecrets = handler.CurrentState.DisableSecrets,
NonInteractive = options.NonInteractive,
SecretPassword = options.SecretPassword,
CommandUnlocksSecrets = CommandUnlocksSecrets,
CommandUnlocksSecrets = CommandUnlocksSecrets || handler.CurrentState.UseSecrets == true,
State = handler.CurrentState,
});

Expand Down
16 changes: 9 additions & 7 deletions src/Aspirate.Commands/Commands/Build/BuildCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ public sealed class BuildCommand : BaseCommand<BuildOptions, BuildCommandHandler

public BuildCommand() : base("build", "Builds and pushes containers")
{
AddOption(ProjectPathOption.Instance);
AddOption(AspireManifestOption.Instance);
AddOption(ContainerBuilderOption.Instance);
AddOption(ContainerImageTagOption.Instance);
AddOption(ContainerRegistryOption.Instance);
AddOption(ContainerRepositoryPrefixOption.Instance);
AddOption(RuntimeIdentifierOption.Instance);
AddOption(ProjectPathOption.Instance);
AddOption(AspireManifestOption.Instance);
AddOption(ContainerBuilderOption.Instance);
AddOption(ContainerImageTagOption.Instance);
AddOption(ContainerRegistryOption.Instance);
AddOption(ContainerRepositoryPrefixOption.Instance);
AddOption(RuntimeIdentifierOption.Instance);
AddOption(UseSecretsOption.Instance);
AddOption(SecretPasswordOption.Instance);
}
}
2 changes: 2 additions & 0 deletions src/Aspirate.Commands/Commands/Build/BuildCommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ public override Task<int> HandleAsync(BuildOptions options) =>
.QueueAction(nameof(LoadConfigurationAction))
.QueueAction(nameof(GenerateAspireManifestAction))
.QueueAction(nameof(LoadAspireManifestAction))
.QueueAction(nameof(PopulateInputsAction))
.QueueAction(nameof(SubstituteValuesAspireManifestAction))
.QueueAction(nameof(PopulateContainerDetailsForProjectsAction))
.QueueAction(nameof(BuildAndPushContainersFromProjectsAction))
.QueueAction(nameof(BuildAndPushContainersFromDockerfilesAction))
Expand Down
1 change: 1 addition & 0 deletions src/Aspirate.Commands/Commands/Build/BuildOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ public sealed class BuildOptions : BaseCommandOptions, IBuildOptions, IContainer
public List<string>? ContainerImageTags { get; set; }
public string? RuntimeIdentifier { get; set; }
public List<string>? ComposeBuilds { get; set; }
public bool? UseSecrets { get; set; }
}
1 change: 1 addition & 0 deletions src/Aspirate.Commands/Commands/Generate/GenerateOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public sealed class GenerateOptions : BaseCommandOptions,
public string? OutputFormat { get; set; }
public string? RuntimeIdentifier { get; set; }
public List<string>? ComposeBuilds { get; set; }
public bool? UseSecrets { get; set; }
public string? PrivateRegistryUrl { get; set; }
public string? PrivateRegistryUsername { get; set; }
public string? PrivateRegistryPassword { get; set; }
Expand Down
16 changes: 16 additions & 0 deletions src/Aspirate.Commands/Options/UseSecretsOption.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace Aspirate.Commands.Options;

public sealed class UseSecretsOption : BaseOption<bool?>
{
private static readonly string[] _aliases = ["--use-secrets"];

private UseSecretsOption() : base(_aliases, "ASPIRATE_USE_SECRETS", false)
{
Name = nameof(IBuildOptions.UseSecrets);
Description = "Include secrets as part of the build process";
Arity = ArgumentArity.ZeroOrOne;
IsRequired = false;
}

public static UseSecretsOption Instance { get; } = new();
}
1 change: 1 addition & 0 deletions src/Aspirate.Processors/Transformation/Literals.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ public static class Literals
public const string ConnectionString = "connectionString";
public const string Host = "host";
public const string Url = "url";
public const string BuildArgs = "buildArgs";
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ private static void HandleSubstitutions(Dictionary<string, Resource> resources,
case IResourceWithConnectionString resourceWithConnectionString when !string.IsNullOrEmpty(resourceWithConnectionString.ConnectionString):
resourceWithConnectionString.ConnectionString = rootNode[key]![Literals.ConnectionString]!.ToString();
break;
case DockerfileResource dockerfileResource:
{
foreach (var buildArg in dockerfileResource.BuildArgs?.Keys ?? new(new ()))
{
dockerfileResource.BuildArgs[buildArg] = rootNode[key]![Literals.BuildArgs]![buildArg].ToString();
}

break;
}
case ValueResource valueResource:
{
foreach (var resourceValue in valueResource.Values.ToList())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ public interface IBuildOptions
{
string? RuntimeIdentifier { get; set; }
List<string>? ComposeBuilds { get; set; }
bool? UseSecrets { get; set; }
}
3 changes: 3 additions & 0 deletions src/Aspirate.Shared/Models/Aspirate/AspirateState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ public class AspirateState :

[JsonIgnore]
public bool? SkipBuild { get; set; }

[JsonIgnore]
public bool? UseSecrets { get; set; }

[JsonIgnore]
public string? AspireManifest { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,40 @@ public async Task EndToEndShop_ParsesSuccessfully()
shopResource.Volumes[0].Name.Should().Be("basketcache-data");
}

[Fact]
public async Task EndToEndDockerfile_ParsesSuccessfully()
{
// Arrange
var fileSystem = new MockFileSystem();
var manifestFile = "dockerfile-with-build-args.json";
var testData = Path.Combine(AppContext.BaseDirectory, "TestData", manifestFile);
fileSystem.AddFile(manifestFile, new MockFileData(await File.ReadAllTextAsync(testData)));
var serviceProvider = CreateServiceProvider(fileSystem);

var service = serviceProvider.GetRequiredService<IManifestFileParserService>();
var inputPopulator = serviceProvider.GetRequiredKeyedService<IAction>(nameof(PopulateInputsAction));
var valueSubstitutor = serviceProvider.GetRequiredKeyedService<IAction>(nameof(SubstituteValuesAspireManifestAction));
var cachePopulator =
serviceProvider.GetRequiredKeyedService<IAction>(nameof(BuildAndPushContainersFromDockerfilesAction));

// Act
var results = await PerformEndToEndTests(manifestFile, 2, serviceProvider, service, inputPopulator, valueSubstitutor);
var state = serviceProvider.GetRequiredService<AspirateState>();
state.AspireComponentsToProcess = state.LoadedAspireManifestResources
.Where(x => x.Value.Type == AspireComponentLiterals.Dockerfile).Select(x => x.Key).ToList();
state.ContainerBuilder = "docker";
await cachePopulator.ExecuteAsync();

//Assert
var clientResource = results["client"] as DockerfileResource;
clientResource.BuildArgs["NPM_TOKEN"].Length.Should().Be(22);
var shellExecutor = serviceProvider.GetRequiredService<IShellExecutionService>();
await shellExecutor.Received(1).ExecuteCommand(Arg.Is<ShellCommandOptions>(x =>
x.Command == "docker" &&
x.ArgumentsBuilder.RenderArguments(' ').Contains($"NPM_TOKEN=\"{clientResource.BuildArgs["NPM_TOKEN"]}\"")
));
}

[Fact]
public async Task EndToEndNodeJs_ParsesSuccessfully()
{
Expand Down Expand Up @@ -251,8 +285,10 @@ private static IServiceProvider CreateServiceProvider(IFileSystem? fileSystem =
services.RegisterAspirateEssential();
services.RemoveAll<IAnsiConsole>();
services.RemoveAll<IFileSystem>();
services.RemoveAll<IShellExecutionService>();
services.AddSingleton(console);
services.AddSingleton(fileSystem);
services.AddSingleton(GetMockShellExecutionService());
services.AddSingleton<ISecretProvider, SecretProvider>();

return services.BuildServiceProvider();
Expand All @@ -268,4 +304,16 @@ private static void EnterPasswordInput(TestConsole console, string password)
console.Input.PushTextWithEnter(password);
console.Input.PushKey(ConsoleKey.Enter);
}

private static IShellExecutionService GetMockShellExecutionService()
{
var mock = Substitute.For<IShellExecutionService>();
mock.IsCommandAvailable(Arg.Any<string>()).Returns(new CommandAvailableResult()
{
FullPath = "",
IsAvailable = true,
});
mock.ExecuteCommand(Arg.Any<ShellCommandOptions>()).Returns(new ShellCommandResult(true,"","",0));
return mock;
}
}
30 changes: 30 additions & 0 deletions tests/Aspirate.Tests/TestData/dockerfile-with-build-args.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"resources": {
"npmToken": {
"type": "parameter.v0",
"value": "{npmToken.inputs.value}",
"inputs": {
"value": {
"type": "string",
"secret": true,
"default": {
"generate": {
"minLength": 22
}
}
}
}
},
"client": {
"type": "dockerfile.v0",
"path": "../aspirate-buildargs-bug.Client/Dockerfile",
"context": "../aspirate-buildargs-bug.Client",
"buildArgs": {
"NPM_TOKEN": "{npmToken.value}"
},
"env": {
"NODE_ENV": "development"
}
}
}
}
Loading