Monkey

Think! And Think Again


  • 首页

  • 分类

  • 关于

  • 归档

  • 标签

  • 站点地图

  • 公益404

  • 搜索

未命名

发表于 2017-05-23 |

ansible 变量提示 交互式 输入变量

执行到这里之后,会出现 交互式窗口 让你输入变量

$ansible-playbook prompts.yml
Enter password:
Product release version: 456
Enter password2:
confirm Enter password2:

vars_prompt:

- name: "some_password"
  prompt: "Enter password"
  private: yes

- name: "release_version"
  prompt: "Product release version"
  default: "my_default_version"
  private: no

- name: "my_password2"
  prompt: "Enter password2"
  private: yes
  encrypt: "md5_crypt" 
  confirm: yes
  salt_size: 7
  salt: "foo" 

this is just a simple example to show that vars_prompt works, but

you might ask for a tag to use with the git module or perhaps

a package version to use with the yum module.

tasks:

  • name: imagine this did something interesting with $release_version
    action: shell echo foo >> /tmp/$release_version-alpha

  • name: look we crypted a password
    action: shell echo my password is $my_password2

未命名

发表于 2017-05-23 |

把表达式 当成变量存储 ,only_if 动作 去解析 执行

ansible 中变量 可以 组合

- role: foo
  param1: '{{ foo }}'
  param2: '{{ some_var1 + "/" + some_var2 }}'
  when: ansible_os_family == 'RedHat'

SHA e6406fa5

1
2
3
4
5
6
7
8
9
10
11
vars:
favcolor: "red"
ssn: 8675309
is_favcolor_blue: "'$favcolor' == 'blue'"
# is_centos: "'$facter_operatingsystem' == 'CentOS'"
tasks:
- name: "do this if my favcolor is blue"
action: shell /bin/false
only_if: '$is_favcolor_blue'

实现方式

这种神奇的方式,在ansible中是这样实现的

  1. 调用double_template 对变量进行两层替换
  2. 对替换的结果 执行eval

runner.py v0.0.2 中

1
2
3
4
5
6
7
8
def _execute_module(self, conn, tmp, remote_module_path, args,
async_jid=None, async_module=None, async_limit=None):
''' runs a module that has already been transferred '''
inject = self.setup_cache.get(conn.host,{})
conditional = utils.double_template(self.conditional, inject)
if not eval(conditional):
return [ utils.smjson(dict(skipped=True)), None, 'skipped' ]

#host file
[staging]
staging.myproject.com nickname=staging vm=0 branch=develop

#playbook
vars:
favcolor: “red”
dog: “fido”
cat: “whiskers”
ssn: 8675309

  • name: Upload SSH key.
    copy: src=key dest=/home/.ssh/id_rsa mode=0600
    only_if: “$vm == 0”

  • name: “do this if my favcolor is blue, and my dog is named fido”
    action: shell /bin/false
    when_string: $favcolor == ‘blue’ and $dog == ‘fido’

These are the types of when statemnets available

when_set: $variable_name

when_unset: $variable_name

when_str: $x == “test”

when_int: $y > 2

when_float: $z => 2.3

未命名

发表于 2017-05-23 |
  1. 使用普通用户连接,然后自动切换为root 执行操作

方法一: 不知道root账户密码的情况,使用sudo
在hosts中配置
[tests]
monkey_1 ansible_host=xx.xx.xx.xx ansible_user=fonsview ansible_ssh_pass=”fonsview用户密码” ansible_port=50000 ansible_sudo_user=”“ ansible_sudo_pass=”“

在playbook中设置become 参数

  • hosts: tests
    become: true
    become_user: root (可省略,默认用户root)
    become_method: sudo (可省略,默认切换方式sudo)
    gather_facts: no
    tasks:

    • name: “查询我是哪个用户”
      command: whoami
      register: xx

    • debug: var=xx

方法二: 知道root账户密码的情况
在hosts中配置
[tests]
monkey_1 ansible_host=xx.xx.xx.xx ansible_user=fonsview ansible_ssh_pass=”fonsview用户密码” ansible_port=50000 ansible_become_pass=”root账户密码”

在playbook中设置become 参数

  • hosts: tests
    become: true
    become_user: root (可省略,默认用户root)
    become_method: su
    gather_facts: no
    tasks:

    • name: “查询我是哪个用户”
      command: whoami
      register: result

    • debug: var=result

http://stackoverflow.com/questions/31408017/ansible-with-a-bastion-host-jump-box

  1. ansible的跨主机 操作实现 A -> B -> C ansible可直接向C发送命令

主机配置
[gatewayed]
foo ansible_host=192.0.2.1
bar ansible_host=192.0.2.2
创建 group_vars/gatewayed.yml 文件,包含如下内容
ansible_ssh_common_args: ‘-o ProxyCommand=”ssh -W %h:%p -q user@gateway.example.com”‘

这样ansible 操作属于gatewayed组的主机,可自动先登录跳板主机,然后再跳转到 生产主机 执行命令

未命名

