Blog

aligned属性(GCC)

Content #

aligned属性规定变量或者结构体成员的最小对齐格式,以字节为单位。

struct qib_user_info {
    __u32 spu_userversion;
    __u64 spu_base_info;
} __aligned(8);

编译器以8字节对齐的方式来分配qib_user_info这个数据结构。

From #

const属性会让编译器只调用该函数一次

Content #

const 属性会让编译器只调用该函数一次,以后再调用时只需要返回第一次结果即可,从而提高效率。

static inline u32 __attribute_const__ read_cpuid_cachetype(void)
{
    return read_cpuid(CTR_EL0);
}

From #

奔跑吧Linux内核——入门篇

__attribute__((noreturn))

Content #

noreturn属性通知编译器,该函数从不返回值,这让编译器消除了不必要的警告信息。比如die函数,该函数不会返回。

void __attribute__((noreturn)) die(void);

From #

creates和removes参数

creates,removes参数 #

只要条件允许,ansible模块会尽量避免修改主机的东西。然而,改变有时是不可避免的。为了帮助ansible更好地保证幂等性,可以通过添加creates或 removes参数。

如果有creates参数,那么在该参数指定的文件已经存在的情况下,命令不会被执行。removes参数正好与之相反,如:

ansible machinename -m command -a 'rm -rf /tmp/testing removes=/tmp/testing'

用file模块来实现,可以不用removes参数。

ansible machinename -m file -a 'path=/tmp/testing state=absent'

From #

netplan中无法为动态接口添加路由

Content #

netplan中配置路由时,不能使用dev关键词。动态生成的接口,如tun0,在配置路由时无法指定。netplan是自动决定使用哪个网络接口的,一般会是系统启动后看到的接口。

From #

jinja2空格控制

Content #

ens3:
    dhcp4: true
    match:
        macaddress: "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['macaddress'] }}"
    mtu: 1500
    set-name: ens3
    routing-policy:
        {% for server in servers -%}
        - from: {{ server.ipv4 }}
            table: table_{{ server.ipv4.split('.')[-1]}}
        {% endfor %}

    routes:
        {% for server in servers -%}
        - to: default
            via: {{ tun1_gateway }}
            dev: tun1
            table: table_{{ server.ipv4.split('.')[-1]}}
        {% endfor %}

模板的缩进位置会影响到生成的文本的缩进。使用"-%}“会移除右大括号后所有的空白字符。同样,”{%-“则会移除左大括号之前的空白字符。 endfor的右侧若使用减号,则会导致后续行的缩进出错。

From #

jinja2文档中查阅 Template Designer Documentation.

command与shell的区别

Content #

command模块 #

  1. command模块用于在目标主机上执行单个命令。
  2. 不会启动一个新的shell,而是直接执行命令。因此,不支持使用通配符、管道、重定向等shell特性。
  3. 可以通过该模块的creates参数指定一个文件路径,如果该文件存在,则命令将被跳过。

shell模块 #

  1. shell模块用于在目标主机上执行命令,并在一个新的shell中运行命令。
  2. 支持使用通配符、管道、重定向等shell特性。
  3. 由于启动了新的shell,因此需要格外小心防范潜在的安全风险,如注入攻击。

From #

部署nodejs应用(Ansible)

Content #

Install app #

  • name: Ensure nodejs app file: “path={{ node_apps_location }}” state=directory"
  • name: Copy nodejs app copy: “src=app dest={{ node_apps_location }}”
  • name: Install npm package npm: “path={{ node_apps_location }}/app”

Run with forever #

  • name: Get running nodejs app list command: forever list register: forever_list changed_when: false
  • name: start nodejs app command: “forever start {{ node_apps_location }}/app/app.js” when: “forever_list.stdout.find(’{{ node_apps_location }}/app/app.js’) == -1”
changed_when: false

用于告诉ansible,本任务没有对主机造成影响(改变文件或安装软件等)。

...

从一台远程主机上获取另一台远程主机的变量信息

Content #

有些时候,我们在运行Ansible任务时,可能需要从一台远程主机上获取另一台远程主机的变量信息,有一个神奇的变量hostvars可以帮我们实现这一需求。变量hostvars包含了指定主机上所定义的所有变量。

比如,我们想获取host1上的变量admin_user的内容,在任意主机上直接使用下面这行代码即可。

{{ hostvars['host1']['admin_user'] }}

From #

Ansible权威指南