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

hostname_script无法设置EC2实例名称问题求助

问题分析与解决方案

核心问题

你将自定义主机名脚本放在了JSON结构体的hostname_script字段中,但AWS的cloud-init不会自动识别并执行该字段内的内容,这是脚本未运行、主机名未修改的根本原因。

解决方法

方法一:直接传递Shell脚本作为user_data

如果仅需执行主机名设置逻辑,可直接将脚本作为user_data内容传递,无需JSON包裹:

user_data = <<-EOF
#!/bin/bash
HOSTNAME=$(printf '%02d' $((each.key + 1))).${local.cluster_name}.${local.region}
IP=$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)

# 先配置cloud-init保留主机名,避免后续被覆盖
echo 'preserve_hostname: true' >> /etc/cloud/cloud.cfg

# 执行主机名设置
hostnamectl set-hostname $HOSTNAME
echo $HOSTNAME > /etc/hostname

# 更新hosts文件
echo "$IP $HOSTNAME" >> /etc/hosts
EOF

方法二:使用cloud-config规范格式(推荐)

cloud-init原生支持cloud-config格式,可直接配置主机名参数,同时保留你需要的其他配置项:

user_data = jsonencode({
  # 原生配置主机名
  hostname = "${format("%02d", each.key + 1)}.${local.cluster_name}.${local.region}"
  preserve_hostname = true

  # 保留你原有配置字段
  cluster_name            = local.cluster_name,
  node_hostname_tmpl      = "{node_num:02d}.${local.cluster_name}.${local.hosting_env_dns_internal_zone_name}",
  node_num                = each.key + 1,
  cluster_cfg             = var.data_fabric_cluster_node_bootstrap_cfg,
  data_block_dev_paths    = var.data_fabric_cluster_node_data_block_devs.paths,
  mapr_password           = data.aws_secretsmanager_secret_version.mapr_password_secret_ver.secret_string,
  nodes_ssh_host_pubkeys  = local.host_pub_key_concatenated,
  nodes_ssh_user_pubkeys  = local.user_pub_key_concatenated,
  ssh_host_privkey        = aws_secretsmanager_secret_version.host_pri_key_ver[each.key].secret_string,
  ssh_host_pubkey         = aws_secretsmanager_secret_version.host_pub_key_ver[each.key].secret_string,
  ssh_user_privkey        = aws_secretsmanager_secret_version.user_pri_key_ver[each.key].secret_string,
  ssh_user_pubkey         = aws_secretsmanager_secret_version.user_pub_key_ver[each.key].secret_string,

  # 额外执行hosts文件更新逻辑
  runcmd = [
    "IP=$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)",
    "echo \"$IP ${format("%02d", each.key + 1)}.${local.cluster_name}.${local.region}\" >> /etc/hosts"
  ]
})

额外检查项

  • 查看EC2实例内的cloud-init日志(/var/log/cloud-init.log和/var/log/cloud-init-output.log),可确认脚本是否执行及错误原因。
  • 确保实例的IAM权限允许访问元数据服务(默认允许,若有自定义安全组需放行169.254.169.254的HTTP请求)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:05:21