根据 ec2 发行版动态设置 ansible-playbook 用户变量 [英] set ansible-playbook user variable dynamically based on the ec2 distros

查看:18
本文介绍了根据 ec2 发行版动态设置 ansible-playbook 用户变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 ansible playbook,它通过一组 AWS EC2 主机并安装一些基本包.在剧本可以执行任何任务之前,剧本需要使用正确的 user: {{ userXXX }} 登录到每个主机(2 种发行版 AWS Linux 或 Ubuntu),这是我的部分不太确定如何传入正确的用户登录名,它可能是 ec2-userubuntu.

I'm creating an ansible playbook that goes through a group of AWS EC2 hosts and install some basic packages. Before the playbook can execute any tasks, the playbook needs to login to each host (2 type of distros AWS Linux or Ubuntu) with correct user: {{ userXXX }} this is the part that I'm not too sure how to pass in the correct user login, it would be either ec2-user or ubuntu.

   - name: setup package agent 
  hosts: ec2_distros_hosts


  user: "{{ ansible_user_id }}"

  roles:
    - role: package_agent_install

我假设 ansible_user_id 可以基于 ansible 的保留变量工作,但这里并非如此.我不想为不同的发行版创建 2 个单独的剧本,是否有一个优雅的解决方案来动态查找用户登录并用作 user: ?

I was assuming ansible_user_id would work based of the reserved variable from ansible but that is not the case here. I don't want to create 2 separate playbook for different distros, is there an elegant solution to dynamically lookup user login and used as the user: ?

这是未知用户的失败 cmd ansible-playbook -i inventory/ec2.py agent.yml

Here is the failed cmd with unknown user ansible-playbook -i inventory/ec2.py agent.yml

推荐答案

您有多种方法来完成您的任务:

You have several ways to accomplish your task:

如果你有,你可以在你的剧本中使用 user: ansible_user.

If you have one, you can use user: ansible_user in your playbook.

您可以为每个 ec2 主机创建一个标签(例如 login_name)并在其中指定用户.对于 Ubuntu 主机 - ubuntu,对于 AWS Linux 主机 - ec2-user.这样做之后,您可以在您的剧本中使用 user: "{{ec2_tag_login_name}}" - 这将从主机的 login_name 标签中获取用户名.

You can create a tag (e.g. login_name) for every ec2 host and specify user in it. For Ubuntu hosts – ubuntu, for AWS Linux hosts – ec2-user. After doing so, you can use user: "{{ec2_tag_login_name}}" in your playbook – this will take username from login_name tag of the host.

似乎没有像样的方法可以从 AMI 获取确切的平台名称,但您可以使用以下方法:

It seems there is no decent way to get exact platform name from AMI, but you can use something like this:

image_name = getattr(conn.get_image(image_id=getattr(instance,'image_id')),'name')
login_name = 'user'
if 'ubuntu' in image_name:
    login_name = 'ubuntu'
elif 'amzn' in image_name:
    login_name = 'ec2-user'
setattr(instance, 'image_name', image_name)
setattr(instance, 'login_name', login_name)

ec2.py 中的 self.add_instance(instance, region) 之前以相同的缩进粘贴此代码.它获取图像名称并做一些猜测工作来定义 login_name.然后你可以在你的剧本中使用 user: "{{ec2_login_name}}".

Paste this code just before self.add_instance(instance, region) in ec2.py with the same indentation. It fetches image name and do some guess work to define login_name. Then you can use user: "{{ec2_login_name}}" in your playbook.

这篇关于根据 ec2 发行版动态设置 ansible-playbook 用户变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