diff --git a/x-pack/plugins/fleet/server/services/package_policy.ts b/x-pack/plugins/fleet/server/services/package_policy.ts index 8366434480e49..aaf158e56dba5 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.ts @@ -242,31 +242,47 @@ class PackagePolicyClientImpl implements PackagePolicyClient { force?: true; } ): Promise { - const agentPolicyIds = new Set(packagePolicies.map((pkgPol) => pkgPol.policy_id)); + const agentPolicyIds = new Set(packagePolicies.map((pkgPolicy) => pkgPolicy.policy_id)); for (const agentPolicyId of agentPolicyIds) { await validateIsNotHostedPolicy(soClient, agentPolicyId, options?.force); } + const packageInfos = await getPackageInfoForPackagePolicies(packagePolicies, soClient); + const isoDate = new Date().toISOString(); // eslint-disable-next-line @typescript-eslint/naming-convention const { saved_objects } = await soClient.bulkCreate( - packagePolicies.map((packagePolicy) => { + await pMap(packagePolicies, async (packagePolicy) => { const packagePolicyId = packagePolicy.id ?? uuid.v4(); const agentPolicyId = packagePolicy.policy_id; - const inputs = packagePolicy.inputs.map((input) => + let inputs = packagePolicy.inputs.map((input) => assignStreamIdToInput(packagePolicyId, input) ); const { id, ...pkgPolicyWithoutId } = packagePolicy; + let elasticsearch: PackagePolicy['elasticsearch']; + if (packagePolicy.package) { + const pkgInfo = packageInfos.get( + `${packagePolicy.package.name}-${packagePolicy.package.version}` + ); + + inputs = pkgInfo + ? await _compilePackagePolicyInputs(pkgInfo, packagePolicy.vars || {}, inputs) + : inputs; + + elasticsearch = pkgInfo?.elasticsearch; + } + return { type: SAVED_OBJECT_TYPE, id: packagePolicyId, attributes: { ...pkgPolicyWithoutId, inputs, + elasticsearch, policy_id: agentPolicyId, revision: 1, created_at: isoDate, @@ -1457,6 +1473,36 @@ export interface NewPackagePolicyWithId extends NewPackagePolicy { export const packagePolicyService: PackagePolicyClient = new PackagePolicyClientImpl(); +async function getPackageInfoForPackagePolicies( + packagePolicies: NewPackagePolicyWithId[], + soClient: SavedObjectsClientContract +) { + const pkgInfoMap = new Map(); + + packagePolicies.forEach(({ package: pkg }) => { + if (pkg) { + pkgInfoMap.set(`${pkg.name}-${pkg.version}`, pkg); + } + }); + + const resultMap = new Map(); + + await pMap(pkgInfoMap.keys(), async (pkgKey) => { + const pkgInfo = pkgInfoMap.get(pkgKey); + if (pkgInfo) { + const pkgInfoData = await getPackageInfo({ + savedObjectsClient: soClient, + pkgName: pkgInfo.name, + pkgVersion: pkgInfo.version, + }); + + resultMap.set(pkgKey, pkgInfoData); + } + }); + + return resultMap; +} + export function updatePackageInputs( basePackagePolicy: NewPackagePolicy, packageInfo: PackageInfo,