ansible sudo: 对不起,你必须有一个 tty 到 运行 sudo

ansible sudo: sorry, you must have a tty to run sudo

当我设置云形成环境时,我需要 运行 Vagrant boxes 和 aws 上的剧本。

在 Vagrant 文件中,我使用 ansible-local 并且一切正常

name: Setup Unified Catalog Webserver  
    hosts: 127.0.0.1  
    connection: local  
  become: yes  
  become_user: root
  roles: generic

然而,当我在 AWS 中创建实例时,ansible 剧本失败并出现错误:
sudo: sorry, you must have a tty to run sudo
发生这种情况是因为它是 运行 作为 root 并且它没有 tty。但我不知道如何在不更改 /etc/sudoers 以允许 !requiretty

的情况下修复它

我可以在 ansible.cfg 或我的 Cloud Formation 模板中设置任何标志吗?

  "#!/bin/bash\n", "\n", "   
 echo 'Installing Git'\n","  
  yum --nogpgcheck -y install git ansible htop nano wget\n",
 "wget https://s3.eu-central-1.amazonaws.com/XXX -O /root/.ssh/id_rsa\n", 
"chmod 600 /root/.ssh/id_rsa\n", 
"ssh-keyscan 172.31.7.235 >> /root/.ssh/known_hosts\n",
 "git clone git@172.31.7.235:something/repo.git /root/repo\n", 
"ansible-playbook /root/env/ansible/test.yml\n

我自己找到了以下解决方案:
1. 使用 sed 运行 剧本更改 /etc/sudoers 中的要求并将其改回。

 "#!/bin/bash\n", "\n", "  
 echo 'Installing Git'\n"," 
 yum --nogpgcheck -y install git ansible htop nano wget\n",  
 "wget https://s3.eu-central-1.amazonaws.com/xx/ansible -O /root/.ssh/id_rsa\n",  
 "chmod 600 /root/.ssh/id_rsa\n",   
  "ssh-keyscan 172.31.9.231 >> /root/.ssh/known_hosts\n",   
  "git clone git@172.31.5.254:somerepo/dev.git /root/dev\n",   
  "sed -i 's/Defaults    requiretty/Defaults    !requiretty/g' /etc/sudoers\n", 
  "\n", 
  "ansible-playbook /root/dev/env/ansible/uk.yml\n",   
  "\n",   
  "sed -i 's/Defaults    !requiretty/Defaults    requiretty/g' /etc/sudoers\n"   

或 2.在ansible playbook中指定变量:

 - name: Setup 
 hosts: 127.0.0.1
 connection: local
 sudo: {{ require_sudo }}
 roles:
    - generic
AWS Cloud Formation 模板中的

运行 为

   "ansible-playbook -e require_sudo=False /root/dev/env/ansible/uk.yml\n"  

对于 ansible.cfg 中的 Vagrant 可以指定

  require_sudo=True
  1. 另外在CF模板中可以识别谁是运行ning和传递变量

    ansible-playbook -e$(id -u |egrep '^0$' > /dev/null && require_sudo=False || require_sudo=True; echo "require_sudo=$require_sudo") /apps/ansible/uk.yml

我可以通过在 ansible.cfg 中设置 transport = paramiko 配置来解决这个问题。

如果您需要特定的连接:paramiko 仅在一个剧本中与 ansible.cfg 中的全局配置,您可以在剧本中添加 connection: paramiko,例如:

- name: Run checks after deployments
  hosts: all
  # https://github.com/paramiko/paramiko/issues/1369
  connection: paramiko
  gather_facts: True