You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用EC2 Image Builder制作RHEL8镜像时authorized_keys缺失问题

AWS EC2 Image Builder RHEL8镜像:authorized_keys未出现在生成AMI中的排查与修复

问题描述

使用AWS EC2 Image Builder创建RedHat 8自定义镜像时,在配方中创建了ansible用户,并通过S3下载authorized_keys和/etc/sudoers.d/ansible文件。其中sudoers文件能正常复制到生成的AMI中,但authorized_keys未出现在/home/ansible/.ssh/路径下。CloudWatch日志显示配方执行无错误,文件已完成下载。

使用的配方如下:

name: USER-Ansible
description: Creazione e configurazione dell'utente ansible
schemaVersion: 1.0
phases:
  - name: build
    steps:
      - name: UserCreate
        action: ExecuteBash
        inputs:
          commands:
            - groupadd -g 2004 ux
            - useradd -u 4134 -g ux -c "AWX Ansible" -m -d /home/ansible ansible
            - mkdir /home/ansible/.ssh
      - name: FilesDownload
        action: S3Download
        inputs:
          - source: s3://[REDACTED]/authorized_keys
            destination: /home/ansible/.ssh/authorized_keys
            expectedBucketOwner: [REDACTED]
            overwrite: false
          - source: s3://[REDACTED]/ansible
            destination: /etc/sudoers.d/ansible
            expectedBucketOwner: [REDACTED]
            overwrite: false
      - name: FilesConfiguration
        action: ExecuteBash
        inputs:
          commands:
            - chown ansible:ux /home/ansible/.ssh/authorized_keys; chmod 600 /home/ansible/.ssh/authorized_keys
            - chown ansible:ux /home/ansible/.ssh; chmod 700 /home/ansible/.ssh
            - chown root:root /etc/sudoers.d/ansible; chmod 440 /etc/sudoers.d/ansible 

排查与修复方案

1. 修复SELinux上下文问题

RedHat 8默认启用SELinux,/home/ansible/.ssh目录及其中的文件需要特定的SELinux上下文才能被SSH服务识别,且镜像打包时不会被过滤。S3下载的文件可能继承了错误的上下文(如default_t),导致最终AMI中无法正常保留。

在FilesConfiguration步骤中添加SELinux上下文恢复命令:

- name: FilesConfiguration
  action: ExecuteBash
  inputs:
    commands:
      - chown ansible:ux /home/ansible/.ssh/authorized_keys; chmod 600 /home/ansible/.ssh/authorized_keys
      - chown ansible:ux /home/ansible/.ssh; chmod 700 /home/ansible/.ssh
      - restorecon -Rv /home/ansible/.ssh/  # 恢复正确的SELinux上下文
      - chown root:root /etc/sudoers.d/ansible; chmod 440 /etc/sudoers.d/ansible 

2. 验证文件状态(可选但推荐)

添加日志输出命令,确认文件在构建实例中确实存在且权限、上下文正确,便于后续排查:

- name: FilesConfiguration
  action: ExecuteBash
  inputs:
    commands:
      - ls -lZ /home/ansible/.ssh/  # 输出文件列表及SELinux上下文
      - chown ansible:ux /home/ansible/.ssh/authorized_keys; chmod 600 /home/ansible/.ssh/authorized_keys
      - chown ansible:ux /home/ansible/.ssh; chmod 700 /home/ansible/.ssh
      - restorecon -Rv /home/ansible/.ssh/
      - chown root:root /etc/sudoers.d/ansible; chmod 440 /etc/sudoers.d/ansible 

3. 检查后续步骤是否存在清理操作

确认Image Builder流水线的其他配方步骤(如test或post-build阶段)是否有删除authorized_keys的操作,避免文件被意外清理。

内容的提问来源于stack exchange,提问作者stressedmana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 06:15:33