diff --git a/apps/ops/inventory.py b/apps/ops/inventory.py index f8013d853..f3de03210 100644 --- a/apps/ops/inventory.py +++ b/apps/ops/inventory.py @@ -76,7 +76,7 @@ class JMSInventory(JMSBaseInventory): write you own inventory, construct you inventory, user_info is obtained from admin_user or asset_user """ - def __init__(self, assets, run_as_admin=False, run_as=None, become_info=None): + def __init__(self, assets, run_as_admin=False, run_as=None, become_info=None, system_user=None): """ :param assets: assets :param run_as_admin: True 是否使用管理用户去执行, 每台服务器的管理用户可能不同 @@ -86,6 +86,7 @@ class JMSInventory(JMSBaseInventory): self.assets = assets self.using_admin = run_as_admin self.run_as = run_as + self.system_user = system_user self.become_info = become_info host_list = [] @@ -104,18 +105,25 @@ class JMSInventory(JMSBaseInventory): def get_run_user_info(self, host): from assets.backends import AssetUserManager - if self.run_as is None: + if not self.run_as and not self.system_user: return {} + asset_id = host.get('id', '') + asset = self.assets.filter(id=asset_id).first() + if not asset: + logger.error('Host not found: ', asset_id) + + if self.system_user: + self.system_user.load_asset_special_auth(asset=asset, username=self.run_as) + return self.system_user._to_secret_json() + try: - asset = self.assets.get(id=host.get('id')) manager = AssetUserManager() run_user = manager.get_latest(username=self.run_as, asset=asset, prefer='system_user') + return run_user._to_secret_json() except Exception as e: logger.error(e, exc_info=True) return {} - else: - return run_user._to_secret_json() class JMSCustomInventory(JMSBaseInventory): diff --git a/apps/ops/models/command.py b/apps/ops/models/command.py index 12ffdddd1..5bf808dce 100644 --- a/apps/ops/models/command.py +++ b/apps/ops/models/command.py @@ -37,7 +37,7 @@ class CommandExecution(OrgModelMixin): username = self.user.username else: username = self.run_as.username - inv = JMSInventory(self.hosts.all(), run_as=username) + inv = JMSInventory(self.hosts.all(), run_as=username, system_user=self.run_as) return inv @lazyproperty