发表于 2017-05-23 |

ansible 开发模式

使用环境变量指定参数,让ansible在指定目录运行

  1. 下载ansible 源码
    git clone ansible

  2. 引入环境变量
    source ./hacking/env-setup

  3. 查看自己的环境
    which ansible

可以看到 ansible 是自己的环境

  1. 使用test-module 运行 自定义 mode

python ./hacking/test-module ./library/command /bin/sleep 3

未命名

发表于 2017-05-23 |

ansible 模板中字符串格式化

ansible 中引用jinja2 中的字符串格式化format_advanced() ,来做格式化
而 format_advanced() 来源于python自带的string 中的 formatstrings方法

‘{2}, {1}, {0}’.format(‘a’, ‘b’, ‘c’)
‘c, b, a’

template –》model

environment = jinja2.Environment()

def format_advanced(fmt, data):

# jinja2 filter to use advanced python string formatting
# e.g, {{ "{0} {1} {2}"|format_advanced(['a', 'b', 'c']) }}
# see http://docs.python.org/library/string.html#formatstrings
if isinstance(data, collections.Mapping):
    return fmt.format(**data)
elif isinstance(data, collections.Sequence):
    return fmt.format(*data)
else:
    return data

environment.filters[‘format_advanced’] = format_advanced

template = environment.from_string(source)

未命名

发表于 2017-05-23 |

开启pipline


  • hosts: gatewayed
    #become: true

    become_user: root

    #become_method: su

    remote_user: root

    gather_facts: no
    vars:

    ansible_ssh_pipelining: yes
    

    tasks:

    • name: “查询我是哪个用户”
      command: whoami
      register: xx

    • debug: var=xx

    • name: “创建一个文件”
      copy: src=site.yml dest=/tmp/ntp2.conf

性能对比

如上小任务,

不开启pipline : 26.971 total
开启pipline:7.475 total

问题

貌似 在pipelining 模式中无法进行 su 切换为root用户
会报错:standard in must be a tty

解决办法:

  1. vim /etc/ssh/sshd_config
    #PermitRootLogin no
  2. 使用root账户 操作,不使用 su切换

删除requiretty

  • 手动

    开启pipline的问题 在rhel6 中要关闭requiretty,注释或删除

    cat /etc/sudoers | grep requiretty
    #Defaults requiretty

  • 自动

  • hosts: foo
    pipelining: no
    tasks:
    • lineinfile: dest=/etc/sudoers line=’Defaults requiretty’ state=absent
      sudo_user: root

参考

参考

未命名

发表于 2017-05-23 |

ansible性能优化

如下配置 可以带来性能的提升

[ssh_connection]

if uncommented, sets the ansible ssh arguments to the following. Leaving off ControlPersist

will result in poor performance, so use transport=paramiko on older platforms rather than

removing it

ssh_args=-o ControlMaster=auto -o ControlPersist=1h -o ControlPath=~/.ssh/sockets/ansible-ssh-%h-%p-%r

#ssh_args=-o PasswordAuthentication=no -o ControlMaster=auto -o ControlPersist=1h -o ControlPath=~/.ssh/sockets/ansible-ssh-%h-%p-%r

PasswordAuthentication=no 明确指定不使用密码认证

the following makes ansible use scp if the connection type is ssh (default is sftp)

#scp_if_ssh=True

下面是主机配置,推荐上面直接在ansible.cfg中配置
$ vim .ssh/config
  Host *
  Compression yes
  ServerAliveInterval 60
  ServerAliveCountMax 5
  ControlMaster auto
  ControlPath ~/.ssh/sockets/%r@%h-%p
  ControlPersist 4h

未命名

发表于 2017-05-23 |
- name: Check to see if Plone 5 is running
  uri:
    url: http://127.0.0.1:5081/Plone
    method: GET
    status_code: 200

- name: Check to see if Plone 4.3.x is running
  uri:
    url: http://127.0.0.1:4081/Plone
    method: GET
    status_code: 200

未命名

发表于 2017-05-23 |

ansible 的灵活性

ansible的灵活性在于

  1. 本地模块 可以用lookup
  2. 远程模块 可以写自定义modul
  3. 变量,可以自己写fact,冲cmdb 等获取变量信息

未命名

发表于 2017-05-23 |

ansible 文件/目录找寻规则

主要是 path_dwim 这里定义的

如果不是 依‘/’ ‘~/‘ 这样开头的 都走相对路径模式
由 basedir + given 组合路径

def path_dwim(basedir, given):
‘’’ make relative paths work like folks expect ‘’’
if given.startswith(“/“):
return given
elif given.startswith(“~/“):
return os.path.expanduser(given)
else:
return os.path.join(basedir, given)

123…21
kikiyou

kikiyou

越努力越幸运

204 日志
20 标签
GitHub Quora 知乎 豆瓣 果壳 Facebook Twitter 新浪微博
Links
  • Awesome
© 2015 - 2017 kikiyou
由 Hexo 强力驱动
主题 - NexT.Mist