使用EC2 Image Builder制作RHEL8镜像时authorized_keys缺失问题
问题描述
使用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
相关产品推荐
相关产品推荐

