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

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

问题描述

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

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 -iventory / 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天全站免登陆