我正在创建一个首先创建新用户名的剧本。然后我想跑#34; moretasks.yml"作为我刚刚创建的新用户。目前,我正在为每项任务设置remote_user。有没有办法可以为整套任务设置一次?我似乎无法找到这方面的例子,也没有试图将remote_user转移到帮助之外。
以下是main.yml:
---
- name: Configure Instance(s)
hosts: all
remote_user: root
gather_facts: true
tags:
- config
- configure
tasks:
- include: createuser.yml new_user=username
- include: moretasks.yml new_user=username
- include: roottasks.yml #some tasks unrelated to username.
moretasks.yml:
---
- name: Task1
copy:
src: /vagrant/FILE
dest: ~/FILE
remote_user: "{{newuser}}"
- name: Task2
copy:
src: /vagrant/FILE
dest: ~/FILE
remote_user: "{{newuser}}"
答案 0 :(得分:8)
首先,您肯定希望使用sudo_user
(远程用户是登录的用户,sudo_user
是执行任务的用户。)
在您的情况下,您希望以另一个用户(之前创建的用户)执行任务:
- include: moretasks.yml
sudo: yes
sudo_user: "{{ newuser }}"
并且这些任务将以{{newuser}}执行(不要忘记引号)
备注:在大多数情况下,您应该将remote_user
视为主机参数。允许用户登录计算机并且具有足够的权限来执行操作。对于操作内容,您应该使用sudo
/ sudo_user
答案 1 :(得分:7)
您可以将其拆分为单独的剧本吗? (剧本可以包含多个剧本)
---
- name: PLAY 1
hosts: all
remote_user: root
gather_facts: true
tasks:
- include: createuser.yml new_user=username
- include: roottasks.yml #some tasks unrelated to username.
- name: PLAY 2
hosts: all
remote_user: username
gather_facts: false
tasks:
- include: moretasks.yml new_user=username
有一个问题使用单独的游戏:你不能在第一次游戏中使用register:
或set_fact:
设置的变量来做第二次游戏中的事情 (这个陈述并不完全正确,变量在hostvars
中可用,但我建议不要在角色之间使用变量)。像group_vars和host_vars这样的定义变量可以正常工作。
我想提出的另一个提示是使用roles
http://docs.ansible.com/playbooks_roles.html进行调查。虽然一开始可能看起来更复杂,但重用它们要容易得多(因为你似乎正在使用" createuser.yml")。看看你想要达到的事物的类型,包括所有的东西'路径不会持续太长时间。
答案 2 :(得分:0)
与您的问题内联。希望能帮助到你。更新我的Playbooks for Ansible 2.5支持Cisco IOS network_cli连接
使用ansible-vault创建的凭据文件:auth / secrets.yml
---
creds:
username: 'ansible'
password: 'user_password'
剧本:
---
- hosts: ios
gather_facts: yes
connection: network_cli
become: yes
become_method: enable
ignore_errors: yes
tasks:
- name: obtain login credentials
include_vars: auth/secrets.yml
- name: Set Username/ Password
set_fact:
remote_user: "{{ creds['username'] }}"
ansible_ssh_pass: "{{ creds['password'] }}"
- name: Find info for "{{ inventory_hostname }}" via ios_facts
ios_facts:
gather_subset: all
register: hardware_fact
在没有auth / secrets.yml的情况下运行playbook:
ansible-playbook -u ansible -k playbook.yml -l inventory_hostname